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