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