Correct error in recent smoothview edits
[blender.git] / source / blender / editors / space_view3d / view3d_edit.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_edit.c
28  *  \ingroup spview3d
29  */
30
31 #include <string.h>
32 #include <stdio.h>
33 #include <math.h>
34 #include <float.h>
35
36 #include "DNA_armature_types.h"
37 #include "DNA_curve_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_scene_types.h"
40
41 #include "MEM_guardedalloc.h"
42
43 #include "BLI_blenlib.h"
44 #include "BLI_kdopbvh.h"
45 #include "BLI_math.h"
46 #include "BLI_utildefines.h"
47
48 #include "BKE_armature.h"
49 #include "BKE_camera.h"
50 #include "BKE_context.h"
51 #include "BKE_font.h"
52 #include "BKE_library.h"
53 #include "BKE_object.h"
54 #include "BKE_paint.h"
55 #include "BKE_report.h"
56 #include "BKE_scene.h"
57 #include "BKE_screen.h"
58 #include "BKE_action.h"
59 #include "BKE_depsgraph.h" /* for ED_view3d_camera_lock_sync */
60
61
62 #include "BIF_gl.h"
63 #include "BIF_glutil.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "RNA_access.h"
69 #include "RNA_define.h"
70
71 #include "ED_armature.h"
72 #include "ED_particle.h"
73 #include "ED_keyframing.h"
74 #include "ED_screen.h"
75 #include "ED_transform.h"
76 #include "ED_mesh.h"
77 #include "ED_view3d.h"
78
79 #include "UI_resources.h"
80
81 #include "PIL_time.h" /* smoothview */
82
83 #include "view3d_intern.h"  /* own include */
84
85 bool ED_view3d_offset_lock_check(const  View3D *v3d, const  RegionView3D *rv3d)
86 {
87         return (rv3d->persp != RV3D_CAMOB) && (v3d->ob_centre_cursor || v3d->ob_centre);
88 }
89
90 static bool view3d_operator_offset_lock_check(bContext *C, wmOperator *op)
91 {
92         View3D *v3d = CTX_wm_view3d(C);
93         RegionView3D *rv3d = CTX_wm_region_view3d(C);
94         if (ED_view3d_offset_lock_check(v3d, rv3d)) {
95                 BKE_report(op->reports, RPT_WARNING, "View offset is locked");
96                 return true;
97         }
98         else {
99                 return false;
100         }
101 }
102
103 /* ********************** view3d_edit: view manipulations ********************* */
104
105 /**
106  * \return true when the view-port is locked to its camera.
107  */
108 bool ED_view3d_camera_lock_check(const View3D *v3d, const RegionView3D *rv3d)
109 {
110         return ((v3d->camera) &&
111                 (v3d->camera->id.lib == NULL) &&
112                 (v3d->flag2 & V3D_LOCK_CAMERA) &&
113                 (rv3d->persp == RV3D_CAMOB));
114 }
115
116 /**
117  * Apply the camera object transformation to the view-port.
118  * (needed so we can use regular view-port manipulation operators, that sync back to the camera).
119  */
120 void ED_view3d_camera_lock_init_ex(View3D *v3d, RegionView3D *rv3d, const bool calc_dist)
121 {
122         if (ED_view3d_camera_lock_check(v3d, rv3d)) {
123                 if (calc_dist) {
124                         /* using a fallback dist is OK here since ED_view3d_from_object() compensates for it */
125                         rv3d->dist = ED_view3d_offset_distance(v3d->camera->obmat, rv3d->ofs, VIEW3D_DIST_FALLBACK);
126                 }
127                 ED_view3d_from_object(v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
128         }
129 }
130
131 void ED_view3d_camera_lock_init(View3D *v3d, RegionView3D *rv3d)
132 {
133         ED_view3d_camera_lock_init_ex(v3d, rv3d, true);
134 }
135
136 /**
137  * Apply the view-port transformation back to the camera object.
138  *
139  * \return true if the camera is moved.
140  */
141 bool ED_view3d_camera_lock_sync(View3D *v3d, RegionView3D *rv3d)
142 {
143         if (ED_view3d_camera_lock_check(v3d, rv3d)) {
144                 ObjectTfmProtectedChannels obtfm;
145                 Object *root_parent;
146
147                 if ((U.uiflag & USER_CAM_LOCK_NO_PARENT) == 0 && (root_parent = v3d->camera->parent)) {
148                         Object *ob_update;
149                         float tmat[4][4];
150                         float imat[4][4];
151                         float view_mat[4][4];
152                         float diff_mat[4][4];
153                         float parent_mat[4][4];
154
155                         while (root_parent->parent) {
156                                 root_parent = root_parent->parent;
157                         }
158
159                         ED_view3d_to_m4(view_mat, rv3d->ofs, rv3d->viewquat, rv3d->dist);
160
161                         normalize_m4_m4(tmat, v3d->camera->obmat);
162
163                         invert_m4_m4(imat, tmat);
164                         mul_m4_m4m4(diff_mat, view_mat, imat);
165
166                         mul_m4_m4m4(parent_mat, diff_mat, root_parent->obmat);
167
168                         BKE_object_tfm_protected_backup(root_parent, &obtfm);
169                         BKE_object_apply_mat4(root_parent, parent_mat, true, false);
170                         BKE_object_tfm_protected_restore(root_parent, &obtfm, root_parent->protectflag);
171
172                         ob_update = v3d->camera;
173                         while (ob_update) {
174                                 DAG_id_tag_update(&ob_update->id, OB_RECALC_OB);
175                                 WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, ob_update);
176                                 ob_update = ob_update->parent;
177                         }
178                 }
179                 else {
180                         /* always maintain the same scale */
181                         const short protect_scale_all = (OB_LOCK_SCALEX | OB_LOCK_SCALEY | OB_LOCK_SCALEZ);
182                         BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
183                         ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
184                         BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag | protect_scale_all);
185
186                         DAG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
187                         WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, v3d->camera);
188                 }
189
190                 return true;
191         }
192         else {
193                 return false;
194         }
195 }
196
197 bool ED_view3d_camera_autokey(
198         Scene *scene, ID *id_key,
199         struct bContext *C, const bool do_rotate, const bool do_translate)
200 {
201         if (autokeyframe_cfra_can_key(scene, id_key)) {
202                 const float cfra = (float)CFRA;
203                 ListBase dsources = {NULL, NULL};
204
205                 /* add data-source override for the camera object */
206                 ANIM_relative_keyingset_add_source(&dsources, id_key, NULL, NULL);
207
208                 /* insert keyframes
209                  * 1) on the first frame
210                  * 2) on each subsequent frame
211                  *    TODO: need to check in future that frame changed before doing this
212                  */
213                 if (do_rotate) {
214                         struct KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_ROTATION_ID);
215                         ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
216                 }
217                 if (do_translate) {
218                         struct KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_LOCATION_ID);
219                         ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
220                 }
221
222                 /* free temp data */
223                 BLI_freelistN(&dsources);
224
225                 return true;
226         }
227         else {
228                 return false;
229         }
230 }
231
232 /**
233  * Call after modifying a locked view.
234  *
235  * \note Not every view edit currently auto-keys (numpad for eg),
236  * this is complicated because of smoothview.
237  */
238 bool ED_view3d_camera_lock_autokey(
239         View3D *v3d, RegionView3D *rv3d,
240         struct bContext *C, const bool do_rotate, const bool do_translate)
241 {
242         /* similar to ED_view3d_cameracontrol_update */
243         if (ED_view3d_camera_lock_check(v3d, rv3d)) {
244                 Scene *scene = CTX_data_scene(C);
245                 ID *id_key;
246                 Object *root_parent;
247                 if ((U.uiflag & USER_CAM_LOCK_NO_PARENT) == 0 && (root_parent = v3d->camera->parent)) {
248                         while (root_parent->parent) {
249                                 root_parent = root_parent->parent;
250                         }
251                         id_key = &root_parent->id;
252                 }
253                 else {
254                         id_key = &v3d->camera->id;
255                 }
256
257                 return ED_view3d_camera_autokey(scene, id_key, C, do_rotate, do_translate);
258         }
259         else {
260                 return false;
261         }
262 }
263
264 /**
265  * For viewport operators that exit camera persp.
266  *
267  * \note This differs from simply setting ``rv3d->persp = persp`` because it
268  * sets the ``ofs`` and ``dist`` values of the viewport so it matches the camera,
269  * otherwise switching out of camera view may jump to a different part of the scene.
270  */
271 static void view3d_persp_switch_from_camera(View3D *v3d, RegionView3D *rv3d, const char persp)
272 {
273         BLI_assert(rv3d->persp == RV3D_CAMOB);
274         BLI_assert(persp != RV3D_CAMOB);
275
276         if (v3d->camera) {
277                 rv3d->dist = ED_view3d_offset_distance(v3d->camera->obmat, rv3d->ofs, VIEW3D_DIST_FALLBACK);
278                 ED_view3d_from_object(v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
279         }
280
281         if (!ED_view3d_camera_lock_check(v3d, rv3d)) {
282                 rv3d->persp = persp;
283         }
284 }
285
286 /* ********************* box view support ***************** */
287
288 static void view3d_boxview_clip(ScrArea *sa)
289 {
290         ARegion *ar;
291         BoundBox *bb = MEM_callocN(sizeof(BoundBox), "clipbb");
292         float clip[6][4];
293         float x1 = 0.0f, y1 = 0.0f, z1 = 0.0f, ofs[3] = {0.0f, 0.0f, 0.0f};
294         int val;
295
296         /* create bounding box */
297         for (ar = sa->regionbase.first; ar; ar = ar->next) {
298                 if (ar->regiontype == RGN_TYPE_WINDOW) {
299                         RegionView3D *rv3d = ar->regiondata;
300
301                         if (rv3d->viewlock & RV3D_BOXCLIP) {
302                                 if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) {
303                                         if (ar->winx > ar->winy) x1 = rv3d->dist;
304                                         else x1 = ar->winx * rv3d->dist / ar->winy;
305
306                                         if (ar->winx > ar->winy) y1 = ar->winy * rv3d->dist / ar->winx;
307                                         else y1 = rv3d->dist;
308                                         copy_v2_v2(ofs, rv3d->ofs);
309                                 }
310                                 else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK)) {
311                                         ofs[2] = rv3d->ofs[2];
312
313                                         if (ar->winx > ar->winy) z1 = ar->winy * rv3d->dist / ar->winx;
314                                         else z1 = rv3d->dist;
315                                 }
316                         }
317                 }
318         }
319
320         for (val = 0; val < 8; val++) {
321                 if (ELEM(val, 0, 3, 4, 7))
322                         bb->vec[val][0] = -x1 - ofs[0];
323                 else
324                         bb->vec[val][0] =  x1 - ofs[0];
325
326                 if (ELEM(val, 0, 1, 4, 5))
327                         bb->vec[val][1] = -y1 - ofs[1];
328                 else
329                         bb->vec[val][1] =  y1 - ofs[1];
330
331                 if (val > 3)
332                         bb->vec[val][2] = -z1 - ofs[2];
333                 else
334                         bb->vec[val][2] =  z1 - ofs[2];
335         }
336
337         /* normals for plane equations */
338         normal_tri_v3(clip[0], bb->vec[0], bb->vec[1], bb->vec[4]);
339         normal_tri_v3(clip[1], bb->vec[1], bb->vec[2], bb->vec[5]);
340         normal_tri_v3(clip[2], bb->vec[2], bb->vec[3], bb->vec[6]);
341         normal_tri_v3(clip[3], bb->vec[3], bb->vec[0], bb->vec[7]);
342         normal_tri_v3(clip[4], bb->vec[4], bb->vec[5], bb->vec[6]);
343         normal_tri_v3(clip[5], bb->vec[0], bb->vec[2], bb->vec[1]);
344
345         /* then plane equations */
346         for (val = 0; val < 6; val++) {
347                 clip[val][3] = -dot_v3v3(clip[val], bb->vec[val % 5]);
348         }
349
350         /* create bounding box */
351         for (ar = sa->regionbase.first; ar; ar = ar->next) {
352                 if (ar->regiontype == RGN_TYPE_WINDOW) {
353                         RegionView3D *rv3d = ar->regiondata;
354
355                         if (rv3d->viewlock & RV3D_BOXCLIP) {
356                                 rv3d->rflag |= RV3D_CLIPPING;
357                                 memcpy(rv3d->clip, clip, sizeof(clip));
358                                 if (rv3d->clipbb) MEM_freeN(rv3d->clipbb);
359                                 rv3d->clipbb = MEM_dupallocN(bb);
360                         }
361                 }
362         }
363         MEM_freeN(bb);
364 }
365
366 /**
367  * Find which axis values are shared between both views and copy to \a rv3d_dst
368  * taking axis flipping into account.
369  */
370 static void view3d_boxview_sync_axis(RegionView3D *rv3d_dst, RegionView3D *rv3d_src)
371 {
372         /* absolute axis values above this are considered to be set (will be ~1.0f) */
373         const float axis_eps = 0.5f;
374         float viewinv[4];
375
376         /* use the view rotation to identify which axis to sync on */
377         float view_axis_all[4][3] = {
378             {1.0f, 0.0f, 0.0f},
379             {0.0f, 1.0f, 0.0f},
380             {1.0f, 0.0f, 0.0f},
381             {0.0f, 1.0f, 0.0f}};
382
383         float *view_src_x = &view_axis_all[0][0];
384         float *view_src_y = &view_axis_all[1][0];
385
386         float *view_dst_x = &view_axis_all[2][0];
387         float *view_dst_y = &view_axis_all[3][0];
388         int i;
389
390
391         /* we could use rv3d->viewinv, but better not depend on view matrix being updated */
392         if (UNLIKELY(ED_view3d_quat_from_axis_view(rv3d_src->view, viewinv) == false)) {
393                 return;
394         }
395         invert_qt_normalized(viewinv);
396         mul_qt_v3(viewinv, view_src_x);
397         mul_qt_v3(viewinv, view_src_y);
398
399         if (UNLIKELY(ED_view3d_quat_from_axis_view(rv3d_dst->view, viewinv) == false)) {
400                 return;
401         }
402         invert_qt_normalized(viewinv);
403         mul_qt_v3(viewinv, view_dst_x);
404         mul_qt_v3(viewinv, view_dst_y);
405
406         /* check source and dest have a matching axis */
407         for (i = 0; i < 3; i++) {
408                 if (((fabsf(view_src_x[i]) > axis_eps) || (fabsf(view_src_y[i]) > axis_eps)) &&
409                     ((fabsf(view_dst_x[i]) > axis_eps) || (fabsf(view_dst_y[i]) > axis_eps)))
410                 {
411                         rv3d_dst->ofs[i] = rv3d_src->ofs[i];
412                 }
413         }
414 }
415
416 /* sync center/zoom view of region to others, for view transforms */
417 static void view3d_boxview_sync(ScrArea *sa, ARegion *ar)
418 {
419         ARegion *artest;
420         RegionView3D *rv3d = ar->regiondata;
421         short clip = 0;
422
423         for (artest = sa->regionbase.first; artest; artest = artest->next) {
424                 if (artest != ar && artest->regiontype == RGN_TYPE_WINDOW) {
425                         RegionView3D *rv3dtest = artest->regiondata;
426
427                         if (rv3dtest->viewlock & RV3D_LOCKED) {
428                                 rv3dtest->dist = rv3d->dist;
429                                 view3d_boxview_sync_axis(rv3dtest, rv3d);
430                                 clip |= rv3dtest->viewlock & RV3D_BOXCLIP;
431
432                                 ED_region_tag_redraw(artest);
433                         }
434                 }
435         }
436
437         if (clip) {
438                 view3d_boxview_clip(sa);
439         }
440 }
441
442 /* for home, center etc */
443 void view3d_boxview_copy(ScrArea *sa, ARegion *ar)
444 {
445         ARegion *artest;
446         RegionView3D *rv3d = ar->regiondata;
447         bool clip = false;
448
449         for (artest = sa->regionbase.first; artest; artest = artest->next) {
450                 if (artest != ar && artest->regiontype == RGN_TYPE_WINDOW) {
451                         RegionView3D *rv3dtest = artest->regiondata;
452
453                         if (rv3dtest->viewlock) {
454                                 rv3dtest->dist = rv3d->dist;
455                                 copy_v3_v3(rv3dtest->ofs, rv3d->ofs);
456                                 ED_region_tag_redraw(artest);
457
458                                 clip |= ((rv3dtest->viewlock & RV3D_BOXCLIP) != 0);
459                         }
460                 }
461         }
462
463         if (clip) {
464                 view3d_boxview_clip(sa);
465         }
466 }
467
468 /* 'clip' is used to know if our clip setting has changed */
469 void ED_view3d_quadview_update(ScrArea *sa, ARegion *ar, bool do_clip)
470 {
471         ARegion *ar_sync = NULL;
472         RegionView3D *rv3d = ar->regiondata;
473         short viewlock;
474         /* this function copies flags from the first of the 3 other quadview
475          * regions to the 2 other, so it assumes this is the region whose
476          * properties are always being edited, weak */
477         viewlock = rv3d->viewlock;
478
479         if ((viewlock & RV3D_LOCKED) == 0) {
480                 do_clip = (viewlock & RV3D_BOXCLIP) != 0;
481                 viewlock = 0;
482         }
483         else if ((viewlock & RV3D_BOXVIEW) == 0 && (viewlock & RV3D_BOXCLIP) != 0) {
484                 do_clip = true;
485                 viewlock &= ~RV3D_BOXCLIP;
486         }
487
488         for (; ar; ar = ar->prev) {
489                 if (ar->alignment == RGN_ALIGN_QSPLIT) {
490                         rv3d = ar->regiondata;
491                         rv3d->viewlock = viewlock;
492
493                         if (do_clip && (viewlock & RV3D_BOXCLIP) == 0) {
494                                 rv3d->rflag &= ~RV3D_BOXCLIP;
495                         }
496
497                         /* use ar_sync so we sync with one of the aligned views below
498                          * else the view jumps on changing view settings like 'clip'
499                          * since it copies from the perspective view */
500                         ar_sync = ar;
501                 }
502         }
503
504         if (rv3d->viewlock & RV3D_BOXVIEW) {
505                 view3d_boxview_sync(sa, ar_sync ? ar_sync : sa->regionbase.last);
506         }
507
508         /* ensure locked regions have an axis, locked user views don't make much sense */
509         if (viewlock & RV3D_LOCKED) {
510                 int index_qsplit = 0;
511                 for (ar = sa->regionbase.first; ar; ar = ar->next) {
512                         if (ar->alignment == RGN_ALIGN_QSPLIT) {
513                                 rv3d = ar->regiondata;
514                                 if (rv3d->viewlock) {
515                                         if (!RV3D_VIEW_IS_AXIS(rv3d->view)) {
516                                                 rv3d->view = ED_view3d_lock_view_from_index(index_qsplit);
517                                                 rv3d->persp = RV3D_ORTHO;
518                                                 ED_view3d_lock(rv3d);
519                                         }
520                                 }
521                                 index_qsplit++;
522                         }
523                 }
524         }
525
526         ED_area_tag_redraw(sa);
527 }
528
529 /* ************************** init for view ops **********************************/
530
531 typedef struct ViewOpsData {
532         /* context pointers (assigned by viewops_data_alloc) */
533         Scene *scene;
534         ScrArea *sa;
535         ARegion *ar;
536         View3D *v3d;
537         RegionView3D *rv3d;
538
539         /* needed for continuous zoom */
540         wmTimer *timer;
541         double timer_lastdraw;
542
543         float oldquat[4];
544         float viewquat[4]; /* working copy of rv3d->viewquat */
545         float trackvec[3];
546         float mousevec[3]; /* dolly only */
547         float reverse;
548         float dist_prev, camzoom_prev;
549         float grid, far;
550         bool axis_snap;  /* view rotate only */
551         float zfac;
552
553         /* use for orbit selection and auto-dist */
554         float ofs[3], dyn_ofs[3];
555         bool use_dyn_ofs;
556
557         int origx, origy, oldx, oldy;
558         int origkey; /* the key that triggered the operator */
559
560 } ViewOpsData;
561
562 #define TRACKBALLSIZE  (1.1f)
563
564 static void calctrackballvec(const rcti *rect, int mx, int my, float vec[3])
565 {
566         float x, y, radius, d, z, t;
567
568         radius = TRACKBALLSIZE;
569
570         /* normalize x and y */
571         x = BLI_rcti_cent_x(rect) - mx;
572         x /= (float)(BLI_rcti_size_x(rect) / 4);
573         y = BLI_rcti_cent_y(rect) - my;
574         y /= (float)(BLI_rcti_size_y(rect) / 2);
575
576         d = sqrtf(x * x + y * y);
577         if (d < radius * (float)M_SQRT1_2) { /* Inside sphere */
578                 z = sqrtf(radius * radius - d * d);
579         }
580         else { /* On hyperbola */
581                 t = radius / (float)M_SQRT2;
582                 z = t * t / d;
583         }
584
585         vec[0] = x;
586         vec[1] = y;
587         vec[2] = -z;     /* yah yah! */
588 }
589
590
591 /* -------------------------------------------------------------------- */
592 /* ViewOpsData */
593
594 /** \name Generic View Operator Custom-Data.
595  * \{ */
596
597 /**
598  * Allocate and fill in context pointers for #ViewOpsData
599  */
600 static void viewops_data_alloc(bContext *C, wmOperator *op)
601 {
602         ViewOpsData *vod = MEM_callocN(sizeof(ViewOpsData), "viewops data");
603
604         /* store data */
605         op->customdata = vod;
606         vod->scene = CTX_data_scene(C);
607         vod->sa = CTX_wm_area(C);
608         vod->ar = CTX_wm_region(C);
609         vod->v3d = vod->sa->spacedata.first;
610         vod->rv3d = vod->ar->regiondata;
611 }
612
613 void view3d_orbit_apply_dyn_ofs(
614         float r_ofs[3], const float ofs_old[3], const float viewquat_old[4],
615         const float viewquat_new[4], const float dyn_ofs[3])
616 {
617         float q[4];
618         invert_qt_qt_normalized(q, viewquat_old);
619         mul_qt_qtqt(q, q, viewquat_new);
620
621         invert_qt_normalized(q);
622
623         sub_v3_v3v3(r_ofs, ofs_old, dyn_ofs);
624         mul_qt_v3(q, r_ofs);
625         add_v3_v3(r_ofs, dyn_ofs);
626 }
627
628 static bool view3d_orbit_calc_center(bContext *C, float r_dyn_ofs[3])
629 {
630         static float lastofs[3] = {0, 0, 0};
631         bool is_set = false;
632
633         Scene *scene = CTX_data_scene(C);
634         Object *ob_act = OBACT;
635
636         if (ob_act && (ob_act->mode & OB_MODE_ALL_PAINT) &&
637             /* with weight-paint + pose-mode, fall through to using calculateTransformCenter */
638             ((ob_act->mode & OB_MODE_WEIGHT_PAINT) && BKE_object_pose_armature_get(ob_act)) == 0)
639         {
640                 /* in case of sculpting use last average stroke position as a rotation
641                  * center, in other cases it's not clear what rotation center shall be
642                  * so just rotate around object origin
643                  */
644                 if (ob_act->mode & (OB_MODE_SCULPT | OB_MODE_TEXTURE_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)) {
645                         float stroke[3];
646                         BKE_paint_stroke_get_average(scene, ob_act, stroke);
647                         copy_v3_v3(lastofs, stroke);
648                 }
649                 else {
650                         copy_v3_v3(lastofs, ob_act->obmat[3]);
651                 }
652                 is_set = true;
653         }
654         else if (ob_act && (ob_act->mode & OB_MODE_EDIT) && (ob_act->type == OB_FONT)) {
655                 Curve *cu = ob_act->data;
656                 EditFont *ef = cu->editfont;
657                 int i;
658
659                 zero_v3(lastofs);
660                 for (i = 0; i < 4; i++) {
661                         add_v2_v2(lastofs, ef->textcurs[i]);
662                 }
663                 mul_v2_fl(lastofs, 1.0f / 4.0f);
664
665                 mul_m4_v3(ob_act->obmat, lastofs);
666
667                 is_set = true;
668         }
669         else if (ob_act == NULL || ob_act->mode == OB_MODE_OBJECT) {
670                 /* object mode use boundbox centers */
671                 View3D *v3d = CTX_wm_view3d(C);
672                 Base *base;
673                 unsigned int tot = 0;
674                 float select_center[3];
675
676                 zero_v3(select_center);
677                 for (base = FIRSTBASE; base; base = base->next) {
678                         if (TESTBASE(v3d, base)) {
679                                 /* use the boundbox if we can */
680                                 Object *ob = base->object;
681
682                                 if (ob->bb && !(ob->bb->flag & BOUNDBOX_DIRTY)) {
683                                         float cent[3];
684
685                                         BKE_boundbox_calc_center_aabb(ob->bb, cent);
686
687                                         mul_m4_v3(ob->obmat, cent);
688                                         add_v3_v3(select_center, cent);
689                                 }
690                                 else {
691                                         add_v3_v3(select_center, ob->obmat[3]);
692                                 }
693                                 tot++;
694                         }
695                 }
696                 if (tot) {
697                         mul_v3_fl(select_center, 1.0f / (float)tot);
698                         copy_v3_v3(lastofs, select_center);
699                         is_set = true;
700                 }
701         }
702         else {
703                 /* If there's no selection, lastofs is unmodified and last value since static */
704                 is_set = calculateTransformCenter(C, V3D_AROUND_CENTER_MEAN, lastofs, NULL);
705         }
706
707         copy_v3_v3(r_dyn_ofs, lastofs);
708
709         return is_set;
710 }
711
712 /**
713  * Calculate the values for #ViewOpsData
714  */
715 static void viewops_data_create_ex(bContext *C, wmOperator *op, const wmEvent *event,
716                                    const bool use_orbit_select,
717                                    const bool use_orbit_zbuf)
718 {
719         ViewOpsData *vod = op->customdata;
720         RegionView3D *rv3d = vod->rv3d;
721
722         /* set the view from the camera, if view locking is enabled.
723          * we may want to make this optional but for now its needed always */
724         ED_view3d_camera_lock_init(vod->v3d, vod->rv3d);
725
726         vod->dist_prev = rv3d->dist;
727         vod->camzoom_prev = rv3d->camzoom;
728         copy_qt_qt(vod->viewquat, rv3d->viewquat);
729         copy_qt_qt(vod->oldquat, rv3d->viewquat);
730         vod->origx = vod->oldx = event->x;
731         vod->origy = vod->oldy = event->y;
732         vod->origkey = event->type; /* the key that triggered the operator.  */
733         vod->use_dyn_ofs = false;
734         copy_v3_v3(vod->ofs, rv3d->ofs);
735
736         if (use_orbit_select) {
737
738                 vod->use_dyn_ofs = true;
739
740                 view3d_orbit_calc_center(C, vod->dyn_ofs);
741
742                 negate_v3(vod->dyn_ofs);
743         }
744         else if (use_orbit_zbuf) {
745                 Scene *scene = CTX_data_scene(C);
746                 float fallback_depth_pt[3];
747
748                 view3d_operator_needs_opengl(C); /* needed for zbuf drawing */
749
750                 negate_v3_v3(fallback_depth_pt, rv3d->ofs);
751
752                 if ((vod->use_dyn_ofs = ED_view3d_autodist(scene, vod->ar, vod->v3d,
753                                                            event->mval, vod->dyn_ofs, true, fallback_depth_pt)))
754                 {
755                         if (rv3d->is_persp) {
756                                 float my_origin[3]; /* original G.vd->ofs */
757                                 float my_pivot[3]; /* view */
758                                 float dvec[3];
759
760                                 /* locals for dist correction */
761                                 float mat[3][3];
762                                 float upvec[3];
763
764                                 negate_v3_v3(my_origin, rv3d->ofs);             /* ofs is flipped */
765
766                                 /* Set the dist value to be the distance from this 3d point
767                                  * this means youll always be able to zoom into it and panning wont go bad when dist was zero */
768
769                                 /* remove dist value */
770                                 upvec[0] = upvec[1] = 0;
771                                 upvec[2] = rv3d->dist;
772                                 copy_m3_m4(mat, rv3d->viewinv);
773
774                                 mul_m3_v3(mat, upvec);
775                                 sub_v3_v3v3(my_pivot, rv3d->ofs, upvec);
776                                 negate_v3(my_pivot);                /* ofs is flipped */
777
778                                 /* find a new ofs value that is along the view axis (rather than the mouse location) */
779                                 closest_to_line_v3(dvec, vod->dyn_ofs, my_pivot, my_origin);
780                                 vod->dist_prev = rv3d->dist = len_v3v3(my_pivot, dvec);
781
782                                 negate_v3_v3(rv3d->ofs, dvec);
783                         }
784                         else {
785                                 const float mval_ar_mid[2] = {
786                                     (float)vod->ar->winx / 2.0f,
787                                     (float)vod->ar->winy / 2.0f};
788
789                                 ED_view3d_win_to_3d(vod->ar, vod->dyn_ofs, mval_ar_mid, rv3d->ofs);
790                                 negate_v3(rv3d->ofs);
791                         }
792                         negate_v3(vod->dyn_ofs);
793                         copy_v3_v3(vod->ofs, rv3d->ofs);
794                 }
795         }
796
797         {
798                 /* for dolly */
799                 const float mval_f[2] = {(float)event->mval[0],
800                                          (float)event->mval[1]};
801                 ED_view3d_win_to_vector(vod->ar, mval_f, vod->mousevec);
802         }
803
804         /* lookup, we don't pass on v3d to prevent confusement */
805         vod->grid = vod->v3d->grid;
806         vod->far = vod->v3d->far;
807
808         calctrackballvec(&vod->ar->winrct, event->x, event->y, vod->trackvec);
809
810         {
811                 float tvec[3];
812                 negate_v3_v3(tvec, rv3d->ofs);
813                 vod->zfac = ED_view3d_calc_zfac(rv3d, tvec, NULL);
814         }
815
816         vod->reverse = 1.0f;
817         if (rv3d->persmat[2][1] < 0.0f)
818                 vod->reverse = -1.0f;
819
820         rv3d->rflag |= RV3D_NAVIGATING;
821 }
822
823 static void viewops_data_create(bContext *C, wmOperator *op, const wmEvent *event)
824 {
825         viewops_data_create_ex(
826                 C, op, event,
827                 (U.uiflag & USER_ORBIT_SELECTION) != 0,
828                 (U.uiflag & USER_ZBUF_ORBIT) != 0);
829 }
830
831 static void viewops_data_free(bContext *C, wmOperator *op)
832 {
833         ARegion *ar;
834         Paint *p = BKE_paint_get_active_from_context(C);
835
836         if (op->customdata) {
837                 ViewOpsData *vod = op->customdata;
838                 ar = vod->ar;
839                 vod->rv3d->rflag &= ~RV3D_NAVIGATING;
840
841                 if (vod->timer)
842                         WM_event_remove_timer(CTX_wm_manager(C), vod->timer->win, vod->timer);
843
844                 MEM_freeN(vod);
845                 op->customdata = NULL;
846         }
847         else {
848                 ar = CTX_wm_region(C);
849         }
850
851         if (p && (p->flags & PAINT_FAST_NAVIGATE))
852                 ED_region_tag_redraw(ar);
853 }
854 /** \} */
855
856
857 /* ************************** viewrotate **********************************/
858
859 enum {
860         VIEW_PASS = 0,
861         VIEW_APPLY,
862         VIEW_CONFIRM
863 };
864
865 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
866 #define VIEW_MODAL_CONFIRM              1 /* used for all view operations */
867 #define VIEWROT_MODAL_AXIS_SNAP_ENABLE  2
868 #define VIEWROT_MODAL_AXIS_SNAP_DISABLE 3
869 #define VIEWROT_MODAL_SWITCH_ZOOM       4
870 #define VIEWROT_MODAL_SWITCH_MOVE       5
871 #define VIEWROT_MODAL_SWITCH_ROTATE     6
872
873 /* called in transform_ops.c, on each regeneration of keymaps  */
874 void viewrotate_modal_keymap(wmKeyConfig *keyconf)
875 {
876         static EnumPropertyItem modal_items[] = {
877                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
878
879                 {VIEWROT_MODAL_AXIS_SNAP_ENABLE,    "AXIS_SNAP_ENABLE", 0, "Enable Axis Snap", ""},
880                 {VIEWROT_MODAL_AXIS_SNAP_DISABLE,   "AXIS_SNAP_DISABLE", 0, "Disable Axis Snap", ""},
881                 
882                 {VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
883                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
884
885                 {0, NULL, 0, NULL, NULL}
886         };
887
888         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Rotate Modal");
889
890         /* this function is called for each spacetype, only needs to add map once */
891         if (keymap && keymap->modal_items) return;
892
893         keymap = WM_modalkeymap_add(keyconf, "View3D Rotate Modal", modal_items);
894
895         /* items for modal map */
896         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
897         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
898
899         WM_modalkeymap_add_item(keymap, LEFTALTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_AXIS_SNAP_ENABLE);
900         WM_modalkeymap_add_item(keymap, LEFTALTKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_AXIS_SNAP_DISABLE);
901
902         /* disabled mode switching for now, can re-implement better, later on */
903 #if 0
904         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
905         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
906         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
907 #endif
908         
909         /* assign map to operators */
910         WM_modalkeymap_assign(keymap, "VIEW3D_OT_rotate");
911
912 }
913
914 static void viewrotate_apply_dyn_ofs(ViewOpsData *vod, const float viewquat_new[4])
915 {
916         if (vod->use_dyn_ofs) {
917                 RegionView3D *rv3d = vod->rv3d;
918                 view3d_orbit_apply_dyn_ofs(rv3d->ofs, vod->ofs, vod->oldquat, viewquat_new, vod->dyn_ofs);
919         }
920 }
921
922 static void viewrotate_apply_snap(ViewOpsData *vod)
923 {
924         const float axis_limit = DEG2RADF(45 / 3);
925
926         RegionView3D *rv3d = vod->rv3d;
927
928         float viewquat_inv[4];
929         float zaxis[3] = {0, 0, 1};
930         float zaxis_best[3];
931         int x, y, z;
932         bool found = false;
933
934         invert_qt_qt_normalized(viewquat_inv, vod->viewquat);
935
936         mul_qt_v3(viewquat_inv, zaxis);
937         normalize_v3(zaxis);
938
939
940         for (x = -1; x < 2; x++) {
941                 for (y = -1; y < 2; y++) {
942                         for (z = -1; z < 2; z++) {
943                                 if (x || y || z) {
944                                         float zaxis_test[3] = {x, y, z};
945
946                                         normalize_v3(zaxis_test);
947
948                                         if (angle_normalized_v3v3(zaxis_test, zaxis) < axis_limit) {
949                                                 copy_v3_v3(zaxis_best, zaxis_test);
950                                                 found = true;
951                                         }
952                                 }
953                         }
954                 }
955         }
956
957         if (found) {
958
959                 /* find the best roll */
960                 float quat_roll[4], quat_final[4], quat_best[4], quat_snap[4];
961                 float viewquat_align[4]; /* viewquat aligned to zaxis_best */
962                 float viewquat_align_inv[4]; /* viewquat aligned to zaxis_best */
963                 float best_angle = axis_limit;
964                 int j;
965
966                 /* viewquat_align is the original viewquat aligned to the snapped axis
967                  * for testing roll */
968                 rotation_between_vecs_to_quat(viewquat_align, zaxis_best, zaxis);
969                 normalize_qt(viewquat_align);
970                 mul_qt_qtqt(viewquat_align, vod->viewquat, viewquat_align);
971                 normalize_qt(viewquat_align);
972                 invert_qt_qt_normalized(viewquat_align_inv, viewquat_align);
973
974                 vec_to_quat(quat_snap, zaxis_best, OB_NEGZ, OB_POSY);
975                 normalize_qt(quat_snap);
976                 invert_qt_normalized(quat_snap);
977
978                 /* check if we can find the roll */
979                 found = false;
980
981                 /* find best roll */
982                 for (j = 0; j < 8; j++) {
983                         float angle;
984                         float xaxis1[3] = {1, 0, 0};
985                         float xaxis2[3] = {1, 0, 0};
986                         float quat_final_inv[4];
987
988                         axis_angle_to_quat(quat_roll, zaxis_best, (float)j * DEG2RADF(45.0f));
989                         normalize_qt(quat_roll);
990
991                         mul_qt_qtqt(quat_final, quat_snap, quat_roll);
992                         normalize_qt(quat_final);
993
994                         /* compare 2 vector angles to find the least roll */
995                         invert_qt_qt_normalized(quat_final_inv, quat_final);
996                         mul_qt_v3(viewquat_align_inv, xaxis1);
997                         mul_qt_v3(quat_final_inv, xaxis2);
998                         angle = angle_v3v3(xaxis1, xaxis2);
999
1000                         if (angle <= best_angle) {
1001                                 found = true;
1002                                 best_angle = angle;
1003                                 copy_qt_qt(quat_best, quat_final);
1004                         }
1005                 }
1006
1007                 if (found) {
1008                         /* lock 'quat_best' to an axis view if we can */
1009                         rv3d->view = ED_view3d_quat_to_axis_view(quat_best, 0.01f);
1010                         if (rv3d->view != RV3D_VIEW_USER) {
1011                                 ED_view3d_quat_from_axis_view(rv3d->view, quat_best);
1012                         }
1013                 }
1014                 else {
1015                         copy_qt_qt(quat_best, viewquat_align);
1016                 }
1017
1018                 copy_qt_qt(rv3d->viewquat, quat_best);
1019
1020                 viewrotate_apply_dyn_ofs(vod, rv3d->viewquat);
1021         }
1022 }
1023
1024 static void viewrotate_apply(ViewOpsData *vod, int x, int y)
1025 {
1026         RegionView3D *rv3d = vod->rv3d;
1027
1028         rv3d->view = RV3D_VIEW_USER; /* need to reset every time because of view snapping */
1029
1030         if (U.flag & USER_TRACKBALL) {
1031                 float axis[3], q1[4], dvec[3], newvec[3];
1032                 float angle;
1033
1034                 calctrackballvec(&vod->ar->winrct, x, y, newvec);
1035
1036                 sub_v3_v3v3(dvec, newvec, vod->trackvec);
1037
1038                 angle = (len_v3(dvec) / (2.0f * TRACKBALLSIZE)) * (float)M_PI;
1039
1040                 /* Allow for rotation beyond the interval [-pi, pi] */
1041                 angle = angle_wrap_rad(angle);
1042
1043                 /* This relation is used instead of the actual angle between vectors
1044                  * so that the angle of rotation is linearly proportional to
1045                  * the distance that the mouse is dragged. */
1046
1047                 cross_v3_v3v3(axis, vod->trackvec, newvec);
1048                 axis_angle_to_quat(q1, axis, angle);
1049
1050                 mul_qt_qtqt(vod->viewquat, q1, vod->oldquat);
1051
1052                 viewrotate_apply_dyn_ofs(vod, vod->viewquat);
1053         }
1054         else {
1055                 /* New turntable view code by John Aughey */
1056                 float quat_local_x[4], quat_global_z[4];
1057                 float m[3][3];
1058                 float m_inv[3][3];
1059                 const float zvec_global[3] = {0.0f, 0.0f, 1.0f};
1060                 float xaxis[3];
1061
1062                 /* Sensitivity will control how fast the viewport rotates.  0.007 was
1063                  * obtained experimentally by looking at viewport rotation sensitivities
1064                  * on other modeling programs. */
1065                 /* Perhaps this should be a configurable user parameter. */
1066                 const float sensitivity = 0.007f;
1067
1068                 /* Get the 3x3 matrix and its inverse from the quaternion */
1069                 quat_to_mat3(m, vod->viewquat);
1070                 invert_m3_m3(m_inv, m);
1071
1072                 /* avoid gimble lock */
1073 #if 1
1074                 if (len_squared_v3v3(zvec_global, m_inv[2]) > 0.001f) {
1075                         float fac;
1076                         cross_v3_v3v3(xaxis, zvec_global, m_inv[2]);
1077                         if (dot_v3v3(xaxis, m_inv[0]) < 0) {
1078                                 negate_v3(xaxis);
1079                         }
1080                         fac = angle_normalized_v3v3(zvec_global, m_inv[2]) / (float)M_PI;
1081                         fac = fabsf(fac - 0.5f) * 2;
1082                         fac = fac * fac;
1083                         interp_v3_v3v3(xaxis, xaxis, m_inv[0], fac);
1084                 }
1085                 else {
1086                         copy_v3_v3(xaxis, m_inv[0]);
1087                 }
1088 #else
1089                 copy_v3_v3(xaxis, m_inv[0]);
1090 #endif
1091
1092                 /* Determine the direction of the x vector (for rotating up and down) */
1093                 /* This can likely be computed directly from the quaternion. */
1094
1095                 /* Perform the up/down rotation */
1096                 axis_angle_to_quat(quat_local_x, xaxis, sensitivity * -(y - vod->oldy));
1097                 mul_qt_qtqt(quat_local_x, vod->viewquat, quat_local_x);
1098
1099                 /* Perform the orbital rotation */
1100                 axis_angle_to_quat_single(quat_global_z, 'Z', sensitivity * vod->reverse * (x - vod->oldx));
1101                 mul_qt_qtqt(vod->viewquat, quat_local_x, quat_global_z);
1102
1103                 viewrotate_apply_dyn_ofs(vod, vod->viewquat);
1104         }
1105
1106         /* avoid precision loss over time */
1107         normalize_qt(vod->viewquat);
1108
1109         /* use a working copy so view rotation locking doesnt overwrite the locked
1110          * rotation back into the view we calculate with */
1111         copy_qt_qt(rv3d->viewquat, vod->viewquat);
1112
1113         /* check for view snap,
1114          * note: don't apply snap to vod->viewquat so the view wont jam up */
1115         if (vod->axis_snap) {
1116                 viewrotate_apply_snap(vod);
1117         }
1118         vod->oldx = x;
1119         vod->oldy = y;
1120
1121         ED_view3d_camera_lock_sync(vod->v3d, rv3d);
1122
1123         ED_region_tag_redraw(vod->ar);
1124 }
1125
1126 static int viewrotate_modal(bContext *C, wmOperator *op, const wmEvent *event)
1127 {
1128         ViewOpsData *vod = op->customdata;
1129         short event_code = VIEW_PASS;
1130         bool use_autokey = false;
1131         int ret = OPERATOR_RUNNING_MODAL;
1132
1133         /* execute the events */
1134         if (event->type == MOUSEMOVE) {
1135                 event_code = VIEW_APPLY;
1136         }
1137         else if (event->type == EVT_MODAL_MAP) {
1138                 switch (event->val) {
1139                         case VIEW_MODAL_CONFIRM:
1140                                 event_code = VIEW_CONFIRM;
1141                                 break;
1142                         case VIEWROT_MODAL_AXIS_SNAP_ENABLE:
1143                                 vod->axis_snap = true;
1144                                 event_code = VIEW_APPLY;
1145                                 break;
1146                         case VIEWROT_MODAL_AXIS_SNAP_DISABLE:
1147                                 vod->axis_snap = false;
1148                                 event_code = VIEW_APPLY;
1149                                 break;
1150                         case VIEWROT_MODAL_SWITCH_ZOOM:
1151                                 WM_operator_name_call(C, "VIEW3D_OT_zoom", WM_OP_INVOKE_DEFAULT, NULL);
1152                                 event_code = VIEW_CONFIRM;
1153                                 break;
1154                         case VIEWROT_MODAL_SWITCH_MOVE:
1155                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
1156                                 event_code = VIEW_CONFIRM;
1157                                 break;
1158                 }
1159         }
1160         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
1161                 event_code = VIEW_CONFIRM;
1162         }
1163
1164         if (event_code == VIEW_APPLY) {
1165                 viewrotate_apply(vod, event->x, event->y);
1166                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
1167                         use_autokey = true;
1168                 }
1169         }
1170         else if (event_code == VIEW_CONFIRM) {
1171                 ED_view3d_depth_tag_update(vod->rv3d);
1172                 use_autokey = true;
1173                 ret = OPERATOR_FINISHED;
1174         }
1175
1176         if (use_autokey) {
1177                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, true, true);
1178         }
1179
1180         if (ret & OPERATOR_FINISHED) {
1181                 viewops_data_free(C, op);
1182         }
1183
1184         return ret;
1185 }
1186
1187 /**
1188  * Action to take when rotating the view,
1189  * handle auto-persp and logic for switching out of views.
1190  *
1191  * shared with NDOF.
1192  */
1193 static bool view3d_ensure_persp(struct View3D *v3d, ARegion *ar)
1194 {
1195         RegionView3D *rv3d = ar->regiondata;
1196         const bool autopersp = (U.uiflag & USER_AUTOPERSP) != 0;
1197
1198         BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
1199
1200         if (ED_view3d_camera_lock_check(v3d, rv3d))
1201                 return false;
1202
1203         if (rv3d->persp != RV3D_PERSP) {
1204                 if (rv3d->persp == RV3D_CAMOB) {
1205                         /* If autopersp and previous view was an axis one, switch back to PERSP mode, else reuse previous mode. */
1206                         char persp = (autopersp && RV3D_VIEW_IS_AXIS(rv3d->lview)) ? RV3D_PERSP : rv3d->lpersp;
1207                         view3d_persp_switch_from_camera(v3d, rv3d, persp);
1208                 }
1209                 else if (autopersp && RV3D_VIEW_IS_AXIS(rv3d->view)) {
1210                         rv3d->persp = RV3D_PERSP;
1211                 }
1212                 return true;
1213         }
1214
1215         return false;
1216 }
1217
1218 static int viewrotate_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1219 {
1220         ViewOpsData *vod;
1221
1222         /* makes op->customdata */
1223         viewops_data_alloc(C, op);
1224         vod = op->customdata;
1225
1226         /* poll should check but in some cases fails, see poll func for details */
1227         if (vod->rv3d->viewlock & RV3D_LOCKED) {
1228                 viewops_data_free(C, op);
1229                 return OPERATOR_PASS_THROUGH;
1230         }
1231
1232         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
1233
1234         /* switch from camera view when: */
1235         if (view3d_ensure_persp(vod->v3d, vod->ar)) {
1236                 /* If we're switching from camera view to the perspective one,
1237                  * need to tag viewport update, so camera vuew and borders
1238                  * are properly updated.
1239                  */
1240                 ED_region_tag_redraw(vod->ar);
1241         }
1242
1243         viewops_data_create(C, op, event);
1244
1245         if (ELEM(event->type, MOUSEPAN, MOUSEROTATE)) {
1246                 /* Rotate direction we keep always same */
1247                 int x, y;
1248
1249                 if (event->type == MOUSEPAN) {
1250                         if (U.uiflag2 & USER_TRACKPAD_NATURAL) {
1251                                 x = 2 * event->x - event->prevx;
1252                                 y = 2 * event->y - event->prevy;
1253                         }
1254                         else {
1255                                 x = event->prevx;
1256                                 y = event->prevy;
1257                         }
1258                 }
1259                 else {
1260                         /* MOUSEROTATE performs orbital rotation, so y axis delta is set to 0 */
1261                         x = event->prevx;
1262                         y = event->y;
1263                 }
1264
1265                 viewrotate_apply(vod, x, y);
1266                 ED_view3d_depth_tag_update(vod->rv3d);
1267
1268                 viewops_data_free(C, op);
1269
1270                 return OPERATOR_FINISHED;
1271         }
1272         else {
1273                 /* add temp handler */
1274                 WM_event_add_modal_handler(C, op);
1275
1276                 return OPERATOR_RUNNING_MODAL;
1277         }
1278 }
1279
1280 /* test for unlocked camera view in quad view */
1281 static int view3d_camera_user_poll(bContext *C)
1282 {
1283         View3D *v3d;
1284         ARegion *ar;
1285
1286         if (ED_view3d_context_user_region(C, &v3d, &ar)) {
1287                 RegionView3D *rv3d = ar->regiondata;
1288                 if (rv3d->persp == RV3D_CAMOB) {
1289                         return 1;
1290                 }
1291         }
1292
1293         return 0;
1294 }
1295
1296 static int view3d_lock_poll(bContext *C)
1297 {
1298         View3D *v3d = CTX_wm_view3d(C);
1299         if (v3d) {
1300                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
1301                 if (rv3d) {
1302                         return ED_view3d_offset_lock_check(v3d, rv3d);
1303                 }
1304         }
1305         return false;
1306 }
1307
1308 static void viewrotate_cancel(bContext *C, wmOperator *op)
1309 {
1310         viewops_data_free(C, op);
1311 }
1312
1313 void VIEW3D_OT_rotate(wmOperatorType *ot)
1314 {
1315         /* identifiers */
1316         ot->name = "Rotate View";
1317         ot->description = "Rotate the view";
1318         ot->idname = "VIEW3D_OT_rotate";
1319
1320         /* api callbacks */
1321         ot->invoke = viewrotate_invoke;
1322         ot->modal = viewrotate_modal;
1323         ot->poll = ED_operator_region_view3d_active;
1324         ot->cancel = viewrotate_cancel;
1325
1326         /* flags */
1327         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
1328 }
1329
1330 /** \name NDOF Utility Functions
1331  * \{ */
1332
1333 #define NDOF_HAS_TRANSLATE ((!ED_view3d_offset_lock_check(v3d, rv3d)) && !is_zero_v3(ndof->tvec))
1334 #define NDOF_HAS_ROTATE    (((rv3d->viewlock & RV3D_LOCKED) == 0) && !is_zero_v3(ndof->rvec))
1335
1336 /**
1337  * \param depth_pt: A point to calculate the depth (in perspective mode)
1338  */
1339 static float view3d_ndof_pan_speed_calc_ex(RegionView3D *rv3d, const float depth_pt[3])
1340 {
1341         float speed = rv3d->pixsize * NDOF_PIXELS_PER_SECOND;
1342
1343         if (rv3d->is_persp) {
1344                 speed *= ED_view3d_calc_zfac(rv3d, depth_pt, NULL);
1345         }
1346
1347         return speed;
1348 }
1349
1350 static float view3d_ndof_pan_speed_calc_from_dist(RegionView3D *rv3d, const float dist)
1351 {
1352         float viewinv[4];
1353         float tvec[3];
1354
1355         BLI_assert(dist >= 0.0f);
1356
1357         copy_v3_fl3(tvec, 0.0f, 0.0f, dist);
1358         /* rv3d->viewinv isn't always valid */
1359 #if 0
1360         mul_mat3_m4_v3(rv3d->viewinv, tvec);
1361 #else
1362         invert_qt_qt_normalized(viewinv, rv3d->viewquat);
1363         mul_qt_v3(viewinv, tvec);
1364 #endif
1365
1366         return view3d_ndof_pan_speed_calc_ex(rv3d, tvec);
1367 }
1368
1369 static float view3d_ndof_pan_speed_calc(RegionView3D *rv3d)
1370 {
1371         float tvec[3];
1372         negate_v3_v3(tvec, rv3d->ofs);
1373
1374         return view3d_ndof_pan_speed_calc_ex(rv3d, tvec);
1375 }
1376
1377 /**
1378  * Zoom and pan in the same function since sometimes zoom is interpreted as dolly (pan forward).
1379  *
1380  * \param has_zoom zoom, otherwise dolly, often `!rv3d->is_persp` since it doesnt make sense to dolly in ortho.
1381  */
1382 static void view3d_ndof_pan_zoom(const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
1383                                  const bool has_translate, const bool has_zoom)
1384 {
1385         RegionView3D *rv3d = ar->regiondata;
1386         float view_inv[4];
1387         float pan_vec[3];
1388
1389         if (has_translate == false && has_zoom == false) {
1390                 return;
1391         }
1392
1393         WM_event_ndof_pan_get(ndof, pan_vec, false);
1394
1395         if (has_zoom) {
1396                 /* zoom with Z */
1397
1398                 /* Zoom!
1399                  * velocity should be proportional to the linear velocity attained by rotational motion of same strength
1400                  * [got that?]
1401                  * proportional to arclength = radius * angle
1402                  */
1403
1404                 pan_vec[2] = 0.0f;
1405
1406                 /* "zoom in" or "translate"? depends on zoom mode in user settings? */
1407                 if (ndof->tvec[2]) {
1408                         float zoom_distance = rv3d->dist * ndof->dt * ndof->tvec[2];
1409
1410                         if (U.ndof_flag & NDOF_ZOOM_INVERT)
1411                                 zoom_distance = -zoom_distance;
1412
1413                         rv3d->dist += zoom_distance;
1414                 }
1415         }
1416         else {
1417                 /* dolly with Z */
1418
1419                 /* all callers must check */
1420                 if (has_translate) {
1421                         BLI_assert(ED_view3d_offset_lock_check((View3D *)sa->spacedata.first, rv3d) == false);
1422                 }
1423         }
1424
1425         if (has_translate) {
1426                 const float speed = view3d_ndof_pan_speed_calc(rv3d);
1427
1428                 mul_v3_fl(pan_vec, speed * ndof->dt);
1429
1430                 /* transform motion from view to world coordinates */
1431                 invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1432                 mul_qt_v3(view_inv, pan_vec);
1433
1434                 /* move center of view opposite of hand motion (this is camera mode, not object mode) */
1435                 sub_v3_v3(rv3d->ofs, pan_vec);
1436
1437                 if (rv3d->viewlock & RV3D_BOXVIEW) {
1438                         view3d_boxview_sync(sa, ar);
1439                 }
1440         }
1441 }
1442
1443
1444 static void view3d_ndof_orbit(const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
1445                               /* optional, can be NULL*/
1446                               ViewOpsData *vod)
1447 {
1448         View3D *v3d = sa->spacedata.first;
1449         RegionView3D *rv3d = ar->regiondata;
1450
1451         float view_inv[4];
1452
1453         BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
1454
1455         view3d_ensure_persp(v3d, ar);
1456
1457         rv3d->view = RV3D_VIEW_USER;
1458
1459         invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1460
1461         if (U.ndof_flag & NDOF_TURNTABLE) {
1462                 float rot[3];
1463
1464                 /* turntable view code by John Aughey, adapted for 3D mouse by [mce] */
1465                 float angle, quat[4];
1466                 float xvec[3] = {1, 0, 0};
1467
1468                 /* only use XY, ignore Z */
1469                 WM_event_ndof_rotate_get(ndof, rot);
1470
1471                 /* Determine the direction of the x vector (for rotating up and down) */
1472                 mul_qt_v3(view_inv, xvec);
1473
1474                 /* Perform the up/down rotation */
1475                 angle = ndof->dt * rot[0];
1476                 axis_angle_to_quat(quat, xvec, angle);
1477                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1478
1479                 /* Perform the orbital rotation */
1480                 angle = ndof->dt * rot[1];
1481
1482                 /* update the onscreen doo-dad */
1483                 rv3d->rot_angle = angle;
1484                 rv3d->rot_axis[0] = 0;
1485                 rv3d->rot_axis[1] = 0;
1486                 rv3d->rot_axis[2] = 1;
1487
1488                 axis_angle_to_quat_single(quat, 'Z', angle);
1489                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1490
1491         }
1492         else {
1493                 float quat[4];
1494                 float axis[3];
1495                 float angle = WM_event_ndof_to_axis_angle(ndof, axis);
1496
1497                 /* transform rotation axis from view to world coordinates */
1498                 mul_qt_v3(view_inv, axis);
1499
1500                 /* update the onscreen doo-dad */
1501                 rv3d->rot_angle = angle;
1502                 copy_v3_v3(rv3d->rot_axis, axis);
1503
1504                 axis_angle_to_quat(quat, axis, angle);
1505
1506                 /* apply rotation */
1507                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1508         }
1509
1510         if (vod) {
1511                 viewrotate_apply_dyn_ofs(vod, rv3d->viewquat);
1512         }
1513 }
1514
1515 /**
1516  * Called from both fly mode and walk mode,
1517  */
1518 void view3d_ndof_fly(
1519         const wmNDOFMotionData *ndof,
1520         View3D *v3d, RegionView3D *rv3d,
1521         const bool use_precision, const short protectflag,
1522         bool *r_has_translate, bool *r_has_rotate)
1523 {
1524         bool has_translate = NDOF_HAS_TRANSLATE;
1525         bool has_rotate = NDOF_HAS_ROTATE;
1526
1527         float view_inv[4];
1528         invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1529
1530         rv3d->rot_angle = 0.0f;  /* disable onscreen rotation doo-dad */
1531
1532         if (has_translate) {
1533                 /* ignore real 'dist' since fly has its own speed settings,
1534                  * also its overwritten at this point. */
1535                 float speed = view3d_ndof_pan_speed_calc_from_dist(rv3d, 1.0f);
1536                 float trans[3], trans_orig_y;
1537
1538                 if (use_precision)
1539                         speed *= 0.2f;
1540
1541                 WM_event_ndof_pan_get(ndof, trans, false);
1542                 mul_v3_fl(trans, speed * ndof->dt);
1543                 trans_orig_y = trans[1];
1544
1545                 if (U.ndof_flag & NDOF_FLY_HELICOPTER) {
1546                         trans[1] = 0.0f;
1547                 }
1548
1549                 /* transform motion from view to world coordinates */
1550                 mul_qt_v3(view_inv, trans);
1551
1552                 if (U.ndof_flag & NDOF_FLY_HELICOPTER) {
1553                         /* replace world z component with device y (yes it makes sense) */
1554                         trans[2] = trans_orig_y;
1555                 }
1556
1557                 if (rv3d->persp == RV3D_CAMOB) {
1558                         /* respect camera position locks */
1559                         if (protectflag & OB_LOCK_LOCX) trans[0] = 0.0f;
1560                         if (protectflag & OB_LOCK_LOCY) trans[1] = 0.0f;
1561                         if (protectflag & OB_LOCK_LOCZ) trans[2] = 0.0f;
1562                 }
1563
1564                 if (!is_zero_v3(trans)) {
1565                         /* move center of view opposite of hand motion (this is camera mode, not object mode) */
1566                         sub_v3_v3(rv3d->ofs, trans);
1567                         has_translate = true;
1568                 }
1569                 else {
1570                         has_translate = false;
1571                 }
1572         }
1573
1574         if (has_rotate) {
1575                 const float turn_sensitivity = 1.0f;
1576
1577                 float rotation[4];
1578                 float axis[3];
1579                 float angle = turn_sensitivity * WM_event_ndof_to_axis_angle(ndof, axis);
1580
1581                 if (fabsf(angle) > 0.0001f) {
1582                         has_rotate = true;
1583
1584                         if (use_precision)
1585                                 angle *= 0.2f;
1586
1587                         /* transform rotation axis from view to world coordinates */
1588                         mul_qt_v3(view_inv, axis);
1589
1590                         /* apply rotation to view */
1591                         axis_angle_to_quat(rotation, axis, angle);
1592                         mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rotation);
1593
1594                         if (U.ndof_flag & NDOF_LOCK_HORIZON) {
1595                                 /* force an upright viewpoint
1596                                  * TODO: make this less... sudden */
1597                                 float view_horizon[3] = {1.0f, 0.0f, 0.0f}; /* view +x */
1598                                 float view_direction[3] = {0.0f, 0.0f, -1.0f}; /* view -z (into screen) */
1599
1600                                 /* find new inverse since viewquat has changed */
1601                                 invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1602                                 /* could apply reverse rotation to existing view_inv to save a few cycles */
1603
1604                                 /* transform view vectors to world coordinates */
1605                                 mul_qt_v3(view_inv, view_horizon);
1606                                 mul_qt_v3(view_inv, view_direction);
1607
1608
1609                                 /* find difference between view & world horizons
1610                                  * true horizon lives in world xy plane, so look only at difference in z */
1611                                 angle = -asinf(view_horizon[2]);
1612
1613                                 /* rotate view so view horizon = world horizon */
1614                                 axis_angle_to_quat(rotation, view_direction, angle);
1615                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rotation);
1616                         }
1617
1618                         rv3d->view = RV3D_VIEW_USER;
1619                 }
1620                 else {
1621                         has_rotate = false;
1622                 }
1623         }
1624
1625         *r_has_translate = has_translate;
1626         *r_has_rotate    = has_rotate;
1627 }
1628
1629 /** \} */
1630
1631
1632 /* -- "orbit" navigation (trackball/turntable)
1633  * -- zooming
1634  * -- panning in rotationally-locked views
1635  */
1636 static int ndof_orbit_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1637 {
1638         
1639         if (event->type != NDOF_MOTION) {
1640                 return OPERATOR_CANCELLED;
1641         }
1642         else {
1643                 ViewOpsData *vod;
1644                 View3D *v3d;
1645                 RegionView3D *rv3d;
1646
1647                 const wmNDOFMotionData *ndof = event->customdata;
1648
1649                 viewops_data_alloc(C, op);
1650                 viewops_data_create_ex(C, op, event,
1651                                        (U.uiflag & USER_ORBIT_SELECTION) != 0, false);
1652                 vod = op->customdata;
1653
1654                 ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
1655
1656                 v3d = vod->v3d;
1657                 rv3d = vod->rv3d;
1658
1659                 /* off by default, until changed later this function */
1660                 rv3d->rot_angle = 0.0f;
1661
1662                 ED_view3d_camera_lock_init_ex(v3d, rv3d, false);
1663
1664                 if (ndof->progress != P_FINISHING) {
1665                         const bool has_rotation = NDOF_HAS_ROTATE;
1666                         /* if we can't rotate, fallback to translate (locked axis views) */
1667                         const bool has_translate = NDOF_HAS_TRANSLATE && (rv3d->viewlock & RV3D_LOCKED);
1668                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1669
1670                         if (has_translate || has_zoom) {
1671                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, has_zoom);
1672                         }
1673
1674                         if (has_rotation) {
1675                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod);
1676                         }
1677                 }
1678
1679                 ED_view3d_camera_lock_sync(v3d, rv3d);
1680
1681                 ED_region_tag_redraw(vod->ar);
1682
1683                 viewops_data_free(C, op);
1684
1685                 return OPERATOR_FINISHED;
1686         }
1687 }
1688
1689 void VIEW3D_OT_ndof_orbit(struct wmOperatorType *ot)
1690 {
1691         /* identifiers */
1692         ot->name = "NDOF Orbit View";
1693         ot->description = "Orbit the view using the 3D mouse";
1694         ot->idname = "VIEW3D_OT_ndof_orbit";
1695
1696         /* api callbacks */
1697         ot->invoke = ndof_orbit_invoke;
1698         ot->poll = ED_operator_view3d_active;
1699
1700         /* flags */
1701         ot->flag = 0;
1702 }
1703
1704 static int ndof_orbit_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1705 {
1706         
1707         if (event->type != NDOF_MOTION) {
1708                 return OPERATOR_CANCELLED;
1709         }
1710         else {
1711                 ViewOpsData *vod;
1712                 View3D *v3d;
1713                 RegionView3D *rv3d;
1714
1715                 const wmNDOFMotionData *ndof = event->customdata;
1716
1717                 viewops_data_alloc(C, op);
1718                 viewops_data_create_ex(C, op, event,
1719                                        (U.uiflag & USER_ORBIT_SELECTION) != 0, false);
1720
1721                 vod = op->customdata;
1722
1723                 ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
1724
1725                 v3d = vod->v3d;
1726                 rv3d = vod->rv3d;
1727
1728                 /* off by default, until changed later this function */
1729                 rv3d->rot_angle = 0.0f;
1730
1731                 ED_view3d_camera_lock_init_ex(v3d, rv3d, false);
1732
1733                 if (ndof->progress == P_FINISHING) {
1734                         /* pass */
1735                 }
1736                 else if ((rv3d->persp == RV3D_ORTHO) && RV3D_VIEW_IS_AXIS(rv3d->view)) {
1737                         /* if we can't rotate, fallback to translate (locked axis views) */
1738                         const bool has_translate = NDOF_HAS_TRANSLATE;
1739                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && ED_view3d_offset_lock_check(v3d, rv3d);
1740
1741                         if (has_translate || has_zoom) {
1742                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, true);
1743                         }
1744                 }
1745                 else if ((U.ndof_flag & NDOF_MODE_ORBIT) ||
1746                          ED_view3d_offset_lock_check(v3d, rv3d))
1747                 {
1748                         const bool has_rotation = NDOF_HAS_ROTATE;
1749                         const bool has_zoom = (ndof->tvec[2] != 0.0f);
1750
1751                         if (has_zoom) {
1752                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, false, has_zoom);
1753                         }
1754
1755                         if (has_rotation) {
1756                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod);
1757                         }
1758                 }
1759                 else {  /* free/explore (like fly mode) */
1760                         const bool has_rotation = NDOF_HAS_ROTATE;
1761                         const bool has_translate = NDOF_HAS_TRANSLATE;
1762                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1763
1764                         float dist_backup;
1765
1766                         if (has_translate || has_zoom) {
1767                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, has_zoom);
1768                         }
1769
1770                         dist_backup = rv3d->dist;
1771                         ED_view3d_distance_set(rv3d, 0.0f);
1772
1773                         if (has_rotation) {
1774                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, NULL);
1775                         }
1776
1777                         ED_view3d_distance_set(rv3d, dist_backup);
1778                 }
1779
1780                 ED_view3d_camera_lock_sync(v3d, rv3d);
1781
1782                 ED_region_tag_redraw(vod->ar);
1783
1784                 viewops_data_free(C, op);
1785
1786                 return OPERATOR_FINISHED;
1787         }
1788 }
1789
1790 void VIEW3D_OT_ndof_orbit_zoom(struct wmOperatorType *ot)
1791 {
1792         /* identifiers */
1793         ot->name = "NDOF Orbit View with Zoom";
1794         ot->description = "Orbit and zoom the view using the 3D mouse";
1795         ot->idname = "VIEW3D_OT_ndof_orbit_zoom";
1796
1797         /* api callbacks */
1798         ot->invoke = ndof_orbit_zoom_invoke;
1799         ot->poll = ED_operator_view3d_active;
1800
1801         /* flags */
1802         ot->flag = 0;
1803 }
1804
1805 /* -- "pan" navigation
1806  * -- zoom or dolly?
1807  */
1808 static int ndof_pan_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
1809 {
1810         if (event->type != NDOF_MOTION) {
1811                 return OPERATOR_CANCELLED;
1812         }
1813         else {
1814                 View3D *v3d = CTX_wm_view3d(C);
1815                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
1816                 const wmNDOFMotionData *ndof = event->customdata;
1817
1818                 const bool has_translate = NDOF_HAS_TRANSLATE;
1819                 const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1820
1821                 /* we're panning here! so erase any leftover rotation from other operators */
1822                 rv3d->rot_angle = 0.0f;
1823
1824                 if (!(has_translate || has_zoom))
1825                         return OPERATOR_CANCELLED;
1826
1827                 ED_view3d_camera_lock_init_ex(v3d, rv3d, false);
1828
1829                 if (ndof->progress != P_FINISHING) {
1830                         ScrArea *sa = CTX_wm_area(C);
1831                         ARegion *ar = CTX_wm_region(C);
1832
1833                         if (has_translate || has_zoom) {
1834                                 view3d_ndof_pan_zoom(ndof, sa, ar, has_translate, has_zoom);
1835                         }
1836                 }
1837
1838                 ED_view3d_camera_lock_sync(v3d, rv3d);
1839
1840                 ED_region_tag_redraw(CTX_wm_region(C));
1841
1842                 return OPERATOR_FINISHED;
1843         }
1844 }
1845
1846 void VIEW3D_OT_ndof_pan(struct wmOperatorType *ot)
1847 {
1848         /* identifiers */
1849         ot->name = "NDOF Pan View";
1850         ot->description = "Pan the view with the 3D mouse";
1851         ot->idname = "VIEW3D_OT_ndof_pan";
1852
1853         /* api callbacks */
1854         ot->invoke = ndof_pan_invoke;
1855         ot->poll = ED_operator_view3d_active;
1856
1857         /* flags */
1858         ot->flag = 0;
1859 }
1860
1861
1862 /**
1863  * wraps #ndof_orbit_zoom but never restrict to orbit.
1864  */
1865 static int ndof_all_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1866 {
1867         /* weak!, but it works */
1868         const int ndof_flag = U.ndof_flag;
1869         int ret;
1870
1871         U.ndof_flag &= ~NDOF_MODE_ORBIT;
1872
1873         ret = ndof_orbit_zoom_invoke(C, op, event);
1874
1875         U.ndof_flag = ndof_flag;
1876
1877         return ret;
1878 }
1879
1880 void VIEW3D_OT_ndof_all(struct wmOperatorType *ot)
1881 {
1882         /* identifiers */
1883         ot->name = "NDOF Move View";
1884         ot->description = "Pan and rotate the view with the 3D mouse";
1885         ot->idname = "VIEW3D_OT_ndof_all";
1886
1887         /* api callbacks */
1888         ot->invoke = ndof_all_invoke;
1889         ot->poll = ED_operator_view3d_active;
1890
1891         /* flags */
1892         ot->flag = 0;
1893 }
1894
1895 /* ************************ viewmove ******************************** */
1896
1897
1898 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
1899
1900 /* called in transform_ops.c, on each regeneration of keymaps  */
1901 void viewmove_modal_keymap(wmKeyConfig *keyconf)
1902 {
1903         static EnumPropertyItem modal_items[] = {
1904                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
1905                 
1906                 {VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
1907                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
1908
1909                 {0, NULL, 0, NULL, NULL}
1910         };
1911
1912         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Move Modal");
1913
1914         /* this function is called for each spacetype, only needs to add map once */
1915         if (keymap && keymap->modal_items) return;
1916
1917         keymap = WM_modalkeymap_add(keyconf, "View3D Move Modal", modal_items);
1918
1919         /* items for modal map */
1920         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1921         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1922
1923         /* disabled mode switching for now, can re-implement better, later on */
1924 #if 0
1925         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1926         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1927         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1928 #endif
1929         
1930         /* assign map to operators */
1931         WM_modalkeymap_assign(keymap, "VIEW3D_OT_move");
1932 }
1933
1934
1935 static void viewmove_apply(ViewOpsData *vod, int x, int y)
1936 {
1937         if (ED_view3d_offset_lock_check(vod->v3d, vod->rv3d)) {
1938                 vod->rv3d->ofs_lock[0] -= ((vod->oldx - x) * 2.0f) / (float)vod->ar->winx;
1939                 vod->rv3d->ofs_lock[1] -= ((vod->oldy - y) * 2.0f) / (float)vod->ar->winy;
1940         }
1941         else if ((vod->rv3d->persp == RV3D_CAMOB) && !ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) {
1942                 const float zoomfac = BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
1943                 vod->rv3d->camdx += (vod->oldx - x) / (vod->ar->winx * zoomfac);
1944                 vod->rv3d->camdy += (vod->oldy - y) / (vod->ar->winy * zoomfac);
1945                 CLAMP(vod->rv3d->camdx, -1.0f, 1.0f);
1946                 CLAMP(vod->rv3d->camdy, -1.0f, 1.0f);
1947         }
1948         else {
1949                 float dvec[3];
1950                 float mval_f[2];
1951
1952                 mval_f[0] = x - vod->oldx;
1953                 mval_f[1] = y - vod->oldy;
1954                 ED_view3d_win_to_delta(vod->ar, mval_f, dvec, vod->zfac);
1955
1956                 add_v3_v3(vod->rv3d->ofs, dvec);
1957
1958                 if (vod->rv3d->viewlock & RV3D_BOXVIEW)
1959                         view3d_boxview_sync(vod->sa, vod->ar);
1960         }
1961
1962         vod->oldx = x;
1963         vod->oldy = y;
1964
1965         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
1966
1967         ED_region_tag_redraw(vod->ar);
1968 }
1969
1970
1971 static int viewmove_modal(bContext *C, wmOperator *op, const wmEvent *event)
1972 {
1973
1974         ViewOpsData *vod = op->customdata;
1975         short event_code = VIEW_PASS;
1976         bool use_autokey = false;
1977         int ret = OPERATOR_RUNNING_MODAL;
1978
1979         /* execute the events */
1980         if (event->type == MOUSEMOVE) {
1981                 event_code = VIEW_APPLY;
1982         }
1983         else if (event->type == EVT_MODAL_MAP) {
1984                 switch (event->val) {
1985                         case VIEW_MODAL_CONFIRM:
1986                                 event_code = VIEW_CONFIRM;
1987                                 break;
1988                         case VIEWROT_MODAL_SWITCH_ZOOM:
1989                                 WM_operator_name_call(C, "VIEW3D_OT_zoom", WM_OP_INVOKE_DEFAULT, NULL);
1990                                 event_code = VIEW_CONFIRM;
1991                                 break;
1992                         case VIEWROT_MODAL_SWITCH_ROTATE:
1993                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
1994                                 event_code = VIEW_CONFIRM;
1995                                 break;
1996                 }
1997         }
1998         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
1999                 event_code = VIEW_CONFIRM;
2000         }
2001
2002         if (event_code == VIEW_APPLY) {
2003                 viewmove_apply(vod, event->x, event->y);
2004                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2005                         use_autokey = true;
2006                 }
2007         }
2008         else if (event_code == VIEW_CONFIRM) {
2009                 ED_view3d_depth_tag_update(vod->rv3d);
2010                 use_autokey = true;
2011                 ret = OPERATOR_FINISHED;
2012         }
2013
2014         if (use_autokey) {
2015                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2016         }
2017
2018         if (ret & OPERATOR_FINISHED) {
2019                 viewops_data_free(C, op);
2020         }
2021
2022         return ret;
2023 }
2024
2025 static int viewmove_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2026 {
2027         ViewOpsData *vod;
2028
2029         /* makes op->customdata */
2030         viewops_data_alloc(C, op);
2031         viewops_data_create(C, op, event);
2032         vod = op->customdata;
2033
2034         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
2035
2036         if (event->type == MOUSEPAN) {
2037                 /* invert it, trackpad scroll follows same principle as 2d windows this way */
2038                 viewmove_apply(vod, 2 * event->x - event->prevx, 2 * event->y - event->prevy);
2039                 ED_view3d_depth_tag_update(vod->rv3d);
2040                 
2041                 viewops_data_free(C, op);
2042                 
2043                 return OPERATOR_FINISHED;
2044         }
2045         else {
2046                 /* add temp handler */
2047                 WM_event_add_modal_handler(C, op);
2048
2049                 return OPERATOR_RUNNING_MODAL;
2050         }
2051 }
2052
2053 static void viewmove_cancel(bContext *C, wmOperator *op)
2054 {
2055         viewops_data_free(C, op);
2056 }
2057
2058 void VIEW3D_OT_move(wmOperatorType *ot)
2059 {
2060
2061         /* identifiers */
2062         ot->name = "Move View";
2063         ot->description = "Move the view";
2064         ot->idname = "VIEW3D_OT_move";
2065
2066         /* api callbacks */
2067         ot->invoke = viewmove_invoke;
2068         ot->modal = viewmove_modal;
2069         ot->poll = ED_operator_view3d_active;
2070         ot->cancel = viewmove_cancel;
2071
2072         /* flags */
2073         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2074 }
2075
2076 /* ************************ viewzoom ******************************** */
2077
2078 /* viewdolly_modal_keymap has an exact copy of this, apply fixes to both */
2079 /* called in transform_ops.c, on each regeneration of keymaps  */
2080 void viewzoom_modal_keymap(wmKeyConfig *keyconf)
2081 {
2082         static EnumPropertyItem modal_items[] = {
2083                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
2084                 
2085                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
2086                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
2087
2088                 {0, NULL, 0, NULL, NULL}
2089         };
2090
2091         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Zoom Modal");
2092
2093         /* this function is called for each spacetype, only needs to add map once */
2094         if (keymap && keymap->modal_items) return;
2095
2096         keymap = WM_modalkeymap_add(keyconf, "View3D Zoom Modal", modal_items);
2097
2098         /* items for modal map */
2099         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2100         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2101
2102         /* disabled mode switching for now, can re-implement better, later on */
2103 #if 0
2104         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2105         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2106         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
2107 #endif
2108         
2109         /* assign map to operators */
2110         WM_modalkeymap_assign(keymap, "VIEW3D_OT_zoom");
2111 }
2112
2113 static void view_zoom_mouseloc_camera(
2114         Scene *scene, View3D *v3d,
2115         ARegion *ar, float dfac, int mx, int my)
2116 {
2117         RegionView3D *rv3d = ar->regiondata;
2118         const float zoomfac = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
2119         const float zoomfac_new = CLAMPIS(zoomfac * (1.0f / dfac), RV3D_CAMZOOM_MIN_FACTOR, RV3D_CAMZOOM_MAX_FACTOR);
2120         const float camzoom_new = BKE_screen_view3d_zoom_from_fac(zoomfac_new);
2121
2122
2123         if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
2124                 float zoomfac_px;
2125                 rctf camera_frame_old;
2126                 rctf camera_frame_new;
2127
2128                 const float pt_src[2] = {mx, my};
2129                 float pt_dst[2];
2130                 float delta_px[2];
2131
2132                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &camera_frame_old, false);
2133                 BLI_rctf_translate(&camera_frame_old, ar->winrct.xmin, ar->winrct.ymin);
2134
2135                 rv3d->camzoom = camzoom_new;
2136                 CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
2137
2138                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &camera_frame_new, false);
2139                 BLI_rctf_translate(&camera_frame_new, ar->winrct.xmin, ar->winrct.ymin);
2140
2141                 BLI_rctf_transform_pt_v(&camera_frame_new, &camera_frame_old, pt_dst, pt_src);
2142                 sub_v2_v2v2(delta_px, pt_dst, pt_src);
2143
2144                 /* translate the camera offset using pixel space delta
2145                  * mapped back to the camera (same logic as panning in camera view) */
2146                 zoomfac_px = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom) * 2.0f;
2147
2148                 rv3d->camdx += delta_px[0] / (ar->winx * zoomfac_px);
2149                 rv3d->camdy += delta_px[1] / (ar->winy * zoomfac_px);
2150                 CLAMP(rv3d->camdx, -1.0f, 1.0f);
2151                 CLAMP(rv3d->camdy, -1.0f, 1.0f);
2152         }
2153         else {
2154                 rv3d->camzoom = camzoom_new;
2155                 CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
2156         }
2157 }
2158
2159 static void view_zoom_mouseloc_3d(ARegion *ar, float dfac, int mx, int my)
2160 {
2161         RegionView3D *rv3d = ar->regiondata;
2162         const float dist_new = rv3d->dist * dfac;
2163
2164         if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
2165                 float dvec[3];
2166                 float tvec[3];
2167                 float tpos[3];
2168                 float mval_f[2];
2169
2170                 float zfac;
2171
2172                 negate_v3_v3(tpos, rv3d->ofs);
2173
2174                 mval_f[0] = (float)(((mx - ar->winrct.xmin) * 2) - ar->winx) / 2.0f;
2175                 mval_f[1] = (float)(((my - ar->winrct.ymin) * 2) - ar->winy) / 2.0f;
2176
2177                 /* Project cursor position into 3D space */
2178                 zfac = ED_view3d_calc_zfac(rv3d, tpos, NULL);
2179                 ED_view3d_win_to_delta(ar, mval_f, dvec, zfac);
2180
2181                 /* Calculate view target position for dolly */
2182                 add_v3_v3v3(tvec, tpos, dvec);
2183                 negate_v3(tvec);
2184
2185                 /* Offset to target position and dolly */
2186                 copy_v3_v3(rv3d->ofs, tvec);
2187                 rv3d->dist = dist_new;
2188
2189                 /* Calculate final offset */
2190                 madd_v3_v3v3fl(rv3d->ofs, tvec, dvec, dfac);
2191         }
2192         else {
2193                 rv3d->dist = dist_new;
2194         }
2195 }
2196
2197 static float viewzoom_scale_value(
2198         const rcti *winrct,
2199         const short viewzoom,
2200         const bool zoom_invert, const bool zoom_invert_force,
2201         const int xy[2], const int xy_orig[2],
2202         const float val, const float val_orig,
2203         double *r_timer_lastdraw)
2204 {
2205         float zfac;
2206
2207         if (viewzoom == USER_ZOOM_CONT) {
2208                 double time = PIL_check_seconds_timer();
2209                 float time_step = (float)(time - *r_timer_lastdraw);
2210                 float fac;
2211
2212                 if (U.uiflag & USER_ZOOM_HORIZ) {
2213                         fac = (float)(xy_orig[0] - xy[0]);
2214                 }
2215                 else {
2216                         fac = (float)(xy_orig[1] - xy[1]);
2217                 }
2218
2219                 if (zoom_invert != zoom_invert_force) {
2220                         fac = -fac;
2221                 }
2222
2223                 /* oldstyle zoom */
2224                 zfac = 1.0f + ((fac / 20.0f) * time_step);
2225                 *r_timer_lastdraw = time;
2226         }
2227         else if (viewzoom == USER_ZOOM_SCALE) {
2228                 /* method which zooms based on how far you move the mouse */
2229
2230                 const int ctr[2] = {
2231                     BLI_rcti_cent_x(winrct),
2232                     BLI_rcti_cent_y(winrct),
2233                 };
2234                 float len_new = 5 + len_v2v2_int(ctr, xy);
2235                 float len_old = 5 + len_v2v2_int(ctr, xy_orig);
2236
2237                 /* intentionally ignore 'zoom_invert' for scale */
2238                 if (zoom_invert_force) {
2239                         SWAP(float, len_new, len_old);
2240                 }
2241
2242                 zfac = val_orig * (len_old / max_ff(len_new, 1.0f)) / val;
2243         }
2244         else {  /* USER_ZOOM_DOLLY */
2245                 float len_new = 5;
2246                 float len_old = 5;
2247
2248                 if (U.uiflag & USER_ZOOM_HORIZ) {
2249                         len_new += (winrct->xmax - xy[0]);
2250                         len_old += (winrct->xmax - xy_orig[0]);
2251                 }
2252                 else {
2253                         len_new += (winrct->ymax - xy[1]);
2254                         len_old += (winrct->ymax - xy_orig[1]);
2255                 }
2256
2257                 if (zoom_invert != zoom_invert_force) {
2258                         SWAP(float, len_new, len_old);
2259                 }
2260
2261                 zfac = val_orig * (2.0f * ((len_new / max_ff(len_old, 1.0f)) - 1.0f) + 1.0f) / val;
2262         }
2263
2264
2265         return zfac;
2266 }
2267
2268 static void viewzoom_apply_camera(
2269         ViewOpsData *vod, const int xy[2],
2270         const short viewzoom, const bool zoom_invert)
2271 {
2272         float zfac;
2273         float zoomfac_prev = BKE_screen_view3d_zoom_to_fac(vod->camzoom_prev) * 2.0f;
2274         float zoomfac =      BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
2275
2276         zfac = viewzoom_scale_value(
2277                &vod->ar->winrct, viewzoom, zoom_invert, true, xy, &vod->origx,
2278                zoomfac, zoomfac_prev,
2279                &vod->timer_lastdraw);
2280
2281         if (zfac != 1.0f && zfac != 0.0f) {
2282                 /* calculate inverted, then invert again (needed because of camera zoom scaling) */
2283                 zfac = 1.0f / zfac;
2284                 view_zoom_mouseloc_camera(
2285                         vod->scene, vod->v3d,
2286                         vod->ar, zfac, vod->oldx, vod->oldy);
2287         }
2288
2289         ED_region_tag_redraw(vod->ar);
2290 }
2291
2292 static void viewzoom_apply_3d(
2293         ViewOpsData *vod, const int xy[2],
2294         const short viewzoom, const bool zoom_invert)
2295 {
2296         float zfac;
2297         float dist_range[2];
2298
2299         ED_view3d_dist_range_get(vod->v3d, dist_range);
2300
2301         zfac = viewzoom_scale_value(
2302                &vod->ar->winrct, viewzoom, zoom_invert, false, xy, &vod->origx,
2303                vod->rv3d->dist, vod->dist_prev,
2304                &vod->timer_lastdraw);
2305
2306         if (zfac != 1.0f) {
2307                 const float zfac_min = dist_range[0] / vod->rv3d->dist;
2308                 const float zfac_max = dist_range[1] / vod->rv3d->dist;
2309                 CLAMP(zfac, zfac_min, zfac_max);
2310
2311                 view_zoom_mouseloc_3d(
2312                         vod->ar, zfac, vod->oldx, vod->oldy);
2313         }
2314
2315         /* these limits were in old code too */
2316         CLAMP(vod->rv3d->dist, dist_range[0], dist_range[1]);
2317
2318         if (vod->rv3d->viewlock & RV3D_BOXVIEW)
2319                 view3d_boxview_sync(vod->sa, vod->ar);
2320
2321         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
2322
2323         ED_region_tag_redraw(vod->ar);
2324 }
2325
2326 static void viewzoom_apply(
2327         ViewOpsData *vod, const int xy[2],
2328         const short viewzoom, const bool zoom_invert)
2329 {
2330         if ((vod->rv3d->persp == RV3D_CAMOB) &&
2331             (vod->rv3d->is_persp && ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) == 0)
2332         {
2333                 viewzoom_apply_camera(vod, xy, viewzoom, zoom_invert);
2334         }
2335         else {
2336                 viewzoom_apply_3d(vod, xy, viewzoom, zoom_invert);
2337         }
2338 }
2339
2340 static int viewzoom_modal(bContext *C, wmOperator *op, const wmEvent *event)
2341 {
2342         ViewOpsData *vod = op->customdata;
2343         short event_code = VIEW_PASS;
2344         bool use_autokey = false;
2345         int ret = OPERATOR_RUNNING_MODAL;
2346
2347         /* execute the events */
2348         if (event->type == TIMER && event->customdata == vod->timer) {
2349                 /* continuous zoom */
2350                 event_code = VIEW_APPLY;
2351         }
2352         else if (event->type == MOUSEMOVE) {
2353                 event_code = VIEW_APPLY;
2354         }
2355         else if (event->type == EVT_MODAL_MAP) {
2356                 switch (event->val) {
2357                         case VIEW_MODAL_CONFIRM:
2358                                 event_code = VIEW_CONFIRM;
2359                                 break;
2360                         case VIEWROT_MODAL_SWITCH_MOVE:
2361                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
2362                                 event_code = VIEW_CONFIRM;
2363                                 break;
2364                         case VIEWROT_MODAL_SWITCH_ROTATE:
2365                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
2366                                 event_code = VIEW_CONFIRM;
2367                                 break;
2368                 }
2369         }
2370         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
2371                 event_code = VIEW_CONFIRM;
2372         }
2373
2374         if (event_code == VIEW_APPLY) {
2375                 viewzoom_apply(vod, &event->x, U.viewzoom, (U.uiflag & USER_ZOOM_INVERT) != 0);
2376                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2377                         use_autokey = true;
2378                 }
2379         }
2380         else if (event_code == VIEW_CONFIRM) {
2381                 ED_view3d_depth_tag_update(vod->rv3d);
2382                 use_autokey = true;
2383                 ret = OPERATOR_FINISHED;
2384         }
2385
2386         if (use_autokey) {
2387                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2388         }
2389
2390         if (ret & OPERATOR_FINISHED) {
2391                 viewops_data_free(C, op);
2392         }
2393
2394         return ret;
2395 }
2396
2397 static int viewzoom_exec(bContext *C, wmOperator *op)
2398 {
2399         Scene *scene = CTX_data_scene(C);
2400         View3D *v3d;
2401         RegionView3D *rv3d;
2402         ScrArea *sa;
2403         ARegion *ar;
2404         bool use_cam_zoom;
2405         float dist_range[2];
2406
2407         const int delta = RNA_int_get(op->ptr, "delta");
2408         int mx, my;
2409
2410         if (op->customdata) {
2411                 ViewOpsData *vod = op->customdata;
2412
2413                 sa = vod->sa;
2414                 ar = vod->ar;
2415         }
2416         else {
2417                 sa = CTX_wm_area(C);
2418                 ar = CTX_wm_region(C);
2419         }
2420
2421         v3d = sa->spacedata.first;
2422         rv3d = ar->regiondata;
2423
2424         mx = RNA_struct_property_is_set(op->ptr, "mx") ? RNA_int_get(op->ptr, "mx") : ar->winx / 2;
2425         my = RNA_struct_property_is_set(op->ptr, "my") ? RNA_int_get(op->ptr, "my") : ar->winy / 2;
2426
2427         use_cam_zoom = (rv3d->persp == RV3D_CAMOB) && !(rv3d->is_persp && ED_view3d_camera_lock_check(v3d, rv3d));
2428
2429         ED_view3d_dist_range_get(v3d, dist_range);
2430
2431         if (delta < 0) {
2432                 const float step = 1.2f;
2433                 /* this min and max is also in viewmove() */
2434                 if (use_cam_zoom) {
2435                         view_zoom_mouseloc_camera(scene, v3d, ar, step, mx, my);
2436                 }
2437                 else {
2438                         if (rv3d->dist < dist_range[1]) {
2439                                 view_zoom_mouseloc_3d(ar, step, mx, my);
2440                         }
2441                 }
2442         }
2443         else {
2444                 const float step = 1.0f / 1.2f;
2445                 if (use_cam_zoom) {
2446                         view_zoom_mouseloc_camera(scene, v3d, ar, step, mx, my);
2447                 }
2448                 else {
2449                         if (rv3d->dist > dist_range[0]) {
2450                                 view_zoom_mouseloc_3d(ar, step, mx, my);
2451                         }
2452                 }
2453         }
2454
2455         if (rv3d->viewlock & RV3D_BOXVIEW)
2456                 view3d_boxview_sync(sa, ar);
2457
2458         ED_view3d_depth_tag_update(rv3d);
2459
2460         ED_view3d_camera_lock_sync(v3d, rv3d);
2461         ED_view3d_camera_lock_autokey(v3d, rv3d, C, false, true);
2462
2463         ED_region_tag_redraw(ar);
2464
2465         viewops_data_free(C, op);
2466
2467         return OPERATOR_FINISHED;
2468 }
2469
2470 /* this is an exact copy of viewzoom_modal_keymap */
2471 /* called in transform_ops.c, on each regeneration of keymaps  */
2472 void viewdolly_modal_keymap(wmKeyConfig *keyconf)
2473 {
2474         static EnumPropertyItem modal_items[] = {
2475                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
2476
2477                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
2478                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
2479
2480                 {0, NULL, 0, NULL, NULL}
2481         };
2482
2483         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Dolly Modal");
2484
2485         /* this function is called for each spacetype, only needs to add map once */
2486         if (keymap && keymap->modal_items) return;
2487
2488         keymap = WM_modalkeymap_add(keyconf, "View3D Dolly Modal", modal_items);
2489
2490         /* items for modal map */
2491         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2492         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2493
2494         /* disabled mode switching for now, can re-implement better, later on */
2495 #if 0
2496         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2497         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2498         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
2499 #endif
2500         
2501         /* assign map to operators */
2502         WM_modalkeymap_assign(keymap, "VIEW3D_OT_dolly");
2503 }
2504
2505 /* viewdolly_invoke() copied this function, changes here may apply there */
2506 static int viewzoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2507 {
2508         ViewOpsData *vod;
2509
2510         /* makes op->customdata */
2511         viewops_data_alloc(C, op);
2512         viewops_data_create(C, op, event);
2513         vod = op->customdata;
2514
2515         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
2516
2517         /* if one or the other zoom position aren't set, set from event */
2518         if (!RNA_struct_property_is_set(op->ptr, "mx") || !RNA_struct_property_is_set(op->ptr, "my")) {
2519                 RNA_int_set(op->ptr, "mx", event->x);
2520                 RNA_int_set(op->ptr, "my", event->y);
2521         }
2522
2523         if (RNA_struct_property_is_set(op->ptr, "delta")) {
2524                 viewzoom_exec(C, op);
2525         }
2526         else {
2527                 if (event->type == MOUSEZOOM || event->type == MOUSEPAN) {
2528
2529                         if (U.uiflag & USER_ZOOM_HORIZ) {
2530                                 vod->origx = vod->oldx = event->x;
2531                                 viewzoom_apply(vod, &event->prevx, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) != 0);
2532                         }
2533                         else {
2534                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
2535                                 vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
2536                                 viewzoom_apply(vod, &event->prevx, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) != 0);
2537                         }
2538                         ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2539
2540                         ED_view3d_depth_tag_update(vod->rv3d);
2541
2542                         viewops_data_free(C, op);
2543                         return OPERATOR_FINISHED;
2544                 }
2545                 else {
2546                         if (U.viewzoom == USER_ZOOM_CONT) {
2547                                 /* needs a timer to continue redrawing */
2548                                 vod->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
2549                                 vod->timer_lastdraw = PIL_check_seconds_timer();
2550                         }
2551
2552                         /* add temp handler */
2553                         WM_event_add_modal_handler(C, op);
2554
2555                         return OPERATOR_RUNNING_MODAL;
2556                 }
2557         }
2558         return OPERATOR_FINISHED;
2559 }
2560
2561 static void viewzoom_cancel(bContext *C, wmOperator *op)
2562 {
2563         viewops_data_free(C, op);
2564 }
2565
2566 void VIEW3D_OT_zoom(wmOperatorType *ot)
2567 {
2568         PropertyRNA *prop;
2569
2570         /* identifiers */
2571         ot->name = "Zoom View";
2572         ot->description = "Zoom in/out in the view";
2573         ot->idname = "VIEW3D_OT_zoom";
2574
2575         /* api callbacks */
2576         ot->invoke = viewzoom_invoke;
2577         ot->exec = viewzoom_exec;
2578         ot->modal = viewzoom_modal;
2579         ot->poll = ED_operator_region_view3d_active;
2580         ot->cancel = viewzoom_cancel;
2581
2582         /* flags */
2583         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2584
2585         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2586         prop = RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
2587         RNA_def_property_flag(prop, PROP_HIDDEN);
2588         prop = RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
2589         RNA_def_property_flag(prop, PROP_HIDDEN);
2590 }
2591
2592
2593 /* ************************ viewdolly ******************************** */
2594 static void view_dolly_mouseloc(ARegion *ar, float orig_ofs[3], float dvec[3], float dfac)
2595 {
2596         RegionView3D *rv3d = ar->regiondata;
2597         madd_v3_v3v3fl(rv3d->ofs, orig_ofs, dvec, -(1.0f - dfac));
2598 }
2599
2600 static void viewdolly_apply(ViewOpsData *vod, int x, int y, const short zoom_invert)
2601 {
2602         float zfac = 1.0;
2603
2604         {
2605                 float len1, len2;
2606
2607                 if (U.uiflag & USER_ZOOM_HORIZ) {
2608                         len1 = (vod->ar->winrct.xmax - x) + 5;
2609                         len2 = (vod->ar->winrct.xmax - vod->origx) + 5;
2610                 }
2611                 else {
2612                         len1 = (vod->ar->winrct.ymax - y) + 5;
2613                         len2 = (vod->ar->winrct.ymax - vod->origy) + 5;
2614                 }
2615                 if (zoom_invert)
2616                         SWAP(float, len1, len2);
2617
2618                 zfac =  1.0f + ((len1 - len2) * 0.01f * vod->rv3d->dist);
2619         }
2620
2621         if (zfac != 1.0f)
2622                 view_dolly_mouseloc(vod->ar, vod->ofs, vod->mousevec, zfac);
2623
2624         if (vod->rv3d->viewlock & RV3D_BOXVIEW)
2625                 view3d_boxview_sync(vod->sa, vod->ar);
2626
2627         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
2628
2629         ED_region_tag_redraw(vod->ar);
2630 }
2631
2632
2633 static int viewdolly_modal(bContext *C, wmOperator *op, const wmEvent *event)
2634 {
2635         ViewOpsData *vod = op->customdata;
2636         short event_code = VIEW_PASS;
2637         bool use_autokey = false;
2638         int ret = OPERATOR_RUNNING_MODAL;
2639
2640         /* execute the events */
2641         if (event->type == MOUSEMOVE) {
2642                 event_code = VIEW_APPLY;
2643         }
2644         else if (event->type == EVT_MODAL_MAP) {
2645                 switch (event->val) {
2646                         case VIEW_MODAL_CONFIRM:
2647                                 event_code = VIEW_CONFIRM;
2648                                 break;
2649                         case VIEWROT_MODAL_SWITCH_MOVE:
2650                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
2651                                 event_code = VIEW_CONFIRM;
2652                                 break;
2653                         case VIEWROT_MODAL_SWITCH_ROTATE:
2654                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
2655                                 event_code = VIEW_CONFIRM;
2656                                 break;
2657                 }
2658         }
2659         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
2660                 event_code = VIEW_CONFIRM;
2661         }
2662
2663         if (event_code == VIEW_APPLY) {
2664                 viewdolly_apply(vod, event->x, event->y, (U.uiflag & USER_ZOOM_INVERT) != 0);
2665                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2666                         use_autokey = true;
2667                 }
2668         }
2669         else if (event_code == VIEW_CONFIRM) {
2670                 ED_view3d_depth_tag_update(vod->rv3d);
2671                 use_autokey = true;
2672                 ret = OPERATOR_FINISHED;
2673         }
2674
2675         if (use_autokey) {
2676                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2677         }
2678
2679         if (ret & OPERATOR_FINISHED) {
2680                 viewops_data_free(C, op);
2681         }
2682
2683         return ret;
2684 }
2685
2686 static int viewdolly_exec(bContext *C, wmOperator *op)
2687 {
2688         View3D *v3d;
2689         RegionView3D *rv3d;
2690         ScrArea *sa;
2691         ARegion *ar;
2692         float mousevec[3];
2693
2694         const int delta = RNA_int_get(op->ptr, "delta");
2695
2696         if (op->customdata) {
2697                 ViewOpsData *vod = op->customdata;
2698
2699                 sa = vod->sa;
2700                 ar = vod->ar;
2701                 copy_v3_v3(mousevec, vod->mousevec);
2702         }
2703         else {
2704                 sa = CTX_wm_area(C);
2705                 ar = CTX_wm_region(C);
2706                 negate_v3_v3(mousevec, ((RegionView3D *)ar->regiondata)->viewinv[2]);
2707                 normalize_v3(mousevec);
2708         }
2709
2710         v3d = sa->spacedata.first;
2711         rv3d = ar->regiondata;
2712
2713         /* overwrite the mouse vector with the view direction (zoom into the center) */
2714         if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
2715                 normalize_v3_v3(mousevec, rv3d->viewinv[2]);
2716         }
2717
2718         if (delta < 0) {
2719                 view_dolly_mouseloc(ar, rv3d->ofs, mousevec, 0.2f);
2720         }
2721         else {
2722                 view_dolly_mouseloc(ar, rv3d->ofs, mousevec, 1.8f);
2723         }
2724
2725         if (rv3d->viewlock & RV3D_BOXVIEW)
2726                 view3d_boxview_sync(sa, ar);
2727
2728         ED_view3d_depth_tag_update(rv3d);
2729
2730         ED_view3d_camera_lock_sync(v3d, rv3d);
2731
2732         ED_region_tag_redraw(ar);
2733
2734         viewops_data_free(C, op);
2735
2736         return OPERATOR_FINISHED;
2737 }
2738
2739 /* copied from viewzoom_invoke(), changes here may apply there */
2740 static int viewdolly_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2741 {
2742         ViewOpsData *vod;
2743
2744         if (view3d_operator_offset_lock_check(C, op))
2745                 return OPERATOR_CANCELLED;
2746
2747         /* makes op->customdata */
2748         viewops_data_alloc(C, op);
2749         vod = op->customdata;
2750
2751         /* poll should check but in some cases fails, see poll func for details */
2752         if (vod->rv3d->viewlock & RV3D_LOCKED) {
2753                 viewops_data_free(C, op);
2754                 return OPERATOR_PASS_THROUGH;
2755         }
2756
2757         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
2758
2759         /* needs to run before 'viewops_data_create' so the backup 'rv3d->ofs' is correct */
2760         /* switch from camera view when: */
2761         if (vod->rv3d->persp != RV3D_PERSP) {
2762                 if (vod->rv3d->persp == RV3D_CAMOB) {
2763                         /* ignore rv3d->lpersp because dolly only makes sense in perspective mode */
2764                         view3d_persp_switch_from_camera(vod->v3d, vod->rv3d, RV3D_PERSP);
2765                 }
2766                 else {
2767                         vod->rv3d->persp = RV3D_PERSP;
2768                 }
2769                 ED_region_tag_redraw(vod->ar);
2770         }
2771
2772         viewops_data_create(C, op, event);
2773
2774
2775         /* if one or the other zoom position aren't set, set from event */
2776         if (!RNA_struct_property_is_set(op->ptr, "mx") || !RNA_struct_property_is_set(op->ptr, "my")) {
2777                 RNA_int_set(op->ptr, "mx", event->x);
2778                 RNA_int_set(op->ptr, "my", event->y);
2779         }
2780
2781         if (RNA_struct_property_is_set(op->ptr, "delta")) {
2782                 viewdolly_exec(C, op);
2783         }
2784         else {
2785                 /* overwrite the mouse vector with the view direction (zoom into the center) */
2786                 if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
2787                         negate_v3_v3(vod->mousevec, vod->rv3d->viewinv[2]);
2788                         normalize_v3(vod->mousevec);
2789                 }
2790
2791                 if (event->type == MOUSEZOOM) {
2792                         /* Bypass Zoom invert flag for track pads (pass false always) */
2793
2794                         if (U.uiflag & USER_ZOOM_HORIZ) {
2795                                 vod->origx = vod->oldx = event->x;
2796                                 viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
2797                         }
2798                         else {
2799
2800                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
2801                                 vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
2802                                 viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
2803                         }
2804                         ED_view3d_depth_tag_update(vod->rv3d);
2805
2806                         viewops_data_free(C, op);
2807                         return OPERATOR_FINISHED;
2808                 }
2809                 else {
2810                         /* add temp handler */
2811                         WM_event_add_modal_handler(C, op);
2812
2813                         return OPERATOR_RUNNING_MODAL;
2814                 }
2815         }
2816         return OPERATOR_FINISHED;
2817 }
2818
2819 static void viewdolly_cancel(bContext *C, wmOperator *op)
2820 {
2821         viewops_data_free(C, op);
2822 }
2823
2824 void VIEW3D_OT_dolly(wmOperatorType *ot)
2825 {
2826         /* identifiers */
2827         ot->name = "Dolly View";
2828         ot->description = "Dolly in/out in the view";
2829         ot->idname = "VIEW3D_OT_dolly";
2830
2831         /* api callbacks */
2832         ot->invoke = viewdolly_invoke;
2833         ot->exec = viewdolly_exec;
2834         ot->modal = viewdolly_modal;
2835         ot->poll = ED_operator_region_view3d_active;
2836         ot->cancel = viewdolly_cancel;
2837
2838         /* flags */
2839         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2840
2841         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2842         RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
2843         RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
2844 }
2845
2846 static void view3d_from_minmax(bContext *C, View3D *v3d, ARegion *ar,
2847                                const float min[3], const float max[3],
2848                                bool ok_dist, const int smooth_viewtx)
2849 {
2850         RegionView3D *rv3d = ar->regiondata;
2851         float afm[3];
2852         float size;
2853
2854         ED_view3d_smooth_view_force_finish(C, v3d, ar);
2855
2856         /* SMOOTHVIEW */
2857         float new_ofs[3];
2858         float new_dist;
2859
2860         sub_v3_v3v3(afm, max, min);
2861         size = max_fff(afm[0], afm[1], afm[2]);
2862
2863         if (ok_dist) {
2864                 char persp;
2865
2866                 if (rv3d->is_persp) {
2867                         if (rv3d->persp == RV3D_CAMOB && ED_view3d_camera_lock_check(v3d, rv3d)) {
2868                                 persp = RV3D_CAMOB;
2869                         }
2870                         else {
2871                                 persp = RV3D_PERSP;
2872                         }
2873                 }
2874                 else { /* ortho */
2875                         if (size < 0.0001f) {
2876                                 /* bounding box was a single point so do not zoom */
2877                                 ok_dist = false;
2878                         }
2879                         else {
2880                                 /* adjust zoom so it looks nicer */
2881                                 persp = RV3D_ORTHO;
2882                         }
2883                 }
2884
2885                 if (ok_dist) {
2886                         new_dist = ED_view3d_radius_to_dist(v3d, ar, persp, true, (size / 2) * VIEW3D_MARGIN);
2887                         if (rv3d->is_persp) {
2888                                 /* don't zoom closer than the near clipping plane */
2889                                 new_dist = max_ff(new_dist, v3d->near * 1.5f);
2890                         }
2891                 }
2892         }
2893
2894         mid_v3_v3v3(new_ofs, min, max);
2895         negate_v3(new_ofs);
2896
2897         if (rv3d->persp == RV3D_CAMOB && !ED_view3d_camera_lock_check(v3d, rv3d)) {
2898                 rv3d->persp = RV3D_PERSP;
2899                 ED_view3d_smooth_view(
2900                         C, v3d, ar, smooth_viewtx,
2901                         &(const V3D_SmoothParams) {
2902                             .camera_old = v3d->camera, .ofs = new_ofs,
2903                             .dist = ok_dist ? &new_dist : NULL});
2904         }
2905         else {
2906                 ED_view3d_smooth_view(
2907                         C, v3d, ar, smooth_viewtx,
2908                         &(const V3D_SmoothParams) {.ofs = new_ofs, .dist = ok_dist ? &new_dist : NULL});
2909         }
2910
2911         /* smooth view does viewlock RV3D_BOXVIEW copy */
2912 }
2913
2914 /* same as view3d_from_minmax but for all regions (except cameras) */
2915 static void view3d_from_minmax_multi(bContext *C, View3D *v3d,
2916                                      const float min[3], const float max[3],
2917                                      const bool ok_dist, const int smooth_viewtx)
2918 {
2919         ScrArea *sa = CTX_wm_area(C);
2920         ARegion *ar;
2921         for (ar = sa->regionbase.first; ar; ar = ar->next) {
2922                 if (ar->regiontype == RGN_TYPE_WINDOW) {
2923                         RegionView3D *rv3d = ar->regiondata;
2924                         /* when using all regions, don't jump out of camera view,
2925                          * but _do_ allow locked cameras to be moved */
2926                         if ((rv3d->persp != RV3D_CAMOB) || ED_view3d_camera_lock_check(v3d, rv3d)) {
2927                                 view3d_from_minmax(C, v3d, ar, min, max, ok_dist, smooth_viewtx);
2928                         }
2929                 }
2930         }
2931 }
2932
2933 static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in 2.4x */
2934 {
2935         ARegion *ar = CTX_wm_region(C);
2936         View3D *v3d = CTX_wm_view3d(C);
2937         Scene *scene = CTX_data_scene(C);
2938         Base *base;
2939         float *curs;
2940         const bool use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
2941         const bool skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
2942                                   /* any one of the regions may be locked */
2943                                   (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
2944         const bool center = RNA_boolean_get(op->ptr, "center");
2945         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
2946
2947         float min[3], max[3];
2948         bool changed = false;
2949
2950         if (center) {
2951                 /* in 2.4x this also move the cursor to (0, 0, 0) (with shift+c). */
2952                 curs = ED_view3d_cursor3d_get(scene, v3d);
2953                 zero_v3(min);
2954                 zero_v3(max);
2955                 zero_v3(curs);
2956         }
2957         else {
2958                 INIT_MINMAX(min, max);
2959         }
2960
2961         for (base = scene->base.first; base; base = base->next) {
2962                 if (BASE_VISIBLE(v3d, base)) {
2963                         changed = true;
2964
2965                         if (skip_camera && base->object == v3d->camera) {
2966                                 continue;
2967                         }
2968
2969                         BKE_object_minmax(base->object, min, max, false);
2970                 }
2971         }
2972         if (!changed) {
2973                 ED_region_tag_redraw(ar);
2974                 /* TODO - should this be cancel?
2975                  * I think no, because we always move the cursor, with or without
2976                  * object, but in this case there is no change in the scene,
2977                  * only the cursor so I choice a ED_region_tag like
2978                  * view3d_smooth_view do for the center_cursor.
2979                  * See bug #22640
2980                  */
2981                 return OPERATOR_FINISHED;
2982         }
2983
2984         if (use_all_regions) {
2985                 view3d_from_minmax_multi(C, v3d, min, max, true, smooth_viewtx);
2986         }
2987         else {
2988                 view3d_from_minmax(C, v3d, ar, min, max, true, smooth_viewtx);
2989         }
2990
2991         return OPERATOR_FINISHED;
2992 }
2993
2994
2995 void VIEW3D_OT_view_all(wmOperatorType *ot)
2996 {
2997         PropertyRNA *prop;
2998
2999         /* identifiers */
3000         ot->name = "View All";
3001         ot->description = "View all objects in scene";
3002         ot->idname = "VIEW3D_OT_view_all";
3003
3004         /* api callbacks */
3005         ot->exec = view3d_all_exec;
3006         ot->poll = ED_operator_region_view3d_active;
3007
3008         /* flags */
3009         ot->flag = 0;
3010
3011         prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
3012         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3013         RNA_def_boolean(ot->srna, "center", 0, "Center", "");
3014 }
3015
3016 /* like a localview without local!, was centerview() in 2.4x */
3017 static int viewselected_exec(bContext *C, wmOperator *op)
3018 {
3019         ARegion *ar = CTX_wm_region(C);
3020         View3D *v3d = CTX_wm_view3d(C);
3021         Scene *scene = CTX_data_scene(C);
3022         Object *ob = OBACT;
3023         Object *obedit = CTX_data_edit_object(C);
3024         float min[3], max[3];
3025         bool ok = false, ok_dist = true;
3026         const bool use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
3027         const bool skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
3028                                   /* any one of the regions may be locked */
3029                                   (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
3030         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
3031
3032         INIT_MINMAX(min, max);
3033
3034         if (ob && (ob->mode & OB_MODE_WEIGHT_PAINT)) {
3035                 /* hard-coded exception, we look for the one selected armature */
3036                 /* this is weak code this way, we should make a generic active/selection callback interface once... */
3037                 Base *base;
3038                 for (base = scene->base.first; base; base = base->next) {
3039                         if (TESTBASELIB(v3d, base)) {
3040                                 if (base->object->type == OB_ARMATURE)
3041                                         if (base->object->mode & OB_MODE_POSE)
3042                                                 break;
3043                         }
3044                 }
3045                 if (base)
3046                         ob = base->object;
3047         }
3048
3049
3050         if (obedit) {
3051                 ok = ED_view3d_minmax_verts(obedit, min, max);    /* only selected */
3052         }
3053         else if (ob && (ob->mode & OB_MODE_POSE)) {
3054                 ok = BKE_pose_minmax(ob, min, max, true, true);
3055         }
3056         else if (BKE_paint_select_face_test(ob)) {
3057                 ok = paintface_minmax(ob, min, max);
3058         }
3059         else if (ob && (ob->mode & OB_MODE_PARTICLE_EDIT)) {
3060                 ok = PE_minmax(scene, min, max);
3061         }
3062         else if (ob && (ob->mode & (OB_MODE_SCULPT | OB_MODE_TEXTURE_PAINT))) {
3063                 BKE_paint_stroke_get_average(scene, ob, min);
3064                 copy_v3_v3(max, min);
3065                 ok = true;
3066                 ok_dist = 0; /* don't zoom */
3067         }
3068         else {
3069                 Base *base;
3070                 for (base = FIRSTBASE; base; base = base->next) {
3071                         if (TESTBASE(v3d, base)) {
3072
3073                                 if (skip_camera && base->object == v3d->camera) {
3074                                         continue;
3075                                 }
3076
3077                                 /* account for duplis */
3078                                 if (BKE_object_minmax_dupli(scene, base->object, min, max, false) == 0)
3079                                         BKE_object_minmax(base->object, min, max, false);  /* use if duplis not found */
3080
3081                                 ok = 1;
3082                         }
3083                 }
3084         }
3085
3086         if (ok == 0) {
3087                 return OPERATOR_FINISHED;
3088         }
3089
3090         if (use_all_regions) {
3091                 view3d_from_minmax_multi(C, v3d, min, max, ok_dist, smooth_viewtx);
3092         }
3093         else {
3094                 view3d_from_minmax(C, v3d, ar, min, max, ok_dist, smooth_viewtx);
3095         }
3096
3097         return OPERATOR_FINISHED;
3098 }
3099
3100 void VIEW3D_OT_view_selected(wmOperatorType *ot)
3101 {
3102         PropertyRNA *prop;
3103
3104         /* identifiers */
3105         ot->name = "View Selected";
3106         ot->description = "Move the view to the selection center";
3107         ot->idname = "VIEW3D_OT_view_selected";
3108
3109         /* api callbacks */
3110         ot->exec = viewselected_exec;
3111         ot->poll = ED_operator_region_view3d_active;
3112
3113         /* flags */
3114         ot->flag = 0;
3115
3116         /* rna later */
3117         prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
3118         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3119 }
3120
3121 static int view_lock_clear_exec(bContext *C, wmOperator *UNUSED(op))
3122 {
3123         View3D *v3d = CTX_wm_view3d(C);
3124
3125         if (v3d) {
3126                 ED_view3D_lock_clear(v3d);
3127
3128                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
3129
3130                 return OPERATOR_FINISHED;
3131         }
3132         else {
3133                 return OPERATOR_CANCELLED;
3134         }
3135 }
3136
3137 void VIEW3D_OT_view_lock_clear(wmOperatorType *ot)
3138 {
3139
3140         /* identifiers */
3141         ot->name = "View Lock Clear";
3142         ot->description = "Clear all view locking";
3143         ot->idname = "VIEW3D_OT_view_lock_clear";
3144
3145         /* api callbacks */
3146         ot->exec = view_lock_clear_exec;
3147         ot->poll = ED_operator_region_view3d_active;
3148
3149         /* flags */
3150         ot->flag = 0;
3151 }
3152
3153 static int view_lock_to_active_exec(bContext *C, wmOperator *UNUSED(op))
3154 {
3155         View3D *v3d = CTX_wm_view3d(C);
3156         Object *obact = CTX_data_active_object(C);
3157
3158         if (v3d) {
3159
3160                 ED_view3D_lock_clear(v3d);
3161
3162                 v3d->ob_centre = obact; /* can be NULL */
3163
3164                 if (obact && obact->type == OB_ARMATURE) {
3165                         if (obact->mode & OB_MODE_POSE) {
3166                                 bPoseChannel *pcham_act = BKE_pose_channel_active(obact);
3167                                 if (pcham_act) {
3168                                         BLI_strncpy(v3d->ob_centre_bone, pcham_act->name, sizeof(v3d->ob_centre_bone));
3169                                 }
3170                         }
3171                         else {
3172                                 EditBone *ebone_act = ((bArmature *)obact->data)->act_edbone;
3173                                 if (ebone_act) {
3174                                         BLI_strncpy(v3d->ob_centre_bone, ebone_act->name, sizeof(v3d->ob_centre_bone));
3175                                 }
3176                         }
3177                 }
3178
3179                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
3180
3181                 return OPERATOR_FINISHED;
3182         }
3183         else {
3184                 return OPERATOR_CANCELLED;
3185         }
3186 }
3187
3188 void VIEW3D_OT_view_lock_to_active(wmOperatorType *ot)
3189 {
3190
3191         /* identifiers */
3192         ot->name = "View Lock to Active";
3193         ot->description = "Lock the view to the active object/bone";
3194         ot->idname = "VIEW3D_OT_view_lock_to_active";
3195
3196         /* api callbacks */
3197         ot->exec = view_lock_to_active_exec;
3198         ot->poll = ED_operator_region_view3d_active;
3199
3200         /* flags */
3201         ot->flag = 0;
3202 }
3203