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