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