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