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