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