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