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