Made wmNDOFMotionData use a vector rather then xyz members, makes it nicer to use...
[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         return ndof->dt * normalize_v3_v3(axis, ndof->rvec);
936 }
937
938 void ndof_to_quat(struct wmNDOFMotionData* ndof, float q[4])
939 {
940         float axis[3];
941         float angle;
942
943         angle= ndof_to_angle_axis(ndof, axis);
944         axis_angle_to_quat(q, axis, angle);
945 }
946
947 static int ndof_orbit_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
948 // -- "orbit" navigation (trackball/turntable)
949 // -- zooming
950 // -- panning in rotationally-locked views
951 {
952         RegionView3D* rv3d = CTX_wm_region_view3d(C);
953         wmNDOFMotionData* ndof = (wmNDOFMotionData*) event->customdata;
954
955         rv3d->rot_angle = 0.f; // off by default, until changed later this function
956
957         if (ndof->progress != P_FINISHING) {
958                 const float dt = ndof->dt;
959         
960                 // tune these until everything feels right
961                 const float rot_sensitivity = 1.f;
962                 const float zoom_sensitivity = 1.f;
963                 const float pan_sensitivity = 1.f;
964         
965                 // rather have bool, but...
966                 int has_rotation = rv3d->viewlock != RV3D_LOCKED && !is_zero_v3(ndof->rvec);
967         
968                 float view_inv[4];
969                 invert_qt_qt(view_inv, rv3d->viewquat);
970         
971                 //#define DEBUG_NDOF_MOTION
972                 #ifdef DEBUG_NDOF_MOTION
973                 printf("ndof: T=(%.2f,%.2f,%.2f) R=(%.2f,%.2f,%.2f) dt=%.3f delivered to 3D view\n",
974                         ndof->tx, ndof->ty, ndof->tz, ndof->rx, ndof->ry, ndof->rz, ndof->dt);
975                 #endif
976         
977                 if (ndof->tvec[2]) {
978                         // Zoom!
979                         // velocity should be proportional to the linear velocity attained by rotational motion of same strength
980                         // [got that?]
981                         // proportional to arclength = radius * angle
982         
983                         float zoom_distance = zoom_sensitivity * rv3d->dist * dt * ndof->tvec[2];
984                         rv3d->dist += zoom_distance;
985                 }
986         
987                 if (rv3d->viewlock == RV3D_LOCKED) {
988                         /* rotation not allowed -- explore panning options instead */
989                         float pan_vec[3] = {ndof->tvec[0], ndof->tvec[1], 0.0f};
990                         mul_v3_fl(pan_vec, pan_sensitivity * rv3d->dist * dt);
991         
992                         /* transform motion from view to world coordinates */
993                         invert_qt_qt(view_inv, rv3d->viewquat);
994                         mul_qt_v3(view_inv, pan_vec);
995         
996                         /* move center of view opposite of hand motion (this is camera mode, not object mode) */
997                         sub_v3_v3(rv3d->ofs, pan_vec);
998                 }
999         
1000                 if (has_rotation) {
1001         
1002                         const int invert = U.ndof_flag & NDOF_ORBIT_INVERT_AXES;
1003         
1004                         rv3d->view = RV3D_VIEW_USER;
1005         
1006                         if (U.flag & USER_TRACKBALL) {
1007                                 float rot[4];
1008         #if 0   // -------------------------- Mike's nifty original version
1009                                 float view_inv_conj[4];
1010         
1011                                 ndof_to_quat(ndof, rot);
1012                                 // mul_qt_fl(rot, rot_sensitivity);
1013                                 // ^^ no apparent effect
1014         
1015                                 if (invert)
1016                                         invert_qt(rot);
1017         
1018                                 copy_qt_qt(view_inv_conj, view_inv);
1019                                 conjugate_qt(view_inv_conj);
1020         
1021                                 // transform rotation from view to world coordinates
1022                                 mul_qt_qtqt(rot, view_inv, rot);
1023                                 mul_qt_qtqt(rot, rot, view_inv_conj);
1024         #else   // ---------------------------------------- Mike's revised version
1025                                 float axis[3];
1026                                 float angle = rot_sensitivity * ndof_to_angle_axis(ndof, axis);
1027         
1028                                 if (invert)
1029                                         angle = -angle;
1030         
1031                                 // transform rotation axis from view to world coordinates
1032                                 mul_qt_v3(view_inv, axis);
1033         
1034                                 // update the onscreen doo-dad
1035                                 rv3d->rot_angle = angle;
1036                                 copy_v3_v3(rv3d->rot_axis, axis);
1037         
1038                                 axis_angle_to_quat(rot, axis, angle);
1039         #endif  // --------------------------------------------
1040                                 // apply rotation
1041                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rot);
1042                         } else {
1043                                 /* turntable view code by John Aughey, adapted for 3D mouse by [mce] */
1044                                 float angle, rot[4];
1045                                 float xvec[3] = {1,0,0};
1046         
1047                                 /* Determine the direction of the x vector (for rotating up and down) */
1048                                 mul_qt_v3(view_inv, xvec);
1049         
1050                                 /* Perform the up/down rotation */
1051                                 angle = rot_sensitivity * dt * ndof->rvec[0];
1052                                 if (invert)
1053                                         angle = -angle;
1054                                 rot[0] = cos(angle);
1055                                 mul_v3_v3fl(rot+1, xvec, sin(angle));
1056                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rot);
1057         
1058                                 /* Perform the orbital rotation */
1059                                 angle = rot_sensitivity * dt * ndof->rvec[1];
1060                                 if (invert)
1061                                         angle = -angle;
1062         
1063                                 // update the onscreen doo-dad
1064                                 rv3d->rot_angle = angle;
1065                                 rv3d->rot_axis[0] = 0;
1066                                 rv3d->rot_axis[1] = 0;
1067                                 rv3d->rot_axis[2] = 1;
1068         
1069                                 rot[0] = cos(angle);
1070                                 rot[1] = rot[2] = 0.0;
1071                                 rot[3] = sin(angle);
1072                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rot);
1073                         }
1074                 }
1075         }
1076
1077         ED_region_tag_redraw(CTX_wm_region(C));
1078
1079         return OPERATOR_FINISHED;
1080 }
1081
1082 void VIEW3D_OT_ndof_orbit(struct wmOperatorType *ot)
1083 {
1084         /* identifiers */
1085         ot->name = "NDOF Orbit View";
1086         ot->description = "Explore every angle of an object using the 3D mouse.";
1087         ot->idname = "VIEW3D_OT_ndof_orbit";
1088
1089         /* api callbacks */
1090         ot->invoke = ndof_orbit_invoke;
1091         ot->poll = ED_operator_view3d_active;
1092
1093         /* flags */
1094         ot->flag = 0;
1095 }
1096
1097 static int ndof_pan_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1098 // -- "pan" navigation
1099 // -- zoom or dolly?
1100 {
1101         RegionView3D* rv3d = CTX_wm_region_view3d(C);
1102         wmNDOFMotionData* ndof = (wmNDOFMotionData*) event->customdata;
1103
1104         rv3d->rot_angle = 0.f; // we're panning here! so erase any leftover rotation from other operators
1105
1106         if (ndof->progress != P_FINISHING) {
1107                 const float dt = ndof->dt;
1108                 float view_inv[4];
1109 #if 0 // ------------------------------------------- zoom with Z
1110                 // tune these until everything feels right
1111                 const float zoom_sensitivity = 1.f;
1112                 const float pan_sensitivity = 1.f;
1113
1114                 float pan_vec[3] = {
1115                         ndof->tx, ndof->ty, 0
1116                         };
1117
1118                 // "zoom in" or "translate"? depends on zoom mode in user settings?
1119                 if (ndof->tz) {
1120                         float zoom_distance = zoom_sensitivity * rv3d->dist * dt * ndof->tz;
1121                         rv3d->dist += zoom_distance;
1122                 }
1123         
1124                 mul_v3_fl(pan_vec, pan_sensitivity * rv3d->dist * dt);
1125 #else // ------------------------------------------------------- dolly with Z
1126                 float speed = 10.f; // blender units per second
1127                 // ^^ this is ok for default cube scene, but should scale with.. something
1128
1129                 // tune these until everything feels right
1130                 const float forward_sensitivity = 1.f;
1131                 const float vertical_sensitivity = 0.4f;
1132                 const float lateral_sensitivity = 0.6f;
1133
1134                 float pan_vec[3] = {lateral_sensitivity * ndof->tvec[0],
1135                                     vertical_sensitivity * ndof->tvec[1],
1136                                     forward_sensitivity * ndof->tvec[2]
1137                                    };
1138
1139                 mul_v3_fl(pan_vec, speed * dt);
1140 #endif
1141                 /* transform motion from view to world coordinates */
1142                 invert_qt_qt(view_inv, rv3d->viewquat);
1143                 mul_qt_v3(view_inv, pan_vec);
1144
1145                 /* move center of view opposite of hand motion (this is camera mode, not object mode) */
1146                 sub_v3_v3(rv3d->ofs, pan_vec);
1147         }
1148
1149         ED_region_tag_redraw(CTX_wm_region(C));
1150
1151         return OPERATOR_FINISHED;
1152 }
1153
1154 void VIEW3D_OT_ndof_pan(struct wmOperatorType *ot)
1155 {
1156         /* identifiers */
1157         ot->name = "NDOF Pan View";
1158         ot->description = "Position your viewpoint with the 3D mouse.";
1159         ot->idname = "VIEW3D_OT_ndof_pan";
1160
1161         /* api callbacks */
1162         ot->invoke = ndof_pan_invoke;
1163         ot->poll = ED_operator_view3d_active;
1164
1165         /* flags */
1166         ot->flag = 0;
1167 }
1168
1169 /* ************************ viewmove ******************************** */
1170
1171
1172 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
1173
1174 /* called in transform_ops.c, on each regeneration of keymaps  */
1175 void viewmove_modal_keymap(wmKeyConfig *keyconf)
1176 {
1177         static EnumPropertyItem modal_items[] = {
1178         {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
1179                 
1180         {VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
1181         {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
1182
1183         {0, NULL, 0, NULL, NULL}};
1184
1185         wmKeyMap *keymap= WM_modalkeymap_get(keyconf, "View3D Move Modal");
1186
1187         /* this function is called for each spacetype, only needs to add map once */
1188         if(keymap) return;
1189
1190         keymap= WM_modalkeymap_add(keyconf, "View3D Move Modal", modal_items);
1191
1192         /* items for modal map */
1193         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1194         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1195
1196         /* disabled mode switching for now, can re-implement better, later on
1197         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1198         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1199         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1200         */
1201         
1202         /* assign map to operators */
1203         WM_modalkeymap_assign(keymap, "VIEW3D_OT_move");
1204 }
1205
1206
1207 static void viewmove_apply(ViewOpsData *vod, int x, int y)
1208 {
1209         if((vod->rv3d->persp==RV3D_CAMOB) && !ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) {
1210                 const float zoomfac= BKE_screen_view3d_zoom_to_fac((float)vod->rv3d->camzoom) * 2.0f;
1211                 vod->rv3d->camdx += (vod->oldx - x)/(vod->ar->winx * zoomfac);
1212                 vod->rv3d->camdy += (vod->oldy - y)/(vod->ar->winy * zoomfac);
1213                 CLAMP(vod->rv3d->camdx, -1.0f, 1.0f);
1214                 CLAMP(vod->rv3d->camdy, -1.0f, 1.0f);
1215         }
1216         else {
1217                 float dvec[3];
1218                 float mval_f[2];
1219
1220                 mval_f[0]= x - vod->oldx;
1221                 mval_f[1]= y - vod->oldy;
1222                 ED_view3d_win_to_delta(vod->ar, mval_f, dvec);
1223
1224                 add_v3_v3(vod->rv3d->ofs, dvec);
1225
1226                 if(vod->rv3d->viewlock & RV3D_BOXVIEW)
1227                         view3d_boxview_sync(vod->sa, vod->ar);
1228         }
1229
1230         vod->oldx= x;
1231         vod->oldy= y;
1232
1233         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
1234
1235         ED_region_tag_redraw(vod->ar);
1236 }
1237
1238
1239 static int viewmove_modal(bContext *C, wmOperator *op, wmEvent *event)
1240 {
1241
1242         ViewOpsData *vod= op->customdata;
1243         short event_code= VIEW_PASS;
1244
1245         /* execute the events */
1246         if(event->type==MOUSEMOVE) {
1247                 event_code= VIEW_APPLY;
1248         }
1249         else if(event->type==EVT_MODAL_MAP) {
1250                 switch (event->val) {
1251                         case VIEW_MODAL_CONFIRM:
1252                                 event_code= VIEW_CONFIRM;
1253                                 break;
1254                         case VIEWROT_MODAL_SWITCH_ZOOM:
1255                                 WM_operator_name_call(C, "VIEW3D_OT_zoom", WM_OP_INVOKE_DEFAULT, NULL);
1256                                 event_code= VIEW_CONFIRM;
1257                                 break;
1258                         case VIEWROT_MODAL_SWITCH_ROTATE:
1259                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
1260                                 event_code= VIEW_CONFIRM;
1261                                 break;
1262                 }
1263         }
1264         else if(event->type==vod->origkey && event->val==KM_RELEASE) {
1265                 event_code= VIEW_CONFIRM;
1266         }
1267
1268         if(event_code==VIEW_APPLY) {
1269                 viewmove_apply(vod, event->x, event->y);
1270         }
1271         else if (event_code==VIEW_CONFIRM) {
1272                 ED_view3d_depth_tag_update(vod->rv3d);
1273
1274                 viewops_data_free(C, op);
1275
1276                 return OPERATOR_FINISHED;
1277         }
1278
1279         return OPERATOR_RUNNING_MODAL;
1280 }
1281
1282 static int viewmove_invoke(bContext *C, wmOperator *op, wmEvent *event)
1283 {
1284         ViewOpsData *vod;
1285
1286         /* makes op->customdata */
1287         viewops_data_create(C, op, event);
1288         vod= op->customdata;
1289
1290         if (event->type == MOUSEPAN) {
1291                 viewmove_apply(vod, event->prevx, event->prevy);
1292                 ED_view3d_depth_tag_update(vod->rv3d);
1293                 
1294                 viewops_data_free(C, op);               
1295                 
1296                 return OPERATOR_FINISHED;
1297         }
1298         else {
1299                 /* add temp handler */
1300                 WM_event_add_modal_handler(C, op);
1301
1302                 return OPERATOR_RUNNING_MODAL;
1303         }
1304 }
1305
1306 static int viewmove_cancel(bContext *C, wmOperator *op)
1307 {
1308         viewops_data_free(C, op);
1309
1310         return OPERATOR_CANCELLED;
1311 }
1312
1313 void VIEW3D_OT_move(wmOperatorType *ot)
1314 {
1315
1316         /* identifiers */
1317         ot->name= "Move view";
1318         ot->description = "Move the view";
1319         ot->idname= "VIEW3D_OT_move";
1320
1321         /* api callbacks */
1322         ot->invoke= viewmove_invoke;
1323         ot->modal= viewmove_modal;
1324         ot->poll= ED_operator_view3d_active;
1325         ot->cancel= viewmove_cancel;
1326
1327         /* flags */
1328         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1329 }
1330
1331 /* ************************ viewzoom ******************************** */
1332
1333 /* viewdolly_modal_keymap has an exact copy of this, apply fixes to both */
1334 /* called in transform_ops.c, on each regeneration of keymaps  */
1335 void viewzoom_modal_keymap(wmKeyConfig *keyconf)
1336 {
1337         static EnumPropertyItem modal_items[] = {
1338         {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
1339                 
1340         {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
1341         {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
1342
1343         {0, NULL, 0, NULL, NULL}};
1344
1345         wmKeyMap *keymap= WM_modalkeymap_get(keyconf, "View3D Zoom Modal");
1346
1347         /* this function is called for each spacetype, only needs to add map once */
1348         if(keymap) return;
1349
1350         keymap= WM_modalkeymap_add(keyconf, "View3D Zoom Modal", modal_items);
1351
1352         /* items for modal map */
1353         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1354         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1355
1356         /* disabled mode switching for now, can re-implement better, later on
1357         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1358         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1359         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
1360          */
1361         
1362         /* assign map to operators */
1363         WM_modalkeymap_assign(keymap, "VIEW3D_OT_zoom");
1364 }
1365
1366 static void view_zoom_mouseloc(ARegion *ar, float dfac, int mx, int my)
1367 {
1368         RegionView3D *rv3d= ar->regiondata;
1369
1370         if(U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
1371                 float dvec[3];
1372                 float tvec[3];
1373                 float tpos[3];
1374                 float mval_f[2];
1375                 float new_dist;
1376
1377                 negate_v3_v3(tpos, rv3d->ofs);
1378
1379                 /* Project cursor position into 3D space */
1380                 initgrabz(rv3d, tpos[0], tpos[1], tpos[2]);
1381
1382                 mval_f[0]= (float)(((mx - ar->winrct.xmin) * 2) - ar->winx) / 2.0f;
1383                 mval_f[1]= (float)(((my - ar->winrct.ymin) * 2) - ar->winy) / 2.0f;
1384                 ED_view3d_win_to_delta(ar, mval_f, dvec);
1385
1386                 /* Calculate view target position for dolly */
1387                 add_v3_v3v3(tvec, tpos, dvec);
1388                 negate_v3(tvec);
1389
1390                 /* Offset to target position and dolly */
1391                 new_dist = rv3d->dist * dfac;
1392
1393                 copy_v3_v3(rv3d->ofs, tvec);
1394                 rv3d->dist = new_dist;
1395
1396                 /* Calculate final offset */
1397                 madd_v3_v3v3fl(rv3d->ofs, tvec, dvec, dfac);
1398         } else {
1399                 rv3d->dist *= dfac;
1400         }
1401 }
1402
1403
1404 static void viewzoom_apply(ViewOpsData *vod, int x, int y, const short viewzoom, const short zoom_invert)
1405 {
1406         float zfac=1.0;
1407
1408         if(viewzoom==USER_ZOOM_CONT) {
1409                 double time= PIL_check_seconds_timer();
1410                 float time_step= (float)(time - vod->timer_lastdraw);
1411                 float fac;
1412
1413                 if (U.uiflag & USER_ZOOM_HORIZ) {
1414                         fac= (float)(x - vod->origx);
1415                 }
1416                 else {
1417                         fac= (float)(y - vod->origy);
1418                 }
1419
1420                 if(zoom_invert) {
1421                         fac= -fac;
1422                 }
1423
1424                 // oldstyle zoom
1425                 zfac = 1.0f + ((fac / 20.0f) * time_step);
1426                 vod->timer_lastdraw= time;
1427         }
1428         else if(viewzoom==USER_ZOOM_SCALE) {
1429                 int ctr[2], len1, len2;
1430                 // method which zooms based on how far you move the mouse
1431
1432                 ctr[0] = (vod->ar->winrct.xmax + vod->ar->winrct.xmin)/2;
1433                 ctr[1] = (vod->ar->winrct.ymax + vod->ar->winrct.ymin)/2;
1434
1435                 len1 = (int)sqrt((ctr[0] - x)*(ctr[0] - x) + (ctr[1] - y)*(ctr[1] - y)) + 5;
1436                 len2 = (int)sqrt((ctr[0] - vod->origx)*(ctr[0] - vod->origx) + (ctr[1] - vod->origy)*(ctr[1] - vod->origy)) + 5;
1437
1438                 zfac = vod->dist0 * ((float)len2/len1) / vod->rv3d->dist;
1439         }
1440         else {  /* USER_ZOOM_DOLLY */
1441                 float len1, len2;
1442                 
1443                 if (U.uiflag & USER_ZOOM_HORIZ) {
1444                         len1 = (vod->ar->winrct.xmax - x) + 5;
1445                         len2 = (vod->ar->winrct.xmax - vod->origx) + 5;
1446                 }
1447                 else {
1448                         len1 = (vod->ar->winrct.ymax - y) + 5;
1449                         len2 = (vod->ar->winrct.ymax - vod->origy) + 5;
1450                 }
1451                 if (zoom_invert) {
1452                         SWAP(float, len1, len2);
1453                 }
1454                 
1455                 zfac = vod->dist0 * (2.0f * ((len2/len1)-1.0f) + 1.0f) / vod->rv3d->dist;
1456         }
1457
1458         if(zfac != 1.0f && zfac*vod->rv3d->dist > 0.001f * vod->grid &&
1459                         zfac * vod->rv3d->dist < 10.0f * vod->far)
1460                 view_zoom_mouseloc(vod->ar, zfac, vod->oldx, vod->oldy);
1461
1462         /* these limits were in old code too */
1463         if(vod->rv3d->dist<0.001f * vod->grid) vod->rv3d->dist= 0.001f * vod->grid;
1464         if(vod->rv3d->dist>10.0f * vod->far) vod->rv3d->dist=10.0f * vod->far;
1465
1466         if(vod->rv3d->viewlock & RV3D_BOXVIEW)
1467                 view3d_boxview_sync(vod->sa, vod->ar);
1468
1469         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
1470
1471         ED_region_tag_redraw(vod->ar);
1472 }
1473
1474
1475 static int viewzoom_modal(bContext *C, wmOperator *op, wmEvent *event)
1476 {
1477         ViewOpsData *vod= op->customdata;
1478         short event_code= VIEW_PASS;
1479
1480         /* execute the events */
1481         if (event->type == TIMER && event->customdata == vod->timer) {
1482                 /* continuous zoom */
1483                 event_code= VIEW_APPLY;
1484         }
1485         else if(event->type==MOUSEMOVE) {
1486                 event_code= VIEW_APPLY;
1487         }
1488         else if(event->type==EVT_MODAL_MAP) {
1489                 switch (event->val) {
1490                         case VIEW_MODAL_CONFIRM:
1491                                 event_code= VIEW_CONFIRM;
1492                                 break;
1493                         case VIEWROT_MODAL_SWITCH_MOVE:
1494                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
1495                                 event_code= VIEW_CONFIRM;
1496                                 break;
1497                         case VIEWROT_MODAL_SWITCH_ROTATE:
1498                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
1499                                 event_code= VIEW_CONFIRM;
1500                                 break;
1501                 }
1502         }
1503         else if(event->type==vod->origkey && event->val==KM_RELEASE) {
1504                 event_code= VIEW_CONFIRM;
1505         }
1506
1507         if(event_code==VIEW_APPLY) {
1508                 viewzoom_apply(vod, event->x, event->y, U.viewzoom, (U.uiflag & USER_ZOOM_INVERT) != 0);
1509         }
1510         else if (event_code==VIEW_CONFIRM) {
1511                 ED_view3d_depth_tag_update(vod->rv3d);
1512                 viewops_data_free(C, op);
1513
1514                 return OPERATOR_FINISHED;
1515         }
1516
1517         return OPERATOR_RUNNING_MODAL;
1518 }
1519
1520 static int viewzoom_exec(bContext *C, wmOperator *op)
1521 {
1522         View3D *v3d;
1523         RegionView3D *rv3d;
1524         ScrArea *sa;
1525         ARegion *ar;
1526         short use_cam_zoom;
1527
1528         int delta= RNA_int_get(op->ptr, "delta");
1529         int mx, my;
1530
1531         if(op->customdata) {
1532                 ViewOpsData *vod= op->customdata;
1533
1534                 sa= vod->sa;
1535                 ar= vod->ar;
1536         }
1537         else {
1538                 sa= CTX_wm_area(C);
1539                 ar= CTX_wm_region(C);
1540         }
1541
1542         v3d= sa->spacedata.first;
1543         rv3d= ar->regiondata;
1544
1545         mx= RNA_property_is_set(op->ptr, "mx") ? RNA_int_get(op->ptr, "mx") : ar->winx / 2;
1546         my= RNA_property_is_set(op->ptr, "my") ? RNA_int_get(op->ptr, "my") : ar->winy / 2;
1547
1548         use_cam_zoom= (rv3d->persp==RV3D_CAMOB) && !(rv3d->is_persp && ED_view3d_camera_lock_check(v3d, rv3d));
1549
1550         if(delta < 0) {
1551                 /* this min and max is also in viewmove() */
1552                 if(use_cam_zoom) {
1553                         rv3d->camzoom-= 10;
1554                         if(rv3d->camzoom < RV3D_CAMZOOM_MIN) rv3d->camzoom= RV3D_CAMZOOM_MIN;
1555                 }
1556                 else if(rv3d->dist < 10.0f * v3d->far) {
1557                         view_zoom_mouseloc(ar, 1.2f, mx, my);
1558                 }
1559         }
1560         else {
1561                 if(use_cam_zoom) {
1562                         rv3d->camzoom+= 10;
1563                         if(rv3d->camzoom > RV3D_CAMZOOM_MAX) rv3d->camzoom= RV3D_CAMZOOM_MAX;
1564                 }
1565                 else if(rv3d->dist> 0.001f * v3d->grid) {
1566                         view_zoom_mouseloc(ar, .83333f, mx, my);
1567                 }
1568         }
1569
1570         if(rv3d->viewlock & RV3D_BOXVIEW)
1571                 view3d_boxview_sync(sa, ar);
1572
1573         ED_view3d_depth_tag_update(rv3d);
1574
1575         ED_view3d_camera_lock_sync(v3d, rv3d);
1576
1577         ED_region_tag_redraw(ar);
1578
1579         viewops_data_free(C, op);
1580
1581         return OPERATOR_FINISHED;
1582 }
1583
1584 /* this is an exact copy of viewzoom_modal_keymap */
1585 /* called in transform_ops.c, on each regeneration of keymaps  */
1586 void viewdolly_modal_keymap(wmKeyConfig *keyconf)
1587 {
1588         static EnumPropertyItem modal_items[] = {
1589         {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
1590
1591         {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
1592         {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
1593
1594         {0, NULL, 0, NULL, NULL}};
1595
1596         wmKeyMap *keymap= WM_modalkeymap_get(keyconf, "View3D Dolly Modal");
1597
1598         /* this function is called for each spacetype, only needs to add map once */
1599         if(keymap) return;
1600
1601         keymap= WM_modalkeymap_add(keyconf, "View3D Dolly Modal", modal_items);
1602
1603         /* items for modal map */
1604         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1605         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1606
1607         /* disabled mode switching for now, can re-implement better, later on
1608         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1609         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1610         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
1611          */
1612         
1613         /* assign map to operators */
1614         WM_modalkeymap_assign(keymap, "VIEW3D_OT_dolly");
1615 }
1616
1617 /* viewdolly_invoke() copied this function, changes here may apply there */
1618 static int viewzoom_invoke(bContext *C, wmOperator *op, wmEvent *event)
1619 {
1620         ViewOpsData *vod;
1621
1622         /* makes op->customdata */
1623         viewops_data_create(C, op, event);
1624         vod= op->customdata;
1625
1626         /* if one or the other zoom position aren't set, set from event */
1627         if (!RNA_property_is_set(op->ptr, "mx") || !RNA_property_is_set(op->ptr, "my"))
1628         {
1629                 RNA_int_set(op->ptr, "mx", event->x);
1630                 RNA_int_set(op->ptr, "my", event->y);
1631         }
1632
1633         if(RNA_property_is_set(op->ptr, "delta")) {
1634                 viewzoom_exec(C, op);
1635         }
1636         else {
1637                 if (event->type == MOUSEZOOM) {
1638                         /* Bypass Zoom invert flag for track pads (pass FALSE always) */
1639
1640                         if (U.uiflag & USER_ZOOM_HORIZ) {
1641                                 vod->origx = vod->oldx = event->x;
1642                                 viewzoom_apply(vod, event->prevx, event->prevy, USER_ZOOM_DOLLY, FALSE);
1643                         }
1644                         else {
1645                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
1646                                 vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
1647                                 viewzoom_apply(vod, event->prevx, event->prevy, USER_ZOOM_DOLLY, FALSE);
1648                         }
1649                         ED_view3d_depth_tag_update(vod->rv3d);
1650                         
1651                         viewops_data_free(C, op);
1652                         return OPERATOR_FINISHED;
1653                 }
1654                 else {
1655                         if(U.viewzoom == USER_ZOOM_CONT) {
1656                                 /* needs a timer to continue redrawing */
1657                                 vod->timer= WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
1658                                 vod->timer_lastdraw= PIL_check_seconds_timer();
1659                         }
1660
1661                         /* add temp handler */
1662                         WM_event_add_modal_handler(C, op);
1663
1664                         return OPERATOR_RUNNING_MODAL;
1665                 }
1666         }
1667         return OPERATOR_FINISHED;
1668 }
1669
1670 static int viewzoom_cancel(bContext *C, wmOperator *op)
1671 {
1672         viewops_data_free(C, op);
1673
1674         return OPERATOR_CANCELLED;
1675 }
1676
1677 void VIEW3D_OT_zoom(wmOperatorType *ot)
1678 {
1679         /* identifiers */
1680         ot->name= "Zoom View";
1681         ot->description = "Zoom in/out in the view";
1682         ot->idname= "VIEW3D_OT_zoom";
1683
1684         /* api callbacks */
1685         ot->invoke= viewzoom_invoke;
1686         ot->exec= viewzoom_exec;
1687         ot->modal= viewzoom_modal;
1688         ot->poll= ED_operator_region_view3d_active;
1689         ot->cancel= viewzoom_cancel;
1690
1691         /* flags */
1692         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1693
1694         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
1695         RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
1696         RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
1697 }
1698
1699
1700 /* ************************ viewdolly ******************************** */
1701 static void view_dolly_mouseloc(ARegion *ar, float orig_ofs[3], float dvec[3], float dfac)
1702 {
1703         RegionView3D *rv3d= ar->regiondata;
1704         madd_v3_v3v3fl(rv3d->ofs, orig_ofs, dvec, -(1.0 - dfac));
1705 }
1706
1707 static void viewdolly_apply(ViewOpsData *vod, int x, int y, const short zoom_invert)
1708 {
1709         float zfac=1.0;
1710
1711         {
1712                 float len1, len2;
1713
1714                 if (U.uiflag & USER_ZOOM_HORIZ) {
1715                         len1 = (vod->ar->winrct.xmax - x) + 5;
1716                         len2 = (vod->ar->winrct.xmax - vod->origx) + 5;
1717                 }
1718                 else {
1719                         len1 = (vod->ar->winrct.ymax - y) + 5;
1720                         len2 = (vod->ar->winrct.ymax - vod->origy) + 5;
1721                 }
1722                 if (zoom_invert)
1723                         SWAP(float, len1, len2);
1724
1725                 zfac =  1.0 + ((len2 - len1) * 0.01 * vod->rv3d->dist);
1726         }
1727
1728         if(zfac != 1.0f)
1729                 view_dolly_mouseloc(vod->ar, vod->ofs, vod->mousevec, zfac);
1730
1731         if(vod->rv3d->viewlock & RV3D_BOXVIEW)
1732                 view3d_boxview_sync(vod->sa, vod->ar);
1733
1734         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
1735
1736         ED_region_tag_redraw(vod->ar);
1737 }
1738
1739
1740 static int viewdolly_modal(bContext *C, wmOperator *op, wmEvent *event)
1741 {
1742         ViewOpsData *vod= op->customdata;
1743         short event_code= VIEW_PASS;
1744
1745         /* execute the events */
1746         if(event->type==MOUSEMOVE) {
1747                 event_code= VIEW_APPLY;
1748         }
1749         else if(event->type==EVT_MODAL_MAP) {
1750                 switch (event->val) {
1751                         case VIEW_MODAL_CONFIRM:
1752                                 event_code= VIEW_CONFIRM;
1753                                 break;
1754                         case VIEWROT_MODAL_SWITCH_MOVE:
1755                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
1756                                 event_code= VIEW_CONFIRM;
1757                                 break;
1758                         case VIEWROT_MODAL_SWITCH_ROTATE:
1759                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
1760                                 event_code= VIEW_CONFIRM;
1761                                 break;
1762                 }
1763         }
1764         else if(event->type==vod->origkey && event->val==KM_RELEASE) {
1765                 event_code= VIEW_CONFIRM;
1766         }
1767
1768         if(event_code==VIEW_APPLY) {
1769                 viewdolly_apply(vod, event->x, event->y, (U.uiflag & USER_ZOOM_INVERT) != 0);
1770         }
1771         else if (event_code==VIEW_CONFIRM) {
1772                 ED_view3d_depth_tag_update(vod->rv3d);
1773                 viewops_data_free(C, op);
1774
1775                 return OPERATOR_FINISHED;
1776         }
1777
1778         return OPERATOR_RUNNING_MODAL;
1779 }
1780
1781 static int viewdolly_exec(bContext *C, wmOperator *op)
1782 {
1783         /* View3D *v3d; */
1784         RegionView3D *rv3d;
1785         ScrArea *sa;
1786         ARegion *ar;
1787         float mousevec[3];
1788
1789         int delta= RNA_int_get(op->ptr, "delta");
1790
1791         if(op->customdata) {
1792                 ViewOpsData *vod= op->customdata;
1793
1794                 sa= vod->sa;
1795                 ar= vod->ar;
1796                 copy_v3_v3(mousevec, vod->mousevec);
1797         }
1798         else {
1799                 sa= CTX_wm_area(C);
1800                 ar= CTX_wm_region(C);
1801                 negate_v3_v3(mousevec, ((RegionView3D *)ar->regiondata)->viewinv[2]);
1802                 normalize_v3(mousevec);
1803         }
1804
1805         /* v3d= sa->spacedata.first; */ /* UNUSED */
1806         rv3d= ar->regiondata;
1807
1808         /* overwrite the mouse vector with the view direction (zoom into the center) */
1809         if((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
1810                 normalize_v3_v3(mousevec, rv3d->viewinv[2]);
1811         }
1812
1813         if(delta < 0) {
1814                 view_dolly_mouseloc(ar, rv3d->ofs, mousevec, 1.2f);
1815         }
1816         else {
1817                 view_dolly_mouseloc(ar, rv3d->ofs, mousevec, .83333f);
1818         }
1819
1820         if(rv3d->viewlock & RV3D_BOXVIEW)
1821                 view3d_boxview_sync(sa, ar);
1822
1823         ED_view3d_depth_tag_update(rv3d);
1824         ED_region_tag_redraw(ar);
1825
1826         viewops_data_free(C, op);
1827
1828         return OPERATOR_FINISHED;
1829 }
1830
1831 /* copied from viewzoom_invoke(), changes here may apply there */
1832 static int viewdolly_invoke(bContext *C, wmOperator *op, wmEvent *event)
1833 {
1834         ViewOpsData *vod;
1835
1836         /* makes op->customdata */
1837         viewops_data_create(C, op, event);
1838         vod= op->customdata;
1839
1840         /* if one or the other zoom position aren't set, set from event */
1841         if (!RNA_property_is_set(op->ptr, "mx") || !RNA_property_is_set(op->ptr, "my"))
1842         {
1843                 RNA_int_set(op->ptr, "mx", event->x);
1844                 RNA_int_set(op->ptr, "my", event->y);
1845         }
1846
1847         if(RNA_property_is_set(op->ptr, "delta")) {
1848                 viewdolly_exec(C, op);
1849         }
1850         else {
1851                 /* overwrite the mouse vector with the view direction (zoom into the center) */
1852                 if((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
1853                         negate_v3_v3(vod->mousevec, vod->rv3d->viewinv[2]);
1854                         normalize_v3(vod->mousevec);
1855                 }
1856
1857                 if (event->type == MOUSEZOOM) {
1858                         /* Bypass Zoom invert flag for track pads (pass FALSE always) */
1859
1860                         if (U.uiflag & USER_ZOOM_HORIZ) {
1861                                 vod->origx = vod->oldx = event->x;
1862                                 viewdolly_apply(vod, event->prevx, event->prevy, FALSE);
1863                         }
1864                         else {
1865
1866                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
1867                                 vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
1868                                 viewdolly_apply(vod, event->prevx, event->prevy, FALSE);
1869                         }
1870                         ED_view3d_depth_tag_update(vod->rv3d);
1871
1872                         viewops_data_free(C, op);
1873                         return OPERATOR_FINISHED;
1874                 }
1875                 else {
1876                         /* add temp handler */
1877                         WM_event_add_modal_handler(C, op);
1878
1879                         return OPERATOR_RUNNING_MODAL;
1880                 }
1881         }
1882         return OPERATOR_FINISHED;
1883 }
1884
1885 /* like ED_operator_region_view3d_active but check its not in ortho view */
1886 static int viewdolly_poll(bContext *C)
1887 {
1888         RegionView3D *rv3d= CTX_wm_region_view3d(C);
1889
1890         if(rv3d) {
1891                 if (rv3d->persp == RV3D_PERSP) {
1892                         return 1;
1893                 }
1894                 else {
1895                         View3D *v3d= CTX_wm_view3d(C);
1896                         if (ED_view3d_camera_lock_check(v3d, rv3d)) {
1897                                 return 1;
1898                         }
1899                 }
1900         }
1901         return 0;
1902 }
1903
1904 static int viewdolly_cancel(bContext *C, wmOperator *op)
1905 {
1906         viewops_data_free(C, op);
1907
1908         return OPERATOR_CANCELLED;
1909 }
1910
1911 void VIEW3D_OT_dolly(wmOperatorType *ot)
1912 {
1913         /* identifiers */
1914         ot->name= "Dolly view";
1915         ot->description = "Dolly in/out in the view";
1916         ot->idname= "VIEW3D_OT_dolly";
1917
1918         /* api callbacks */
1919         ot->invoke= viewdolly_invoke;
1920         ot->exec= viewdolly_exec;
1921         ot->modal= viewdolly_modal;
1922         ot->poll= viewdolly_poll;
1923         ot->cancel= viewdolly_cancel;
1924
1925         /* flags */
1926         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1927
1928         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
1929         RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
1930         RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
1931 }
1932
1933
1934
1935 static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in 2.4x */
1936 {
1937         ARegion *ar= CTX_wm_region(C);
1938         View3D *v3d = CTX_wm_view3d(C);
1939         RegionView3D *rv3d= CTX_wm_region_view3d(C);
1940         Scene *scene= CTX_data_scene(C);
1941         Base *base;
1942         float *curs;
1943         const short skip_camera= ED_view3d_camera_lock_check(v3d, rv3d);
1944
1945         int center= RNA_boolean_get(op->ptr, "center");
1946
1947         float size, min[3], max[3], afm[3];
1948         int ok= 1, onedone=0;
1949
1950         if(center) {
1951                 /* in 2.4x this also move the cursor to (0, 0, 0) (with shift+c). */
1952                 curs= give_cursor(scene, v3d);
1953                 zero_v3(min);
1954                 zero_v3(max);
1955                 zero_v3(curs);
1956         }
1957         else {
1958                 INIT_MINMAX(min, max);
1959         }
1960
1961         for(base= scene->base.first; base; base= base->next) {
1962                 if(BASE_VISIBLE(v3d, base)) {
1963                         onedone= 1;
1964
1965                         if(skip_camera && base->object == v3d->camera) {
1966                                 continue;
1967                         }
1968
1969                         minmax_object(base->object, min, max);
1970                 }
1971         }
1972         if(!onedone) {
1973                 ED_region_tag_redraw(ar);
1974                 /* TODO - should this be cancel?
1975                  * I think no, because we always move the cursor, with or without
1976                  * object, but in this case there is no change in the scene,
1977                  * only the cursor so I choice a ED_region_tag like
1978                  * smooth_view do for the center_cursor.
1979                  * See bug #22640
1980                  */
1981                 return OPERATOR_FINISHED;
1982         }
1983
1984         sub_v3_v3v3(afm, max, min);
1985         size= 0.7f*MAX3(afm[0], afm[1], afm[2]);
1986         if(size == 0.0f) ok= 0;
1987
1988         if(ok) {
1989                 float new_dist;
1990                 float new_ofs[3];
1991
1992                 new_dist = size;
1993                 new_ofs[0]= -(min[0]+max[0])/2.0f;
1994                 new_ofs[1]= -(min[1]+max[1])/2.0f;
1995                 new_ofs[2]= -(min[2]+max[2])/2.0f;
1996
1997                 // correction for window aspect ratio
1998                 if(ar->winy>2 && ar->winx>2) {
1999                         size= (float)ar->winx/(float)ar->winy;
2000                         if(size < 1.0f) size= 1.0f/size;
2001                         new_dist*= size;
2002                 }
2003
2004                 if ((rv3d->persp==RV3D_CAMOB) && !ED_view3d_camera_lock_check(v3d, rv3d)) {
2005                         rv3d->persp= RV3D_PERSP;
2006                         smooth_view(C, v3d, ar, v3d->camera, NULL, new_ofs, NULL, &new_dist, NULL);
2007                 }
2008                 else {
2009                         smooth_view(C, v3d, ar, NULL, NULL, new_ofs, NULL, &new_dist, NULL);
2010                 }
2011         }
2012 // XXX  BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
2013
2014         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_VIEW3D, v3d);
2015
2016         return OPERATOR_FINISHED;
2017 }
2018
2019
2020 void VIEW3D_OT_view_all(wmOperatorType *ot)
2021 {
2022         /* identifiers */
2023         ot->name= "View All";
2024         ot->description = "View all objects in scene";
2025         ot->idname= "VIEW3D_OT_view_all";
2026
2027         /* api callbacks */
2028         ot->exec= view3d_all_exec;
2029         ot->poll= ED_operator_region_view3d_active;
2030
2031         /* flags */
2032         ot->flag= 0;
2033
2034         RNA_def_boolean(ot->srna, "center", 0, "Center", "");
2035 }
2036
2037
2038 static int viewselected_exec(bContext *C, wmOperator *UNUSED(op)) /* like a localview without local!, was centerview() in 2.4x */
2039 {
2040         ARegion *ar= CTX_wm_region(C);
2041         View3D *v3d = CTX_wm_view3d(C);
2042         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2043         Scene *scene= CTX_data_scene(C);
2044         Object *ob= OBACT;
2045         Object *obedit= CTX_data_edit_object(C);
2046         float size, min[3], max[3], afm[3];
2047         int ok=0, ok_dist=1;
2048         const short skip_camera= ED_view3d_camera_lock_check(v3d, rv3d);
2049
2050         /* SMOOTHVIEW */
2051         float new_ofs[3];
2052         float new_dist;
2053
2054         INIT_MINMAX(min, max);
2055
2056         if (ob && ob->mode & OB_MODE_WEIGHT_PAINT) {
2057                 /* hardcoded exception, we look for the one selected armature */
2058                 /* this is weak code this way, we should make a generic active/selection callback interface once... */
2059                 Base *base;
2060                 for(base=scene->base.first; base; base= base->next) {
2061                         if(TESTBASELIB(v3d, base)) {
2062                                 if(base->object->type==OB_ARMATURE)
2063                                         if(base->object->mode & OB_MODE_POSE)
2064                                                 break;
2065                         }
2066                 }
2067                 if(base)
2068                         ob= base->object;
2069         }
2070
2071
2072         if(obedit) {
2073                 ok = minmax_verts(obedit, min, max);    /* only selected */
2074         }
2075         else if(ob && (ob->mode & OB_MODE_POSE)) {
2076                 if(ob->pose) {
2077                         bArmature *arm= ob->data;
2078                         bPoseChannel *pchan;
2079                         float vec[3];
2080
2081                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2082                                 if(pchan->bone->flag & BONE_SELECTED) {
2083                                         if(pchan->bone->layer & arm->layer) {
2084                                                 bPoseChannel *pchan_tx= pchan->custom_tx ? pchan->custom_tx : pchan;
2085                                                 ok= 1;
2086                                                 mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_head);
2087                                                 DO_MINMAX(vec, min, max);
2088                                                 mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_tail);
2089                                                 DO_MINMAX(vec, min, max);
2090                                         }
2091                                 }
2092                         }
2093                 }
2094         }
2095         else if (paint_facesel_test(ob)) {
2096                 ok= paintface_minmax(ob, min, max);
2097         }
2098         else if (ob && (ob->mode & OB_MODE_PARTICLE_EDIT)) {
2099                 ok= PE_minmax(scene, min, max);
2100         }
2101         else {
2102                 Base *base;
2103                 for(base= FIRSTBASE; base; base = base->next) {
2104                         if(TESTBASE(v3d, base))  {
2105
2106                                 if(skip_camera && base->object == v3d->camera) {
2107                                         continue;
2108                                 }
2109
2110                                 /* account for duplis */
2111                                 if (minmax_object_duplis(scene, base->object, min, max)==0)
2112                                         minmax_object(base->object, min, max); /* use if duplis not found */
2113
2114                                 ok= 1;
2115                         }
2116                 }
2117         }
2118
2119         if(ok==0) return OPERATOR_FINISHED;
2120
2121         sub_v3_v3v3(afm, max, min);
2122         size= MAX3(afm[0], afm[1], afm[2]);
2123
2124         if(!rv3d->is_persp) {
2125                 if(size < 0.0001f) { /* if its a sinble point. dont even re-scale */
2126                         ok_dist= 0;
2127                 }
2128                 else {
2129                         /* perspective should be a bit farther away to look nice */
2130                         size*= 0.7f;
2131                 }
2132         }
2133         else {
2134                 if(size <= v3d->near*1.5f) {
2135                         size= v3d->near*1.5f;
2136                 }
2137         }
2138
2139         add_v3_v3v3(new_ofs, min, max);
2140         mul_v3_fl(new_ofs, -0.5f);
2141
2142         new_dist = size;
2143
2144         /* correction for window aspect ratio */
2145         if(ar->winy>2 && ar->winx>2) {
2146                 size= (float)ar->winx/(float)ar->winy;
2147                 if(size<1.0f) size= 1.0f/size;
2148                 new_dist*= size;
2149         }
2150
2151         if (rv3d->persp==RV3D_CAMOB && !ED_view3d_camera_lock_check(v3d, rv3d)) {
2152                 rv3d->persp= RV3D_PERSP;
2153                 smooth_view(C, v3d, ar, v3d->camera, NULL, new_ofs, NULL, &new_dist, NULL);
2154         }
2155         else {
2156                 smooth_view(C, v3d, ar, NULL, NULL, new_ofs, NULL, ok_dist ? &new_dist : NULL, NULL);
2157         }
2158
2159         /* smooth view does viewlock RV3D_BOXVIEW copy */
2160         
2161 // XXX  BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
2162
2163         return OPERATOR_FINISHED;
2164 }
2165
2166 void VIEW3D_OT_view_selected(wmOperatorType *ot)
2167 {
2168
2169         /* identifiers */
2170         ot->name= "View Selected";
2171         ot->description = "Move the view to the selection center";
2172         ot->idname= "VIEW3D_OT_view_selected";
2173
2174         /* api callbacks */
2175         ot->exec= viewselected_exec;
2176         ot->poll= ED_operator_region_view3d_active;
2177
2178         /* flags */
2179         ot->flag= 0;
2180 }
2181
2182 static int viewcenter_cursor_exec(bContext *C, wmOperator *UNUSED(op))
2183 {
2184         View3D *v3d = CTX_wm_view3d(C);
2185         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2186         Scene *scene= CTX_data_scene(C);
2187         
2188         if (rv3d) {
2189                 ARegion *ar= CTX_wm_region(C);
2190
2191                 /* non camera center */
2192                 float new_ofs[3];
2193                 negate_v3_v3(new_ofs, give_cursor(scene, v3d));
2194                 smooth_view(C, v3d, ar, NULL, NULL, new_ofs, NULL, NULL, NULL);
2195                 
2196                 /* smooth view does viewlock RV3D_BOXVIEW copy */
2197         }
2198         
2199         return OPERATOR_FINISHED;
2200 }
2201
2202 void VIEW3D_OT_view_center_cursor(wmOperatorType *ot)
2203 {
2204         /* identifiers */
2205         ot->name= "Center View to Cursor";
2206         ot->description= "Centers the view so that the cursor is in the middle of the view";
2207         ot->idname= "VIEW3D_OT_view_center_cursor";
2208         
2209         /* api callbacks */
2210         ot->exec= viewcenter_cursor_exec;
2211         ot->poll= ED_operator_view3d_active;
2212         
2213         /* flags */
2214         ot->flag= 0;
2215 }
2216
2217 static int view3d_center_camera_exec(bContext *C, wmOperator *UNUSED(op)) /* was view3d_home() in 2.4x */
2218 {
2219         ARegion *ar= CTX_wm_region(C);
2220         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2221         Scene *scene= CTX_data_scene(C);
2222         float xfac, yfac;
2223         float size[2];
2224
2225         rv3d->camdx= rv3d->camdy= 0.0f;
2226
2227         view3d_viewborder_size_get(scene, ar, size);
2228
2229         /* 4px is just a little room from the edge of the area */
2230         xfac= (float)ar->winx / (float)(size[0] + 4);
2231         yfac= (float)ar->winy / (float)(size[1] + 4);
2232
2233         rv3d->camzoom= BKE_screen_view3d_zoom_from_fac(MIN2(xfac, yfac));
2234         CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
2235
2236         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_VIEW3D, CTX_wm_view3d(C));
2237
2238         return OPERATOR_FINISHED;
2239 }
2240
2241 void VIEW3D_OT_view_center_camera(wmOperatorType *ot)
2242 {
2243         /* identifiers */
2244         ot->name= "View Camera Center";
2245         ot->description = "Center the camera view";
2246         ot->idname= "VIEW3D_OT_view_center_camera";
2247
2248         /* api callbacks */
2249         ot->exec= view3d_center_camera_exec;
2250         ot->poll= view3d_camera_active_poll;
2251
2252         /* flags */
2253         ot->flag= 0;
2254 }
2255
2256 /* ********************* Set render border operator ****************** */
2257
2258 static int render_border_exec(bContext *C, wmOperator *op)
2259 {
2260         View3D *v3d = CTX_wm_view3d(C);
2261         ARegion *ar= CTX_wm_region(C);
2262         RegionView3D *rv3d= ED_view3d_context_rv3d(C);
2263         Scene *scene= CTX_data_scene(C);
2264
2265         rcti rect;
2266         rctf vb;
2267
2268         /* get border select values using rna */
2269         rect.xmin= RNA_int_get(op->ptr, "xmin");
2270         rect.ymin= RNA_int_get(op->ptr, "ymin");
2271         rect.xmax= RNA_int_get(op->ptr, "xmax");
2272         rect.ymax= RNA_int_get(op->ptr, "ymax");
2273
2274         /* calculate range */
2275         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, FALSE);
2276
2277         scene->r.border.xmin= ((float)rect.xmin-vb.xmin)/(vb.xmax-vb.xmin);
2278         scene->r.border.ymin= ((float)rect.ymin-vb.ymin)/(vb.ymax-vb.ymin);
2279         scene->r.border.xmax= ((float)rect.xmax-vb.xmin)/(vb.xmax-vb.xmin);
2280         scene->r.border.ymax= ((float)rect.ymax-vb.ymin)/(vb.ymax-vb.ymin);
2281
2282         /* actually set border */
2283         CLAMP(scene->r.border.xmin, 0.0f, 1.0f);
2284         CLAMP(scene->r.border.ymin, 0.0f, 1.0f);
2285         CLAMP(scene->r.border.xmax, 0.0f, 1.0f);
2286         CLAMP(scene->r.border.ymax, 0.0f, 1.0f);
2287
2288         /* drawing a border surrounding the entire camera view switches off border rendering
2289          * or the border covers no pixels */
2290         if ((scene->r.border.xmin <= 0.0f && scene->r.border.xmax >= 1.0f &&
2291                 scene->r.border.ymin <= 0.0f && scene->r.border.ymax >= 1.0f) ||
2292            (scene->r.border.xmin == scene->r.border.xmax ||
2293                 scene->r.border.ymin == scene->r.border.ymax ))
2294         {
2295                 scene->r.mode &= ~R_BORDER;
2296         } else {
2297                 scene->r.mode |= R_BORDER;
2298         }
2299         
2300         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_OPTIONS, NULL);
2301
2302         return OPERATOR_FINISHED;
2303
2304 }
2305
2306 void VIEW3D_OT_render_border(wmOperatorType *ot)
2307 {
2308         /* identifiers */
2309         ot->name= "Set Render Border";
2310         ot->description = "Set the boundaries of the border render and enables border render ";
2311         ot->idname= "VIEW3D_OT_render_border";
2312
2313         /* api callbacks */
2314         ot->invoke= WM_border_select_invoke;
2315         ot->exec= render_border_exec;
2316         ot->modal= WM_border_select_modal;
2317         ot->cancel= WM_border_select_cancel;
2318
2319         ot->poll= view3d_camera_active_poll;
2320
2321         /* flags */
2322         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2323
2324         /* rna */
2325         RNA_def_int(ot->srna, "xmin", 0, INT_MIN, INT_MAX, "X Min", "", INT_MIN, INT_MAX);
2326         RNA_def_int(ot->srna, "xmax", 0, INT_MIN, INT_MAX, "X Max", "", INT_MIN, INT_MAX);
2327         RNA_def_int(ot->srna, "ymin", 0, INT_MIN, INT_MAX, "Y Min", "", INT_MIN, INT_MAX);
2328         RNA_def_int(ot->srna, "ymax", 0, INT_MIN, INT_MAX, "Y Max", "", INT_MIN, INT_MAX);
2329
2330 }
2331 /* ********************* Border Zoom operator ****************** */
2332
2333 static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
2334 {
2335         ARegion *ar= CTX_wm_region(C);
2336         View3D *v3d = CTX_wm_view3d(C);
2337         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2338         Scene *scene= CTX_data_scene(C);
2339
2340         /* Zooms in on a border drawn by the user */
2341         rcti rect;
2342         float dvec[3], vb[2], xscale, yscale, scale;
2343
2344         /* SMOOTHVIEW */
2345         float new_dist;
2346         float new_ofs[3];
2347
2348         /* ZBuffer depth vars */
2349         bglMats mats;
2350         float depth_close= FLT_MAX;
2351         double cent[2],  p[3];
2352
2353         /* note; otherwise opengl won't work */
2354         view3d_operator_needs_opengl(C);
2355
2356         /* get border select values using rna */
2357         rect.xmin= RNA_int_get(op->ptr, "xmin");
2358         rect.ymin= RNA_int_get(op->ptr, "ymin");
2359         rect.xmax= RNA_int_get(op->ptr, "xmax");
2360         rect.ymax= RNA_int_get(op->ptr, "ymax");
2361
2362         /* Get Z Depths, needed for perspective, nice for ortho */
2363         bgl_get_mats(&mats);
2364         draw_depth(scene, ar, v3d, NULL);
2365         
2366         {
2367                 /* avoid allocating the whole depth buffer */
2368                 ViewDepths depth_temp= {0};
2369
2370                 /* avoid view3d_update_depths() for speed. */
2371                 view3d_update_depths_rect(ar, &depth_temp, &rect);
2372         
2373                 /* find the closest Z pixel */
2374                 depth_close= view3d_depth_near(&depth_temp);
2375         
2376                 MEM_freeN(depth_temp.depths);
2377         }
2378
2379         cent[0] = (((double)rect.xmin)+((double)rect.xmax)) / 2;
2380         cent[1] = (((double)rect.ymin)+((double)rect.ymax)) / 2;
2381
2382         if (rv3d->is_persp) {
2383                 double p_corner[3];
2384
2385                 /* no depths to use, we cant do anything! */
2386                 if (depth_close==FLT_MAX){
2387                         BKE_report(op->reports, RPT_ERROR, "Depth Too Large");
2388                         return OPERATOR_CANCELLED;
2389                 }
2390                 /* convert border to 3d coordinates */
2391                 if ((   !gluUnProject(cent[0], cent[1], depth_close, mats.modelview, mats.projection, (GLint *)mats.viewport, &p[0], &p[1], &p[2])) ||
2392                         (       !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])))
2393                         return OPERATOR_CANCELLED;
2394
2395                 dvec[0] = p[0]-p_corner[0];
2396                 dvec[1] = p[1]-p_corner[1];
2397                 dvec[2] = p[2]-p_corner[2];
2398
2399                 new_dist = len_v3(dvec);
2400                 if(new_dist <= v3d->near * 1.5f) new_dist= v3d->near * 1.5f;
2401
2402                 new_ofs[0] = -p[0];
2403                 new_ofs[1] = -p[1];
2404                 new_ofs[2] = -p[2];
2405
2406         } else { /* othographic */
2407                 /* find the current window width and height */
2408                 vb[0] = ar->winx;
2409                 vb[1] = ar->winy;
2410
2411                 new_dist = rv3d->dist;
2412
2413                 /* convert the drawn rectangle into 3d space */
2414                 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])) {
2415                         new_ofs[0] = -p[0];
2416                         new_ofs[1] = -p[1];
2417                         new_ofs[2] = -p[2];
2418                 }
2419                 else {
2420                         float mval_f[2];
2421                         /* We cant use the depth, fallback to the old way that dosnt set the center depth */
2422                         copy_v3_v3(new_ofs, rv3d->ofs);
2423
2424                         initgrabz(rv3d, -new_ofs[0], -new_ofs[1], -new_ofs[2]);
2425
2426                         mval_f[0]= (rect.xmin + rect.xmax - vb[0]) / 2.0f;
2427                         mval_f[1]= (rect.ymin + rect.ymax - vb[1]) / 2.0f;
2428                         ED_view3d_win_to_delta(ar, mval_f, dvec);
2429                         /* center the view to the center of the rectangle */
2430                         sub_v3_v3(new_ofs, dvec);
2431                 }
2432
2433                 /* work out the ratios, so that everything selected fits when we zoom */
2434                 xscale = ((rect.xmax-rect.xmin)/vb[0]);
2435                 yscale = ((rect.ymax-rect.ymin)/vb[1]);
2436                 scale = (xscale >= yscale)?xscale:yscale;
2437
2438                 /* zoom in as required, or as far as we can go */
2439                 new_dist = ((new_dist*scale) >= 0.001f * v3d->grid)? new_dist*scale:0.001f * v3d->grid;
2440         }
2441
2442         smooth_view(C, v3d, ar, NULL, NULL, new_ofs, NULL, &new_dist, NULL);
2443
2444         if(rv3d->viewlock & RV3D_BOXVIEW)
2445                 view3d_boxview_sync(CTX_wm_area(C), ar);
2446
2447         return OPERATOR_FINISHED;
2448 }
2449
2450 static int view3d_zoom_border_invoke(bContext *C, wmOperator *op, wmEvent *event)
2451 {
2452         View3D *v3d= CTX_wm_view3d(C);
2453         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2454
2455         /* if in camera view do not exec the operator so we do not conflict with set render border*/
2456         if ((rv3d->persp != RV3D_CAMOB) || ED_view3d_camera_lock_check(v3d, rv3d))
2457                 return WM_border_select_invoke(C, op, event);
2458         else
2459                 return OPERATOR_PASS_THROUGH;
2460 }
2461
2462 void VIEW3D_OT_zoom_border(wmOperatorType *ot)
2463 {
2464         /* identifiers */
2465         ot->name= "Border Zoom";
2466         ot->description = "Zoom in the view to the nearest object contained in the border";
2467         ot->idname= "VIEW3D_OT_zoom_border";
2468
2469         /* api callbacks */
2470         ot->invoke= view3d_zoom_border_invoke;
2471         ot->exec= view3d_zoom_border_exec;
2472         ot->modal= WM_border_select_modal;
2473         ot->cancel= WM_border_select_cancel;
2474
2475         ot->poll= ED_operator_region_view3d_active;
2476
2477         /* flags */
2478         ot->flag= 0;
2479
2480         /* rna */
2481         RNA_def_int(ot->srna, "xmin", 0, INT_MIN, INT_MAX, "X Min", "", INT_MIN, INT_MAX);
2482         RNA_def_int(ot->srna, "xmax", 0, INT_MIN, INT_MAX, "X Max", "", INT_MIN, INT_MAX);
2483         RNA_def_int(ot->srna, "ymin", 0, INT_MIN, INT_MAX, "Y Min", "", INT_MIN, INT_MAX);
2484         RNA_def_int(ot->srna, "ymax", 0, INT_MIN, INT_MAX, "Y Max", "", INT_MIN, INT_MAX);
2485
2486 }
2487
2488 /* sets the view to 1:1 camera/render-pixel */
2489 static void view3d_set_1_to_1_viewborder(Scene *scene, ARegion *ar)
2490 {
2491         RegionView3D *rv3d= ar->regiondata;
2492         float size[2];
2493         int im_width= (scene->r.size*scene->r.xsch)/100;
2494         
2495         view3d_viewborder_size_get(scene, ar, size);
2496
2497         rv3d->camzoom= BKE_screen_view3d_zoom_from_fac((float)im_width/size[0]);
2498         CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
2499 }
2500
2501 static int view3d_zoom_1_to_1_camera_exec(bContext *C, wmOperator *UNUSED(op))
2502 {
2503         Scene *scene= CTX_data_scene(C);
2504         ARegion *ar= CTX_wm_region(C);
2505
2506         view3d_set_1_to_1_viewborder(scene, ar);
2507
2508         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_VIEW3D, CTX_wm_view3d(C));
2509
2510         return OPERATOR_FINISHED;
2511 }
2512
2513 void VIEW3D_OT_zoom_camera_1_to_1(wmOperatorType *ot)
2514 {
2515         /* identifiers */
2516         ot->name= "Zoom Camera 1:1";
2517         ot->description = "Match the camera to 1:1 to the render output";
2518         ot->idname= "VIEW3D_OT_zoom_camera_1_to_1";
2519
2520         /* api callbacks */
2521         ot->exec= view3d_zoom_1_to_1_camera_exec;
2522         ot->poll= view3d_camera_active_poll;
2523
2524         /* flags */
2525         ot->flag= 0;
2526 }
2527
2528 /* ********************* Changing view operator ****************** */
2529
2530 static EnumPropertyItem prop_view_items[] = {
2531         {RV3D_VIEW_FRONT, "FRONT", 0, "Front", "View From the Front"},
2532         {RV3D_VIEW_BACK, "BACK", 0, "Back", "View From the Back"},
2533         {RV3D_VIEW_LEFT, "LEFT", 0, "Left", "View From the Left"},
2534         {RV3D_VIEW_RIGHT, "RIGHT", 0, "Right", "View From the Right"},
2535         {RV3D_VIEW_TOP, "TOP", 0, "Top", "View From the Top"},
2536         {RV3D_VIEW_BOTTOM, "BOTTOM", 0, "Bottom", "View From the Bottom"},
2537         {RV3D_VIEW_CAMERA, "CAMERA", 0, "Camera", "View From the active amera"},
2538         {0, NULL, 0, NULL, NULL}};
2539
2540
2541 /* would like to make this a generic function - outside of transform */
2542
2543 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)
2544 {
2545         RegionView3D *rv3d= ar->regiondata; /* no NULL check is needed, poll checks */
2546         float new_quat[4];
2547
2548         new_quat[0]= q1; new_quat[1]= q2;
2549         new_quat[2]= q3; new_quat[3]= q4;
2550         normalize_qt(new_quat);
2551
2552         if(align_active) {
2553                 /* align to active object */
2554                 Object *obact= CTX_data_active_object(C);
2555                 if (obact==NULL) {
2556                         /* no active object, ignore this option */
2557                         align_active= FALSE;
2558                 }
2559                 else {
2560                         float obact_quat[4];
2561                         float twmat[3][3];
2562
2563                         /* same as transform manipulator when normal is set */
2564                         ED_getTransformOrientationMatrix(C, twmat, FALSE);
2565
2566                         mat3_to_quat( obact_quat,twmat);
2567                         invert_qt(obact_quat);
2568                         mul_qt_qtqt(new_quat, new_quat, obact_quat);
2569
2570                         rv3d->view= view= RV3D_VIEW_USER;
2571                 }
2572         }
2573
2574         if(align_active==FALSE) {
2575                 /* normal operation */
2576                 if(rv3d->viewlock) {
2577                         /* only pass on if */
2578                         if(rv3d->view==RV3D_VIEW_FRONT && view==RV3D_VIEW_BACK);
2579                         else if(rv3d->view==RV3D_VIEW_BACK && view==RV3D_VIEW_FRONT);
2580                         else if(rv3d->view==RV3D_VIEW_RIGHT && view==RV3D_VIEW_LEFT);
2581                         else if(rv3d->view==RV3D_VIEW_LEFT && view==RV3D_VIEW_RIGHT);
2582                         else if(rv3d->view==RV3D_VIEW_BOTTOM && view==RV3D_VIEW_TOP);
2583                         else if(rv3d->view==RV3D_VIEW_TOP && view==RV3D_VIEW_BOTTOM);
2584                         else return;
2585                 }
2586
2587                 rv3d->view= view;
2588         }
2589
2590         if(rv3d->viewlock) {
2591                 ED_region_tag_redraw(ar);
2592                 return;
2593         }
2594
2595         if (rv3d->persp==RV3D_CAMOB && v3d->camera) {
2596
2597                 if (U.uiflag & USER_AUTOPERSP) rv3d->persp= view ? RV3D_ORTHO : RV3D_PERSP;
2598                 else if(rv3d->persp==RV3D_CAMOB) rv3d->persp= perspo;
2599
2600                 smooth_view(C, v3d, ar, v3d->camera, NULL, rv3d->ofs, new_quat, NULL, NULL);
2601         }
2602         else {
2603
2604                 if (U.uiflag & USER_AUTOPERSP) rv3d->persp= view ? RV3D_ORTHO : RV3D_PERSP;
2605                 else if(rv3d->persp==RV3D_CAMOB) rv3d->persp= perspo;
2606
2607                 smooth_view(C, v3d, ar, NULL, NULL, NULL, new_quat, NULL, NULL);
2608         }
2609
2610 }
2611
2612 static int viewnumpad_exec(bContext *C, wmOperator *op)
2613 {
2614         View3D *v3d = CTX_wm_view3d(C);
2615         ARegion *ar= ED_view3d_context_region_unlock(C);
2616         RegionView3D *rv3d= ar->regiondata; /* no NULL check is needed, poll checks */
2617         Scene *scene= CTX_data_scene(C);
2618         static int perspo=RV3D_PERSP;
2619         int viewnum, align_active, nextperspo;
2620
2621         viewnum = RNA_enum_get(op->ptr, "type");
2622         align_active = RNA_boolean_get(op->ptr, "align_active");
2623
2624         /* set this to zero, gets handled in axis_set_view */
2625         if(rv3d->viewlock)
2626                 align_active= 0;
2627
2628         /* Use this to test if we started out with a camera */
2629
2630         if (rv3d->persp == RV3D_CAMOB) {
2631                 nextperspo= rv3d->lpersp;
2632         } else {
2633                 nextperspo= perspo;
2634         }
2635
2636         switch (viewnum) {
2637                 case RV3D_VIEW_BOTTOM :
2638                         axis_set_view(C, v3d, ar, 0.0, -1.0, 0.0, 0.0, viewnum, nextperspo, align_active);
2639                         break;
2640
2641                 case RV3D_VIEW_BACK:
2642                         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);
2643                         break;
2644
2645                 case RV3D_VIEW_LEFT:
2646                         axis_set_view(C, v3d, ar, 0.5, -0.5, 0.5, 0.5, viewnum, nextperspo, align_active);
2647                         break;
2648
2649                 case RV3D_VIEW_TOP:
2650                         axis_set_view(C, v3d, ar, 1.0, 0.0, 0.0, 0.0, viewnum, nextperspo, align_active);
2651                         break;
2652
2653                 case RV3D_VIEW_FRONT:
2654                         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);
2655                         break;
2656
2657                 case RV3D_VIEW_RIGHT:
2658                         axis_set_view(C, v3d, ar, 0.5, -0.5, -0.5, -0.5, viewnum, nextperspo, align_active);
2659                         break;
2660
2661                 case RV3D_VIEW_CAMERA:
2662                         if(rv3d->viewlock==0) {
2663                                 /* lastview -  */
2664
2665                                 if(rv3d->persp != RV3D_CAMOB) {
2666                                         Object *ob= OBACT;
2667
2668                                         if (!rv3d->smooth_timer) {
2669                                                 /* store settings of current view before allowing overwriting with camera view
2670                                                  * only if we're not currently in a view transition */
2671                                                 copy_qt_qt(rv3d->lviewquat, rv3d->viewquat);
2672                                                 rv3d->lview= rv3d->view;
2673                                                 rv3d->lpersp= rv3d->persp;
2674                                         }
2675
2676         #if 0
2677                                         if(G.qual==LR_ALTKEY) {
2678                                                 if(oldcamera && is_an_active_object(oldcamera)) {
2679                                                         v3d->camera= oldcamera;
2680                                                 }
2681                                                 handle_view3d_lock();
2682                                         }
2683         #endif
2684                                         
2685                                         /* first get the default camera for the view lock type */
2686                                         if(v3d->scenelock) {
2687                                                 /* sets the camera view if available */
2688                                                 v3d->camera= scene->camera;                                             
2689                                         }
2690                                         else {
2691                                                 /* use scene camera if one is not set (even though we're unlocked) */
2692                                                 if(v3d->camera==NULL) {
2693                                                         v3d->camera= scene->camera;
2694                                                 }
2695                                         }
2696
2697                                         /* if the camera isnt found, check a number of options */
2698                                         if(v3d->camera==NULL && ob && ob->type==OB_CAMERA)
2699                                                 v3d->camera= ob;
2700                                         
2701                                         if(v3d->camera==NULL)
2702                                                 v3d->camera= scene_find_camera(scene);          
2703
2704                                         /* couldnt find any useful camera, bail out */
2705                                         if(v3d->camera==NULL)
2706                                                 return OPERATOR_CANCELLED;
2707                                         
2708                                         /* important these dont get out of sync for locked scenes */
2709                                         if(v3d->scenelock)
2710                                                 scene->camera= v3d->camera;
2711
2712                                         /* finally do snazzy view zooming */
2713                                         rv3d->persp= RV3D_CAMOB;
2714                                         smooth_view(C, v3d, ar, NULL, v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, &v3d->lens);
2715
2716                                 }
2717                                 else{
2718                                         /* return to settings of last view */
2719                                         /* does smooth_view too */
2720                                         axis_set_view(C, v3d, ar, rv3d->lviewquat[0], rv3d->lviewquat[1], rv3d->lviewquat[2], rv3d->lviewquat[3], rv3d->lview, rv3d->lpersp, 0);
2721                                 }
2722                         }
2723                         break;
2724
2725                 default :
2726                         break;
2727         }
2728
2729         if(rv3d->persp != RV3D_CAMOB) perspo= rv3d->persp;
2730
2731         return OPERATOR_FINISHED;
2732 }
2733
2734
2735 void VIEW3D_OT_viewnumpad(wmOperatorType *ot)
2736 {
2737         /* identifiers */
2738         ot->name= "View numpad";
2739         ot->description = "Set the view";
2740         ot->idname= "VIEW3D_OT_viewnumpad";
2741
2742         /* api callbacks */
2743         ot->exec= viewnumpad_exec;
2744         ot->poll= ED_operator_rv3d_unlock_poll;
2745
2746         /* flags */
2747         ot->flag= 0;
2748
2749         RNA_def_enum(ot->srna, "type", prop_view_items, 0, "View", "The Type of view");
2750         RNA_def_boolean(ot->srna, "align_active", 0, "Align Active", "Align to the active objects axis");
2751 }
2752
2753 static EnumPropertyItem prop_view_orbit_items[] = {
2754         {V3D_VIEW_STEPLEFT, "ORBITLEFT", 0, "Orbit Left", "Orbit the view around to the Left"},
2755         {V3D_VIEW_STEPRIGHT, "ORBITRIGHT", 0, "Orbit Right", "Orbit the view around to the Right"},
2756         {V3D_VIEW_STEPUP, "ORBITUP", 0, "Orbit Up", "Orbit the view Up"},
2757         {V3D_VIEW_STEPDOWN, "ORBITDOWN", 0, "Orbit Down", "Orbit the view Down"},
2758         {0, NULL, 0, NULL, NULL}};
2759
2760 static int vieworbit_exec(bContext *C, wmOperator *op)
2761 {
2762         View3D *v3d= CTX_wm_view3d(C);
2763         ARegion *ar= ED_view3d_context_region_unlock(C);
2764         RegionView3D *rv3d= ar->regiondata; /* no NULL check is needed, poll checks */
2765         float phi, q1[4], new_quat[4];
2766         int orbitdir;
2767
2768         orbitdir = RNA_enum_get(op->ptr, "type");
2769
2770         if(rv3d->viewlock==0) {
2771                 if((rv3d->persp != RV3D_CAMOB) || ED_view3d_camera_lock_check(v3d, rv3d)) {
2772                         if(orbitdir == V3D_VIEW_STEPLEFT || orbitdir == V3D_VIEW_STEPRIGHT) {
2773                                 float si;
2774                                 /* z-axis */
2775                                 phi= (float)(M_PI/360.0)*U.pad_rot_angle;
2776                                 if(orbitdir == V3D_VIEW_STEPRIGHT) phi= -phi;
2777                                 si= (float)sin(phi);
2778                                 q1[0]= (float)cos(phi);
2779                                 q1[1]= q1[2]= 0.0;
2780                                 q1[3]= si;
2781                                 mul_qt_qtqt(new_quat, rv3d->viewquat, q1);
2782                                 rv3d->view= RV3D_VIEW_USER;
2783                         }
2784                         else if(orbitdir == V3D_VIEW_STEPDOWN || orbitdir == V3D_VIEW_STEPUP) {
2785                                 /* horizontal axis */
2786                                 copy_v3_v3(q1+1, rv3d->viewinv[0]);
2787
2788                                 normalize_v3(q1+1);
2789                                 phi= (float)(M_PI/360.0)*U.pad_rot_angle;
2790                                 if(orbitdir == V3D_VIEW_STEPDOWN) phi= -phi;
2791                                 q1[0]= (float)cos(phi);
2792                                 mul_v3_fl(q1+1, sin(phi));
2793                                 mul_qt_qtqt(new_quat, rv3d->viewquat, q1);
2794                                 rv3d->view= RV3D_VIEW_USER;
2795                         }
2796
2797                         smooth_view(C, CTX_wm_view3d(C), ar, NULL, NULL, NULL, new_quat, NULL, NULL);
2798                 }
2799         }
2800
2801         return OPERATOR_FINISHED;
2802 }
2803
2804 void VIEW3D_OT_view_orbit(wmOperatorType *ot)
2805 {
2806         /* identifiers */
2807         ot->name= "View Orbit";
2808         ot->description = "Orbit the view";
2809         ot->idname= "VIEW3D_OT_view_orbit";
2810
2811         /* api callbacks */
2812         ot->exec= vieworbit_exec;
2813         ot->poll= ED_operator_rv3d_unlock_poll;
2814
2815         /* flags */
2816         ot->flag= 0;
2817         RNA_def_enum(ot->srna, "type", prop_view_orbit_items, 0, "Orbit", "Direction of View Orbit");
2818 }
2819
2820 static EnumPropertyItem prop_view_pan_items[] = {
2821         {V3D_VIEW_PANLEFT, "PANLEFT", 0, "Pan Left", "Pan the view to the Left"},
2822         {V3D_VIEW_PANRIGHT, "PANRIGHT", 0, "Pan Right", "Pan the view to the Right"},
2823         {V3D_VIEW_PANUP, "PANUP", 0, "Pan Up", "Pan the view Up"},
2824         {V3D_VIEW_PANDOWN, "PANDOWN", 0, "Pan Down", "Pan the view Down"},
2825         {0, NULL, 0, NULL, NULL}};
2826
2827 static int viewpan_exec(bContext *C, wmOperator *op)
2828 {
2829         ARegion *ar= CTX_wm_region(C);
2830         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2831         float vec[3];
2832         float mval_f[2]= {0.0f, 0.0f};
2833         int pandir;
2834
2835         pandir = RNA_enum_get(op->ptr, "type");
2836
2837         initgrabz(rv3d, 0.0, 0.0, 0.0);
2838         if(pandir == V3D_VIEW_PANRIGHT)         { mval_f[0]= -32.0f; ED_view3d_win_to_delta(ar, mval_f, vec); }
2839         else if(pandir == V3D_VIEW_PANLEFT)     { mval_f[0]=  32.0f; ED_view3d_win_to_delta(ar, mval_f, vec); }
2840         else if(pandir == V3D_VIEW_PANUP)       { mval_f[1]= -25.0f; ED_view3d_win_to_delta(ar, mval_f, vec); }
2841         else if(pandir == V3D_VIEW_PANDOWN)     { mval_f[1]=  25.0f; ED_view3d_win_to_delta(ar, mval_f, vec); }
2842         add_v3_v3(rv3d->ofs, vec);
2843
2844         if(rv3d->viewlock & RV3D_BOXVIEW)
2845                 view3d_boxview_sync(CTX_wm_area(C), ar);
2846
2847         ED_region_tag_redraw(ar);
2848
2849         return OPERATOR_FINISHED;
2850 }
2851
2852 void VIEW3D_OT_view_pan(wmOperatorType *ot)
2853 {
2854         /* identifiers */
2855         ot->name= "View Pan";
2856         ot->description = "Pan the view";
2857         ot->idname= "VIEW3D_OT_view_pan";
2858
2859         /* api callbacks */
2860         ot->exec= viewpan_exec;
2861         ot->poll= ED_operator_region_view3d_active;
2862
2863         /* flags */
2864         ot->flag= 0;
2865         RNA_def_enum(ot->srna, "type", prop_view_pan_items, 0, "Pan", "Direction of View Pan");
2866 }
2867
2868 static int viewpersportho_exec(bContext *C, wmOperator *UNUSED(op))
2869 {
2870         ARegion *ar= ED_view3d_context_region_unlock(C);
2871         RegionView3D *rv3d= ar->regiondata; /* no NULL check is needed, poll checks */
2872
2873         if(rv3d->viewlock==0) {
2874                 if(rv3d->persp!=RV3D_ORTHO)
2875                         rv3d->persp=RV3D_ORTHO;
2876                 else rv3d->persp=RV3D_PERSP;
2877                 ED_region_tag_redraw(ar);
2878         }
2879
2880         return OPERATOR_FINISHED;
2881
2882 }
2883
2884 void VIEW3D_OT_view_persportho(wmOperatorType *ot)
2885 {
2886         /* identifiers */
2887         ot->name= "View Persp/Ortho";
2888         ot->description = "Switch the current view from perspective/orthographic";
2889         ot->idname= "VIEW3D_OT_view_persportho";
2890
2891         /* api callbacks */
2892         ot->exec= viewpersportho_exec;
2893         ot->poll= ED_operator_rv3d_unlock_poll;
2894
2895         /* flags */
2896         ot->flag= 0;
2897 }
2898
2899
2900 /* ******************** add background image operator **************** */
2901
2902 static BGpic *background_image_add(bContext *C)
2903 {
2904         View3D *v3d= CTX_wm_view3d(C);
2905         
2906         BGpic *bgpic= MEM_callocN(sizeof(BGpic), "Background Image");
2907         bgpic->size= 5.0;
2908         bgpic->blend= 0.5;
2909         bgpic->iuser.fie_ima= 2;
2910         bgpic->iuser.ok= 1;
2911         bgpic->view= 0; /* 0 for all */
2912         
2913         BLI_addtail(&v3d->bgpicbase, bgpic);
2914         
2915         return bgpic;
2916 }
2917
2918 static int background_image_add_exec(bContext *C, wmOperator *UNUSED(op))
2919 {
2920         background_image_add(C);
2921
2922         return OPERATOR_FINISHED;
2923 }
2924
2925 static int background_image_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2926 {
2927         View3D *v3d= CTX_wm_view3d(C);
2928         Image *ima= NULL;
2929         BGpic *bgpic;
2930         char name[32];
2931         
2932         /* check input variables */
2933         if(RNA_property_is_set(op->ptr, "filepath")) {
2934                 char path[FILE_MAX];
2935                 
2936                 RNA_string_get(op->ptr, "filepath", path);
2937                 ima= BKE_add_image_file(path);
2938         }
2939         else if(RNA_property_is_set(op->ptr, "name")) {
2940                 RNA_string_get(op->ptr, "name", name);
2941                 ima= (Image *)find_id("IM", name);
2942         }
2943         
2944         bgpic = background_image_add(C);
2945         
2946         if (ima) {
2947                 bgpic->ima = ima;
2948                 
2949                 if(ima->id.us==0) id_us_plus(&ima->id);
2950                 else id_lib_extern(&ima->id);
2951                 
2952                 if (!(v3d->flag & V3D_DISPBGPICS))
2953                         v3d->flag |= V3D_DISPBGPICS;
2954         }
2955         
2956         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_VIEW3D, v3d);
2957         
2958         return OPERATOR_FINISHED;
2959 }
2960
2961 void VIEW3D_OT_background_image_add(wmOperatorType *ot)
2962 {
2963         /* identifiers */
2964         ot->name   = "Add Background Image";
2965         ot->description= "Add a new background image";
2966         ot->idname = "VIEW3D_OT_background_image_add";
2967
2968         /* api callbacks */
2969         ot->invoke = background_image_add_invoke;
2970         ot->exec   = background_image_add_exec;
2971         ot->poll   = ED_operator_view3d_active;
2972
2973         /* flags */
2974         ot->flag   = 0;
2975         
2976         /* properties */
2977         RNA_def_string(ot->srna, "name", "Image", 24, "Name", "Image name to assign.");
2978         RNA_def_string(ot->srna, "filepath", "Path", FILE_MAX, "Filepath", "Path to image file");
2979 }
2980
2981
2982 /* ***** remove image operator ******* */
2983 static int background_image_remove_exec(bContext *C, wmOperator *op)
2984 {
2985         View3D *vd = CTX_wm_view3d(C);
2986         int index = RNA_int_get(op->ptr, "index");
2987         BGpic *bgpic_rem= BLI_findlink(&vd->bgpicbase, index);
2988
2989         if(bgpic_rem) {
2990                 BLI_remlink(&vd->bgpicbase, bgpic_rem);
2991                 if(bgpic_rem->ima) bgpic_rem->ima->id.us--;
2992                 MEM_freeN(bgpic_rem);
2993                 WM_event_add_notifier(C, NC_SPACE|ND_SPACE_VIEW3D, vd);
2994                 return OPERATOR_FINISHED;
2995         }
2996         else {
2997                 return OPERATOR_CANCELLED;
2998         }
2999
3000 }
3001
3002 void VIEW3D_OT_background_image_remove(wmOperatorType *ot)
3003 {
3004         /* identifiers */
3005         ot->name   = "Remove Background Image";
3006         ot->description= "Remove a background image from the 3D view";
3007         ot->idname = "VIEW3D_OT_background_image_remove";
3008
3009         /* api callbacks */
3010         ot->exec   = background_image_remove_exec;
3011         ot->poll   = ED_operator_view3d_active;
3012
3013         /* flags */
3014         ot->flag   = 0;
3015
3016         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "Background image index to remove ", 0, INT_MAX);
3017 }
3018
3019 /* ********************* set clipping operator ****************** */
3020
3021 static void calc_clipping_plane(float clip[6][4], BoundBox *clipbb)
3022 {
3023         int val;
3024
3025         for(val=0; val<4; val++) {
3026
3027                 normal_tri_v3( clip[val],clipbb->vec[val], clipbb->vec[val==3?0:val+1], clipbb->vec[val+4]);
3028
3029                 clip[val][3]=
3030                         - clip[val][0]*clipbb->vec[val][0]
3031                         - clip[val][1]*clipbb->vec[val][1]
3032                         - clip[val][2]*clipbb->vec[val][2];
3033         }
3034 }
3035
3036 static void calc_local_clipping(float clip_local[][4], BoundBox *clipbb, float mat[][4])
3037 {
3038         BoundBox clipbb_local;
3039         float imat[4][4];
3040         int i;
3041
3042         invert_m4_m4(imat, mat);
3043
3044         for(i=0; i<8; i++) {
3045                 mul_v3_m4v3(clipbb_local.vec[i], imat, clipbb->vec[i]);
3046         }
3047
3048         calc_clipping_plane(clip_local, &clipbb_local);
3049 }
3050
3051 void ED_view3d_local_clipping(RegionView3D *rv3d, float mat[][4])
3052 {
3053         if(rv3d->rflag & RV3D_CLIPPING)
3054                 calc_local_clipping(rv3d->clip_local, rv3d->clipbb, mat);
3055 }
3056
3057 static int view3d_clipping_exec(bContext *C, wmOperator *op)
3058 {
3059         RegionView3D *rv3d= CTX_wm_region_view3d(C);
3060         ViewContext vc;
3061         bglMats mats;
3062         rcti rect;
3063
3064         rect.xmin= RNA_int_get(op->ptr, "xmin");
3065         rect.ymin= RNA_int_get(op->ptr, "ymin");
3066         rect.xmax= RNA_int_get(op->ptr, "xmax");
3067         rect.ymax= RNA_int_get(op->ptr, "ymax");
3068
3069         rv3d->rflag |= RV3D_CLIPPING;
3070         rv3d->clipbb= MEM_callocN(sizeof(BoundBox), "clipbb");
3071
3072         /* note; otherwise opengl won't work */
3073         view3d_operator_needs_opengl(C);
3074
3075         view3d_set_viewcontext(C, &vc);
3076         view3d_get_transformation(vc.ar, vc.rv3d, NULL, &mats); /* NULL because we don't want it in object space */
3077         ED_view3d_calc_clipping(rv3d->clipbb, rv3d->clip, &mats, &rect);
3078
3079         return OPERATOR_FINISHED;
3080 }
3081
3082 static int view3d_clipping_invoke(bContext *C, wmOperator *op, wmEvent *event)
3083 {
3084         RegionView3D *rv3d= CTX_wm_region_view3d(C);
3085         ARegion *ar= CTX_wm_region(C);
3086
3087         if(rv3d->rflag & RV3D_CLIPPING) {
3088                 rv3d->rflag &= ~RV3D_CLIPPING;
3089                 ED_region_tag_redraw(ar);
3090                 if(rv3d->clipbb) MEM_freeN(rv3d->clipbb);
3091                 rv3d->clipbb= NULL;
3092                 return OPERATOR_FINISHED;
3093         }
3094         else {
3095                 return WM_border_select_invoke(C, op, event);
3096         }
3097 }
3098
3099 /* toggles */
3100 void VIEW3D_OT_clip_border(wmOperatorType *ot)
3101 {
3102
3103         /* identifiers */
3104         ot->name= "Clipping Border";
3105         ot->description = "Set the view clipping border";
3106         ot->idname= "VIEW3D_OT_clip_border";
3107
3108         /* api callbacks */
3109         ot->invoke= view3d_clipping_invoke;
3110         ot->exec= view3d_clipping_exec;
3111         ot->modal= WM_border_select_modal;
3112         ot->cancel= WM_border_select_cancel;
3113
3114         ot->poll= ED_operator_region_view3d_active;
3115
3116         /* flags */
3117         ot->flag= 0;
3118
3119         /* rna */
3120         RNA_def_int(ot->srna, "xmin", 0, INT_MIN, INT_MAX, "X Min", "", INT_MIN, INT_MAX);
3121         RNA_def_int(ot->srna, "xmax", 0, INT_MIN, INT_MAX, "X Max", "", INT_MIN, INT_MAX);
3122         RNA_def_int(ot->srna, "ymin", 0, INT_MIN, INT_MAX, "Y Min", "", INT_MIN, INT_MAX);
3123         RNA_def_int(ot->srna, "ymax", 0, INT_MIN, INT_MAX, "Y Max", "", INT_MIN, INT_MAX);
3124 }
3125
3126 /* ***************** 3d cursor cursor op ******************* */
3127
3128 /* mx my in region coords */
3129 static int set_3dcursor_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
3130 {
3131         Scene *scene= CTX_data_scene(C);
3132         ARegion *ar= CTX_wm_region(C);
3133         View3D *v3d = CTX_wm_view3d(C);
3134         RegionView3D *rv3d= CTX_wm_region_view3d(C);
3135         float dx, dy, fz, *fp = NULL, dvec[3], oldcurs[3];
3136         int mval[2];
3137 //      short ctrl= 0; // XXX
3138         int flip;
3139         fp= give_cursor(scene, v3d);
3140
3141 //      if(obedit && ctrl) lr_click= 1;
3142         copy_v3_v3(oldcurs, fp);
3143
3144         project_int_noclip(ar, fp, mval);
3145         flip= initgrabz(rv3d, fp[0], fp[1], fp[2]);
3146         
3147         /* reset the depth based on the view offset */
3148         if(flip) {
3149                 negate_v3_v3(fp, rv3d->ofs);
3150
3151                 /* re initialize */
3152                 project_int_noclip(ar, fp, mval);
3153                 flip= initgrabz(rv3d, fp[0], fp[1], fp[2]);
3154         }
3155
3156         if(mval[0]!=IS_CLIPPED) {
3157                 short depth_used = 0;
3158
3159                 if (U.uiflag & USER_ORBIT_ZBUF) { /* maybe this should be accessed some other way */
3160                         view3d_operator_needs_opengl(C);
3161                         if (ED_view3d_autodist(scene, ar, v3d, event->mval, fp))
3162                                 depth_used= 1;