a626b71fdf8c31883d8290ae6cbc281c57374538
[blender.git] / source / blender / editors / space_view3d / view3d_view.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_view.c
28  *  \ingroup spview3d
29  */
30
31
32 #include "DNA_camera_types.h"
33 #include "DNA_scene_types.h"
34 #include "DNA_object_types.h"
35 #include "DNA_lamp_types.h"
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_math.h"
40 #include "BLI_rect.h"
41 #include "BLI_listbase.h"
42 #include "BLI_utildefines.h"
43
44 #include "BKE_anim.h"
45 #include "BKE_action.h"
46 #include "BKE_camera.h"
47 #include "BKE_context.h"
48 #include "BKE_depsgraph.h"
49 #include "BKE_object.h"
50 #include "BKE_global.h"
51 #include "BKE_main.h"
52 #include "BKE_report.h"
53 #include "BKE_scene.h"
54 #include "BKE_screen.h"
55
56 #include "BIF_gl.h"
57 #include "BIF_glutil.h"
58
59 #include "GPU_draw.h"
60
61 #include "WM_api.h"
62 #include "WM_types.h"
63
64 #include "ED_screen.h"
65 #include "ED_armature.h"
66
67 #ifdef WITH_GAMEENGINE
68 #include "BL_System.h"
69 #endif
70
71 #include "RNA_access.h"
72 #include "RNA_define.h"
73
74 #include "view3d_intern.h"  /* own include */
75
76 /* use this call when executing an operator,
77  * event system doesn't set for each event the
78  * opengl drawing context */
79 void view3d_operator_needs_opengl(const bContext *C)
80 {
81         wmWindow *win = CTX_wm_window(C);
82         ARegion *ar = CTX_wm_region(C);
83         
84         view3d_region_operator_needs_opengl(win, ar);
85 }
86
87 void view3d_region_operator_needs_opengl(wmWindow *win, ARegion *ar)
88 {
89         /* for debugging purpose, context should always be OK */
90         if ((ar == NULL) || (ar->regiontype != RGN_TYPE_WINDOW)) {
91                 printf("view3d_region_operator_needs_opengl error, wrong region\n");
92         }
93         else {
94                 RegionView3D *rv3d = ar->regiondata;
95                 
96                 wmSubWindowSet(win, ar->swinid);
97                 glMatrixMode(GL_PROJECTION);
98                 glLoadMatrixf(rv3d->winmat);
99                 glMatrixMode(GL_MODELVIEW);
100                 glLoadMatrixf(rv3d->viewmat);
101         }
102 }
103
104 float *give_cursor(Scene *scene, View3D *v3d)
105 {
106         if (v3d && v3d->localvd) return v3d->cursor;
107         else return scene->cursor;
108 }
109
110
111 /* ****************** smooth view operator ****************** */
112 /* This operator is one of the 'timer refresh' ones like animation playback */
113
114 struct SmoothView3DStore {
115         float orig_dist, new_dist;
116         float orig_lens, new_lens;
117         float orig_quat[4], new_quat[4];
118         float orig_ofs[3], new_ofs[3];
119         
120         int to_camera, orig_view;
121         
122         double time_allowed;
123 };
124
125 /* will start timer if appropriate */
126 /* the arguments are the desired situation */
127 void view3d_smooth_view(bContext *C, View3D *v3d, ARegion *ar, Object *oldcamera, Object *camera,
128                         float *ofs, float *quat, float *dist, float *lens)
129 {
130         wmWindowManager *wm = CTX_wm_manager(C);
131         wmWindow *win = CTX_wm_window(C);
132         ScrArea *sa = CTX_wm_area(C);
133
134         RegionView3D *rv3d = ar->regiondata;
135         struct SmoothView3DStore sms = {0};
136         short ok = FALSE;
137         
138         /* initialize sms */
139         copy_v3_v3(sms.new_ofs, rv3d->ofs);
140         copy_qt_qt(sms.new_quat, rv3d->viewquat);
141         sms.new_dist = rv3d->dist;
142         sms.new_lens = v3d->lens;
143         sms.to_camera = FALSE;
144
145         /* note on camera locking, this is a little confusing but works ok.
146          * we may be changing the view 'as if' there is no active camera, but in fact
147          * there is an active camera which is locked to the view.
148          *
149          * In the case where smooth view is moving _to_ a camera we don't want that
150          * camera to be moved or changed, so only when the camera is not being set should
151          * we allow camera option locking to initialize the view settings from the camera.
152          */
153         if (camera == NULL && oldcamera == NULL) {
154                 ED_view3d_camera_lock_init(v3d, rv3d);
155         }
156
157         /* store the options we want to end with */
158         if (ofs) copy_v3_v3(sms.new_ofs, ofs);
159         if (quat) copy_qt_qt(sms.new_quat, quat);
160         if (dist) sms.new_dist = *dist;
161         if (lens) sms.new_lens = *lens;
162
163         if (camera) {
164                 sms.new_dist = ED_view3d_offset_distance(camera->obmat, ofs);
165                 ED_view3d_from_object(camera, sms.new_ofs, sms.new_quat, &sms.new_dist, &sms.new_lens);
166                 sms.to_camera = TRUE; /* restore view3d values in end */
167         }
168         
169         if (C && U.smooth_viewtx) {
170                 int changed = FALSE; /* zero means no difference */
171                 
172                 if (oldcamera != camera)
173                         changed = TRUE;
174                 else if (sms.new_dist != rv3d->dist)
175                         changed = TRUE;
176                 else if (sms.new_lens != v3d->lens)
177                         changed = TRUE;
178                 else if (!equals_v3v3(sms.new_ofs, rv3d->ofs))
179                         changed = TRUE;
180                 else if (!equals_v4v4(sms.new_quat, rv3d->viewquat))
181                         changed = TRUE;
182                 
183                 /* The new view is different from the old one
184                  * so animate the view */
185                 if (changed) {
186
187                         /* original values */
188                         if (oldcamera) {
189                                 sms.orig_dist = ED_view3d_offset_distance(oldcamera->obmat, rv3d->ofs);
190                                 ED_view3d_from_object(oldcamera, sms.orig_ofs, sms.orig_quat, &sms.orig_dist, &sms.orig_lens);
191                         }
192                         else {
193                                 copy_v3_v3(sms.orig_ofs, rv3d->ofs);
194                                 copy_qt_qt(sms.orig_quat, rv3d->viewquat);
195                                 sms.orig_dist = rv3d->dist;
196                                 sms.orig_lens = v3d->lens;
197                         }
198                         /* grid draw as floor */
199                         if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
200                                 /* use existing if exists, means multiple calls to smooth view wont loose the original 'view' setting */
201                                 sms.orig_view = rv3d->sms ? rv3d->sms->orig_view : rv3d->view;
202                                 rv3d->view = RV3D_VIEW_USER;
203                         }
204
205                         sms.time_allowed = (double)U.smooth_viewtx / 1000.0;
206                         
207                         /* if this is view rotation only
208                          * we can decrease the time allowed by
209                          * the angle between quats 
210                          * this means small rotations wont lag */
211                         if (quat && !ofs && !dist) {
212                                 float vec1[3] = {0, 0, 1}, vec2[3] = {0, 0, 1};
213                                 float q1[4], q2[4];
214
215                                 invert_qt_qt(q1, sms.new_quat);
216                                 invert_qt_qt(q2, sms.orig_quat);
217
218                                 mul_qt_v3(q1, vec1);
219                                 mul_qt_v3(q2, vec2);
220
221                                 /* scale the time allowed by the rotation */
222                                 sms.time_allowed *= (double)angle_v3v3(vec1, vec2) / M_PI; /* 180deg == 1.0 */
223                         }
224
225                         /* ensure it shows correct */
226                         if (sms.to_camera) rv3d->persp = RV3D_PERSP;
227
228                         rv3d->rflag |= RV3D_NAVIGATING;
229                         
230                         /* keep track of running timer! */
231                         if (rv3d->sms == NULL)
232                                 rv3d->sms = MEM_mallocN(sizeof(struct SmoothView3DStore), "smoothview v3d");
233                         *rv3d->sms = sms;
234                         if (rv3d->smooth_timer)
235                                 WM_event_remove_timer(wm, win, rv3d->smooth_timer);
236                         /* TIMER1 is hardcoded in keymap */
237                         rv3d->smooth_timer = WM_event_add_timer(wm, win, TIMER1, 1.0 / 100.0); /* max 30 frs/sec */
238                         
239                         ok = TRUE;
240                 }
241         }
242         
243         /* if we get here nothing happens */
244         if (ok == FALSE) {
245                 if (sms.to_camera == FALSE) {
246                         copy_v3_v3(rv3d->ofs, sms.new_ofs);
247                         copy_qt_qt(rv3d->viewquat, sms.new_quat);
248                         rv3d->dist = sms.new_dist;
249                         v3d->lens = sms.new_lens;
250                 }
251
252                 ED_view3d_camera_lock_sync(v3d, rv3d);
253
254                 if (rv3d->viewlock & RV3D_BOXVIEW)
255                         view3d_boxview_copy(sa, ar);
256
257                 ED_region_tag_redraw(ar);
258         }
259 }
260
261 /* only meant for timer usage */
262 static int view3d_smoothview_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
263 {
264         View3D *v3d = CTX_wm_view3d(C);
265         RegionView3D *rv3d = CTX_wm_region_view3d(C);
266         struct SmoothView3DStore *sms = rv3d->sms;
267         float step, step_inv;
268         
269         /* escape if not our timer */
270         if (rv3d->smooth_timer == NULL || rv3d->smooth_timer != event->customdata)
271                 return OPERATOR_PASS_THROUGH;
272         
273         if (sms->time_allowed != 0.0)
274                 step = (float)((rv3d->smooth_timer->duration) / sms->time_allowed);
275         else
276                 step = 1.0f;
277         
278         /* end timer */
279         if (step >= 1.0f) {
280                 
281                 /* if we went to camera, store the original */
282                 if (sms->to_camera) {
283                         rv3d->persp = RV3D_CAMOB;
284                         copy_v3_v3(rv3d->ofs, sms->orig_ofs);
285                         copy_qt_qt(rv3d->viewquat, sms->orig_quat);
286                         rv3d->dist = sms->orig_dist;
287                         v3d->lens = sms->orig_lens;
288                 }
289                 else {
290                         copy_v3_v3(rv3d->ofs, sms->new_ofs);
291                         copy_qt_qt(rv3d->viewquat, sms->new_quat);
292                         rv3d->dist = sms->new_dist;
293                         v3d->lens = sms->new_lens;
294
295                         ED_view3d_camera_lock_sync(v3d, rv3d);
296                 }
297                 
298                 if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
299                         rv3d->view = sms->orig_view;
300                 }
301
302                 MEM_freeN(rv3d->sms);
303                 rv3d->sms = NULL;
304                 
305                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rv3d->smooth_timer);
306                 rv3d->smooth_timer = NULL;
307                 rv3d->rflag &= ~RV3D_NAVIGATING;
308         }
309         else {
310                 /* ease in/out */
311                 step = (3.0f * step * step - 2.0f * step * step * step);
312
313                 step_inv = 1.0f - step;
314
315                 interp_v3_v3v3(rv3d->ofs,      sms->orig_ofs,  sms->new_ofs,  step);
316                 interp_qt_qtqt(rv3d->viewquat, sms->orig_quat, sms->new_quat, step);
317                 
318                 rv3d->dist = sms->new_dist * step + sms->orig_dist * step_inv;
319                 v3d->lens  = sms->new_lens * step + sms->orig_lens * step_inv;
320
321                 ED_view3d_camera_lock_sync(v3d, rv3d);
322         }
323         
324         if (rv3d->viewlock & RV3D_BOXVIEW)
325                 view3d_boxview_copy(CTX_wm_area(C), CTX_wm_region(C));
326         
327         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
328         
329         return OPERATOR_FINISHED;
330 }
331
332 void VIEW3D_OT_smoothview(wmOperatorType *ot)
333 {
334         
335         /* identifiers */
336         ot->name = "Smooth View";
337         ot->idname = "VIEW3D_OT_smoothview";
338         ot->description = "The time to animate the change of view (in milliseconds)";
339         
340         /* api callbacks */
341         ot->invoke = view3d_smoothview_invoke;
342         
343         ot->poll = ED_operator_view3d_active;
344 }
345
346 /* ****************** change view operators ****************** */
347
348 static int view3d_camera_to_view_exec(bContext *C, wmOperator *UNUSED(op))
349 {
350         View3D *v3d = CTX_wm_view3d(C);
351         RegionView3D *rv3d = CTX_wm_region_view3d(C);
352         ObjectTfmProtectedChannels obtfm;
353
354         copy_qt_qt(rv3d->lviewquat, rv3d->viewquat);
355         rv3d->lview = rv3d->view;
356         if (rv3d->persp != RV3D_CAMOB) {
357                 rv3d->lpersp = rv3d->persp;
358         }
359
360         BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
361
362         ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
363
364         BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag);
365
366         DAG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
367         rv3d->persp = RV3D_CAMOB;
368         
369         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, v3d->camera);
370         
371         return OPERATOR_FINISHED;
372
373 }
374
375 static int view3d_camera_to_view_poll(bContext *C)
376 {
377         View3D *v3d = CTX_wm_view3d(C);
378         if (v3d && v3d->camera && v3d->camera->id.lib == NULL) {
379                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
380                 if (rv3d && !rv3d->viewlock) {
381                         return 1;
382                 }
383         }
384
385         return 0;
386 }
387
388 void VIEW3D_OT_camera_to_view(wmOperatorType *ot)
389 {
390         /* identifiers */
391         ot->name = "Align Camera To View";
392         ot->description = "Set camera view to active view";
393         ot->idname = "VIEW3D_OT_camera_to_view";
394         
395         /* api callbacks */
396         ot->exec = view3d_camera_to_view_exec;
397         ot->poll = view3d_camera_to_view_poll;
398         
399         /* flags */
400         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
401 }
402
403 /* unlike VIEW3D_OT_view_selected this is for framing a render and not
404  * meant to take into account vertex/bone selection for eg. */
405 static int view3d_camera_to_view_selected_exec(bContext *C, wmOperator *UNUSED(op))
406 {
407         Scene *scene = CTX_data_scene(C);
408         View3D *v3d = CTX_wm_view3d(C);
409         Object *camera_ob = v3d->camera;
410
411         float r_co[3]; /* the new location to apply */
412
413         /* this function does all the important stuff */
414         if (BKE_camera_view_frame_fit_to_scene(scene, v3d, camera_ob, r_co)) {
415
416                 ObjectTfmProtectedChannels obtfm;
417                 float obmat_new[4][4];
418
419                 copy_m4_m4(obmat_new, camera_ob->obmat);
420                 copy_v3_v3(obmat_new[3], r_co);
421
422                 /* only touch location */
423                 BKE_object_tfm_protected_backup(camera_ob, &obtfm);
424                 BKE_object_apply_mat4(camera_ob, obmat_new, TRUE, TRUE);
425                 BKE_object_tfm_protected_restore(camera_ob, &obtfm, OB_LOCK_SCALE | OB_LOCK_ROT4D);
426
427                 /* notifiers */
428                 DAG_id_tag_update(&camera_ob->id, OB_RECALC_OB);
429                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, camera_ob);
430                 return OPERATOR_FINISHED;
431         }
432         else {
433                 return OPERATOR_CANCELLED;
434         }
435 }
436
437 static int view3d_camera_to_view_selected_poll(bContext *C)
438 {
439         View3D *v3d = CTX_wm_view3d(C);
440         if (v3d && v3d->camera && v3d->camera->id.lib == NULL) {
441                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
442                 if (rv3d) {
443                         if (rv3d->is_persp == FALSE) {
444                                 CTX_wm_operator_poll_msg_set(C, "Only valid for a perspective camera view");
445                         }
446                         else if (!rv3d->viewlock) {
447                                 return 1;
448                         }
449                 }
450         }
451
452         return 0;
453 }
454
455 void VIEW3D_OT_camera_to_view_selected(wmOperatorType *ot)
456 {
457         /* identifiers */
458         ot->name = "Camera Fit Frame to Selected";
459         ot->description = "Move the camera so selected objects are framed";
460         ot->idname = "VIEW3D_OT_camera_to_view_selected";
461
462         /* api callbacks */
463         ot->exec = view3d_camera_to_view_selected_exec;
464         ot->poll = view3d_camera_to_view_selected_poll;
465
466         /* flags */
467         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
468 }
469
470
471 static int view3d_setobjectascamera_exec(bContext *C, wmOperator *UNUSED(op))
472 {       
473         View3D *v3d;
474         ARegion *ar;
475         RegionView3D *rv3d;
476
477         Scene *scene = CTX_data_scene(C);
478         Object *ob = CTX_data_active_object(C);
479
480         /* no NULL check is needed, poll checks */
481         ED_view3d_context_user_region(C, &v3d, &ar);
482         rv3d = ar->regiondata;
483
484         if (ob) {
485                 Object *camera_old = (rv3d->persp == RV3D_CAMOB) ? V3D_CAMERA_SCENE(scene, v3d) : NULL;
486                 rv3d->persp = RV3D_CAMOB;
487                 v3d->camera = ob;
488                 if (v3d->scenelock)
489                         scene->camera = ob;
490
491                 if (camera_old != ob) /* unlikely but looks like a glitch when set to the same */
492                         view3d_smooth_view(C, v3d, ar, camera_old, v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, &v3d->lens);
493
494                 WM_event_add_notifier(C, NC_SCENE | ND_RENDER_OPTIONS | NC_OBJECT | ND_DRAW, CTX_data_scene(C));
495         }
496         
497         return OPERATOR_FINISHED;
498 }
499
500 int ED_operator_rv3d_user_region_poll(bContext *C)
501 {
502         View3D *v3d_dummy;
503         ARegion *ar_dummy;
504
505         return ED_view3d_context_user_region(C, &v3d_dummy, &ar_dummy);
506 }
507
508 void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
509 {
510         
511         /* identifiers */
512         ot->name = "Set Active Object as Camera";
513         ot->description = "Set the active object as the active camera for this view or scene";
514         ot->idname = "VIEW3D_OT_object_as_camera";
515         
516         /* api callbacks */
517         ot->exec = view3d_setobjectascamera_exec;
518         ot->poll = ED_operator_rv3d_user_region_poll;
519         
520         /* flags */
521         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
522 }
523
524 /* ********************************** */
525
526 void ED_view3d_clipping_calc(BoundBox *bb, float planes[4][4], bglMats *mats, const rcti *rect)
527 {
528         float modelview[4][4];
529         double xs, ys, p[3];
530         int val, flip_sign, a;
531
532         /* near zero floating point values can give issues with gluUnProject
533          * in side view on some implementations */
534         if (fabs(mats->modelview[0]) < 1e-6) mats->modelview[0] = 0.0;
535         if (fabs(mats->modelview[5]) < 1e-6) mats->modelview[5] = 0.0;
536
537         /* Set up viewport so that gluUnProject will give correct values */
538         mats->viewport[0] = 0;
539         mats->viewport[1] = 0;
540
541         /* four clipping planes and bounding volume */
542         /* first do the bounding volume */
543         for (val = 0; val < 4; val++) {
544                 xs = (val == 0 || val == 3) ? rect->xmin : rect->xmax;
545                 ys = (val == 0 || val == 1) ? rect->ymin : rect->ymax;
546
547                 gluUnProject(xs, ys, 0.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
548                 copy_v3fl_v3db(bb->vec[val], p);
549
550                 gluUnProject(xs, ys, 1.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
551                 copy_v3fl_v3db(bb->vec[4 + val], p);
552         }
553
554         /* verify if we have negative scale. doing the transform before cross
555          * product flips the sign of the vector compared to doing cross product
556          * before transform then, so we correct for that. */
557         for (a = 0; a < 16; a++)
558                 ((float *)modelview)[a] = mats->modelview[a];
559         flip_sign = is_negative_m4(modelview);
560
561         /* then plane equations */
562         for (val = 0; val < 4; val++) {
563
564                 normal_tri_v3(planes[val], bb->vec[val], bb->vec[val == 3 ? 0 : val + 1], bb->vec[val + 4]);
565
566                 if (flip_sign)
567                         negate_v3(planes[val]);
568
569                 planes[val][3] = -planes[val][0] * bb->vec[val][0] -
570                                   planes[val][1] * bb->vec[val][1] -
571                                   planes[val][2] * bb->vec[val][2];
572         }
573 }
574
575
576 int ED_view3d_boundbox_clip(RegionView3D *rv3d, float obmat[][4], BoundBox *bb)
577 {
578         /* return 1: draw */
579
580         float mat[4][4];
581         float vec[4], min, max;
582         int a, flag = -1, fl;
583
584         if (bb == NULL) return 1;
585         if (bb->flag & OB_BB_DISABLED) return 1;
586
587         mult_m4_m4m4(mat, rv3d->persmat, obmat);
588
589         for (a = 0; a < 8; a++) {
590                 copy_v3_v3(vec, bb->vec[a]);
591                 vec[3] = 1.0;
592                 mul_m4_v4(mat, vec);
593                 max = vec[3];
594                 min = -vec[3];
595
596                 fl = 0;
597                 if (vec[0] < min) fl += 1;
598                 if (vec[0] > max) fl += 2;
599                 if (vec[1] < min) fl += 4;
600                 if (vec[1] > max) fl += 8;
601                 if (vec[2] < min) fl += 16;
602                 if (vec[2] > max) fl += 32;
603
604                 flag &= fl;
605                 if (flag == 0) return 1;
606         }
607
608         return 0;
609 }
610
611 float ED_view3d_depth_read_cached(ViewContext *vc, int x, int y)
612 {
613         ViewDepths *vd = vc->rv3d->depths;
614                 
615         x -= vc->ar->winrct.xmin;
616         y -= vc->ar->winrct.ymin;
617
618         if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h)
619                 return vd->depths[y * vd->w + x];
620         else
621                 return 1;
622 }
623
624 void ED_view3d_depth_tag_update(RegionView3D *rv3d)
625 {
626         if (rv3d->depths)
627                 rv3d->depths->damaged = 1;
628 }
629
630 /* copies logic of get_view3d_viewplane(), keep in sync */
631 int ED_view3d_clip_range_get(View3D *v3d, RegionView3D *rv3d, float *clipsta, float *clipend)
632 {
633         CameraParams params;
634
635         BKE_camera_params_init(&params);
636         BKE_camera_params_from_view3d(&params, v3d, rv3d);
637
638         if (clipsta) *clipsta = params.clipsta;
639         if (clipend) *clipend = params.clipend;
640
641         return params.is_ortho;
642 }
643
644 /* also exposed in previewrender.c */
645 int ED_view3d_viewplane_get(View3D *v3d, RegionView3D *rv3d, int winx, int winy,
646                             rctf *viewplane, float *clipsta, float *clipend)
647 {
648         CameraParams params;
649
650         BKE_camera_params_init(&params);
651         BKE_camera_params_from_view3d(&params, v3d, rv3d);
652         BKE_camera_params_compute_viewplane(&params, winx, winy, 1.0f, 1.0f);
653
654         if (viewplane) *viewplane = params.viewplane;
655         if (clipsta) *clipsta = params.clipsta;
656         if (clipend) *clipend = params.clipend;
657         
658         return params.is_ortho;
659 }
660
661 void setwinmatrixview3d(ARegion *ar, View3D *v3d, rctf *rect)       /* rect: for picking */
662 {
663         RegionView3D *rv3d = ar->regiondata;
664         rctf viewplane;
665         float clipsta, clipend, x1, y1, x2, y2;
666         int orth;
667         
668         orth = ED_view3d_viewplane_get(v3d, rv3d, ar->winx, ar->winy, &viewplane, &clipsta, &clipend);
669         rv3d->is_persp = !orth;
670
671 #if 0
672         printf("%s: %d %d %f %f %f %f %f %f\n", __func__, winx, winy,
673                viewplane.xmin, viewplane.ymin, viewplane.xmax, viewplane.ymax,
674                clipsta, clipend);
675 #endif
676
677         x1 = viewplane.xmin;
678         y1 = viewplane.ymin;
679         x2 = viewplane.xmax;
680         y2 = viewplane.ymax;
681
682         if (rect) {  /* picking */
683                 rect->xmin /= (float)ar->winx;
684                 rect->xmin = x1 + rect->xmin * (x2 - x1);
685                 rect->ymin /= (float)ar->winy;
686                 rect->ymin = y1 + rect->ymin * (y2 - y1);
687                 rect->xmax /= (float)ar->winx;
688                 rect->xmax = x1 + rect->xmax * (x2 - x1);
689                 rect->ymax /= (float)ar->winy;
690                 rect->ymax = y1 + rect->ymax * (y2 - y1);
691                 
692                 if (orth) wmOrtho(rect->xmin, rect->xmax, rect->ymin, rect->ymax, -clipend, clipend);
693                 else wmFrustum(rect->xmin, rect->xmax, rect->ymin, rect->ymax, clipsta, clipend);
694                 
695         }
696         else {
697                 if (orth) wmOrtho(x1, x2, y1, y2, clipsta, clipend);
698                 else wmFrustum(x1, x2, y1, y2, clipsta, clipend);
699         }
700
701         /* update matrix in 3d view region */
702         glGetFloatv(GL_PROJECTION_MATRIX, (float *)rv3d->winmat);
703 }
704
705 static void obmat_to_viewmat(View3D *v3d, RegionView3D *rv3d, Object *ob, short smooth)
706 {
707         float bmat[4][4];
708         float tmat[3][3];
709         
710         rv3d->view = RV3D_VIEW_USER; /* don't show the grid */
711         
712         copy_m4_m4(bmat, ob->obmat);
713         normalize_m4(bmat);
714         invert_m4_m4(rv3d->viewmat, bmat);
715         
716         /* view quat calculation, needed for add object */
717         copy_m3_m4(tmat, rv3d->viewmat);
718         if (smooth) {
719                 float new_quat[4];
720                 if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
721                         /* were from a camera view */
722                         
723                         float orig_ofs[3];
724                         float orig_dist = rv3d->dist;
725                         float orig_lens = v3d->lens;
726                         copy_v3_v3(orig_ofs, rv3d->ofs);
727                         
728                         /* Switch from camera view */
729                         mat3_to_quat(new_quat, tmat);
730                         
731                         rv3d->persp = RV3D_PERSP;
732                         rv3d->dist = 0.0;
733                         
734                         ED_view3d_from_object(v3d->camera, rv3d->ofs, NULL, NULL, &v3d->lens);
735                         view3d_smooth_view(NULL, NULL, NULL, NULL, NULL, orig_ofs, new_quat, &orig_dist, &orig_lens); /* XXX */
736
737                         rv3d->persp = RV3D_CAMOB; /* just to be polite, not needed */
738                         
739                 }
740                 else {
741                         mat3_to_quat(new_quat, tmat);
742                         view3d_smooth_view(NULL, NULL, NULL, NULL, NULL, NULL, new_quat, NULL, NULL); /* XXX */
743                 }
744         }
745         else {
746                 mat3_to_quat(rv3d->viewquat, tmat);
747         }
748 }
749
750 #define QUATSET(a, b, c, d, e) { a[0] = b; a[1] = c; a[2] = d; a[3] = e; } (void)0
751
752 int ED_view3d_lock(RegionView3D *rv3d)
753 {
754         switch (rv3d->view) {
755                 case RV3D_VIEW_BOTTOM:
756                         QUATSET(rv3d->viewquat, 0.0, -1.0, 0.0, 0.0);
757                         break;
758
759                 case RV3D_VIEW_BACK:
760                         QUATSET(rv3d->viewquat, 0.0, 0.0, -M_SQRT1_2, -M_SQRT1_2);
761                         break;
762
763                 case RV3D_VIEW_LEFT:
764                         QUATSET(rv3d->viewquat, 0.5, -0.5, 0.5, 0.5);
765                         break;
766
767                 case RV3D_VIEW_TOP:
768                         QUATSET(rv3d->viewquat, 1.0, 0.0, 0.0, 0.0);
769                         break;
770
771                 case RV3D_VIEW_FRONT:
772                         QUATSET(rv3d->viewquat, M_SQRT1_2, -M_SQRT1_2, 0.0, 0.0);
773                         break;
774
775                 case RV3D_VIEW_RIGHT:
776                         QUATSET(rv3d->viewquat, 0.5, -0.5, -0.5, -0.5);
777                         break;
778                 default:
779                         return FALSE;
780         }
781
782         return TRUE;
783 }
784
785 /* don't set windows active in here, is used by renderwin too */
786 void setviewmatrixview3d(Scene *scene, View3D *v3d, RegionView3D *rv3d)
787 {
788         if (rv3d->persp == RV3D_CAMOB) {      /* obs/camera */
789                 if (v3d->camera) {
790                         BKE_object_where_is_calc(scene, v3d->camera);
791                         obmat_to_viewmat(v3d, rv3d, v3d->camera, 0);
792                 }
793                 else {
794                         quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
795                         rv3d->viewmat[3][2] -= rv3d->dist;
796                 }
797         }
798         else {
799                 /* should be moved to better initialize later on XXX */
800                 if (rv3d->viewlock)
801                         ED_view3d_lock(rv3d);
802                 
803                 quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
804                 if (rv3d->persp == RV3D_PERSP) rv3d->viewmat[3][2] -= rv3d->dist;
805                 if (v3d->ob_centre) {
806                         Object *ob = v3d->ob_centre;
807                         float vec[3];
808                         
809                         copy_v3_v3(vec, ob->obmat[3]);
810                         if (ob->type == OB_ARMATURE && v3d->ob_centre_bone[0]) {
811                                 bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, v3d->ob_centre_bone);
812                                 if (pchan) {
813                                         copy_v3_v3(vec, pchan->pose_mat[3]);
814                                         mul_m4_v3(ob->obmat, vec);
815                                 }
816                         }
817                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
818                 }
819                 else if (v3d->ob_centre_cursor) {
820                         float vec[3];
821                         copy_v3_v3(vec, give_cursor(scene, v3d));
822                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
823                 }
824                 else translate_m4(rv3d->viewmat, rv3d->ofs[0], rv3d->ofs[1], rv3d->ofs[2]);
825         }
826 }
827
828 /* IGLuint-> GLuint */
829 /* Warning: be sure to account for a negative return value
830  *   This is an error, "Too many objects in select buffer"
831  *   and no action should be taken (can crash blender) if this happens
832  */
833 short view3d_opengl_select(ViewContext *vc, unsigned int *buffer, unsigned int bufsize, rcti *input)
834 {
835         Scene *scene = vc->scene;
836         View3D *v3d = vc->v3d;
837         ARegion *ar = vc->ar;
838         rctf rect;
839         short code, hits;
840         char dt, dtx;
841         
842         G.f |= G_PICKSEL;
843         
844         /* case not a border select */
845         if (input->xmin == input->xmax) {
846                 rect.xmin = input->xmin - 12;  /* seems to be default value for bones only now */
847                 rect.xmax = input->xmin + 12;
848                 rect.ymin = input->ymin - 12;
849                 rect.ymax = input->ymin + 12;
850         }
851         else {
852                 BLI_rctf_rcti_copy(&rect, input);
853         }
854         
855         setwinmatrixview3d(ar, v3d, &rect);
856         mult_m4_m4m4(vc->rv3d->persmat, vc->rv3d->winmat, vc->rv3d->viewmat);
857         
858         if (v3d->drawtype > OB_WIRE) {
859                 v3d->zbuf = TRUE;
860                 glEnable(GL_DEPTH_TEST);
861         }
862         
863         if (vc->rv3d->rflag & RV3D_CLIPPING)
864                 ED_view3d_clipping_set(vc->rv3d);
865         
866         glSelectBuffer(bufsize, (GLuint *)buffer);
867         glRenderMode(GL_SELECT);
868         glInitNames();  /* these two calls whatfor? It doesnt work otherwise */
869         glPushName(-1);
870         code = 1;
871         
872         if (vc->obedit && vc->obedit->type == OB_MBALL) {
873                 draw_object(scene, ar, v3d, BASACT, DRAW_PICKING | DRAW_CONSTCOLOR);
874         }
875         else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
876                 /* if not drawing sketch, draw bones */
877                 if (!BDR_drawSketchNames(vc)) {
878                         draw_object(scene, ar, v3d, BASACT, DRAW_PICKING | DRAW_CONSTCOLOR);
879                 }
880         }
881         else {
882                 Base *base;
883                 
884                 v3d->xray = TRUE;  /* otherwise it postpones drawing */
885                 for (base = scene->base.first; base; base = base->next) {
886                         if (base->lay & v3d->lay) {
887                                 
888                                 if (base->object->restrictflag & OB_RESTRICT_SELECT)
889                                         base->selcol = 0;
890                                 else {
891                                         base->selcol = code;
892                                         glLoadName(code);
893                                         draw_object(scene, ar, v3d, base, DRAW_PICKING | DRAW_CONSTCOLOR);
894                                         
895                                         /* we draw duplicators for selection too */
896                                         if ((base->object->transflag & OB_DUPLI)) {
897                                                 ListBase *lb;
898                                                 DupliObject *dob;
899                                                 Base tbase;
900                                                 
901                                                 tbase.flag = OB_FROMDUPLI;
902                                                 lb = object_duplilist(scene, base->object, FALSE);
903                                                 
904                                                 for (dob = lb->first; dob; dob = dob->next) {
905                                                         tbase.object = dob->ob;
906                                                         copy_m4_m4(dob->ob->obmat, dob->mat);
907                                                         
908                                                         /* extra service: draw the duplicator in drawtype of parent */
909                                                         /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
910                                                         dt = tbase.object->dt;   tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
911                                                         dtx = tbase.object->dtx; tbase.object->dtx = base->object->dtx;
912
913                                                         draw_object(scene, ar, v3d, &tbase, DRAW_PICKING | DRAW_CONSTCOLOR);
914                                                         
915                                                         tbase.object->dt = dt;
916                                                         tbase.object->dtx = dtx;
917
918                                                         copy_m4_m4(dob->ob->obmat, dob->omat);
919                                                 }
920                                                 free_object_duplilist(lb);
921                                         }
922                                         code++;
923                                 }
924                         }
925                 }
926                 v3d->xray = FALSE;  /* restore */
927         }
928         
929         glPopName();    /* see above (pushname) */
930         hits = glRenderMode(GL_RENDER);
931         
932         G.f &= ~G_PICKSEL;
933         setwinmatrixview3d(ar, v3d, NULL);
934         mult_m4_m4m4(vc->rv3d->persmat, vc->rv3d->winmat, vc->rv3d->viewmat);
935         
936         if (v3d->drawtype > OB_WIRE) {
937                 v3d->zbuf = 0;
938                 glDisable(GL_DEPTH_TEST);
939         }
940 // XXX  persp(PERSP_WIN);
941         
942         if (vc->rv3d->rflag & RV3D_CLIPPING)
943                 ED_view3d_clipping_disable();
944         
945         if (hits < 0) printf("Too many objects in select buffer\n");  /* XXX make error message */
946
947         return hits;
948 }
949
950 /* ********************** local view operator ******************** */
951
952 static unsigned int free_localbit(Main *bmain)
953 {
954         unsigned int lay;
955         ScrArea *sa;
956         bScreen *sc;
957         
958         lay = 0;
959         
960         /* sometimes we loose a localview: when an area is closed */
961         /* check all areas: which localviews are in use? */
962         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
963                 for (sa = sc->areabase.first; sa; sa = sa->next) {
964                         SpaceLink *sl = sa->spacedata.first;
965                         for (; sl; sl = sl->next) {
966                                 if (sl->spacetype == SPACE_VIEW3D) {
967                                         View3D *v3d = (View3D *) sl;
968                                         lay |= v3d->lay;
969                                 }
970                         }
971                 }
972         }
973         
974         if ((lay & 0x01000000) == 0) return 0x01000000;
975         if ((lay & 0x02000000) == 0) return 0x02000000;
976         if ((lay & 0x04000000) == 0) return 0x04000000;
977         if ((lay & 0x08000000) == 0) return 0x08000000;
978         if ((lay & 0x10000000) == 0) return 0x10000000;
979         if ((lay & 0x20000000) == 0) return 0x20000000;
980         if ((lay & 0x40000000) == 0) return 0x40000000;
981         if ((lay & 0x80000000) == 0) return 0x80000000;
982         
983         return 0;
984 }
985
986 int ED_view3d_scene_layer_set(int lay, const int *values, int *active)
987 {
988         int i, tot = 0;
989         
990         /* ensure we always have some layer selected */
991         for (i = 0; i < 20; i++)
992                 if (values[i])
993                         tot++;
994         
995         if (tot == 0)
996                 return lay;
997         
998         for (i = 0; i < 20; i++) {
999                 
1000                 if (active) {
1001                         /* if this value has just been switched on, make that layer active */
1002                         if (values[i] && (lay & (1 << i)) == 0) {
1003                                 *active = (1 << i);
1004                         }
1005                 }
1006                         
1007                 if (values[i]) lay |= (1 << i);
1008                 else lay &= ~(1 << i);
1009         }
1010         
1011         /* ensure always an active layer */
1012         if (active && (lay & *active) == 0) {
1013                 for (i = 0; i < 20; i++) {
1014                         if (lay & (1 << i)) {
1015                                 *active = 1 << i;
1016                                 break;
1017                         }
1018                 }
1019         }
1020         
1021         return lay;
1022 }
1023
1024 static int view3d_localview_init(Main *bmain, Scene *scene, ScrArea *sa, ReportList *reports)
1025 {
1026         View3D *v3d = sa->spacedata.first;
1027         Base *base;
1028         float size = 0.0, min[3], max[3], box[3];
1029         unsigned int locallay;
1030         int ok = FALSE;
1031
1032         if (v3d->localvd) {
1033                 return ok;
1034         }
1035
1036         INIT_MINMAX(min, max);
1037
1038         locallay = free_localbit(bmain);
1039
1040         if (locallay == 0) {
1041                 BKE_reportf(reports, RPT_ERROR, "No more than 8 local views");
1042                 ok = FALSE;
1043         }
1044         else {
1045                 if (scene->obedit) {
1046                         BKE_object_minmax(scene->obedit, min, max, FALSE);
1047                         
1048                         ok = TRUE;
1049                 
1050                         BASACT->lay |= locallay;
1051                         scene->obedit->lay = BASACT->lay;
1052                 }
1053                 else {
1054                         for (base = FIRSTBASE; base; base = base->next) {
1055                                 if (TESTBASE(v3d, base)) {
1056                                         BKE_object_minmax(base->object, min, max, FALSE);
1057                                         base->lay |= locallay;
1058                                         base->object->lay = base->lay;
1059                                         ok = TRUE;
1060                                 }
1061                         }
1062                 }
1063                 
1064                 box[0] = (max[0] - min[0]);
1065                 box[1] = (max[1] - min[1]);
1066                 box[2] = (max[2] - min[2]);
1067                 size = MAX3(box[0], box[1], box[2]);
1068                 if (size <= 0.01f) size = 0.01f;
1069         }
1070         
1071         if (ok == TRUE) {
1072                 ARegion *ar;
1073                 
1074                 v3d->localvd = MEM_mallocN(sizeof(View3D), "localview");
1075                 
1076                 memcpy(v3d->localvd, v3d, sizeof(View3D));
1077
1078                 for (ar = sa->regionbase.first; ar; ar = ar->next) {
1079                         if (ar->regiontype == RGN_TYPE_WINDOW) {
1080                                 RegionView3D *rv3d = ar->regiondata;
1081
1082                                 rv3d->localvd = MEM_mallocN(sizeof(RegionView3D), "localview region");
1083                                 memcpy(rv3d->localvd, rv3d, sizeof(RegionView3D));
1084                                 
1085                                 rv3d->ofs[0] = -(min[0] + max[0]) / 2.0f;
1086                                 rv3d->ofs[1] = -(min[1] + max[1]) / 2.0f;
1087                                 rv3d->ofs[2] = -(min[2] + max[2]) / 2.0f;
1088
1089                                 rv3d->dist = size;
1090                                 /* perspective should be a bit farther away to look nice */
1091                                 if (rv3d->persp == RV3D_ORTHO)
1092                                         rv3d->dist *= 0.7f;
1093
1094                                 /* correction for window aspect ratio */
1095                                 if (ar->winy > 2 && ar->winx > 2) {
1096                                         float asp = (float)ar->winx / (float)ar->winy;
1097                                         if (asp < 1.0f) asp = 1.0f / asp;
1098                                         rv3d->dist *= asp;
1099                                 }
1100                                 
1101                                 if (rv3d->persp == RV3D_CAMOB) rv3d->persp = RV3D_PERSP;
1102                                 
1103                                 v3d->cursor[0] = -rv3d->ofs[0];
1104                                 v3d->cursor[1] = -rv3d->ofs[1];
1105                                 v3d->cursor[2] = -rv3d->ofs[2];
1106                         }
1107                 }
1108                 
1109                 v3d->lay = locallay;
1110         }
1111         else {
1112                 /* clear flags */ 
1113                 for (base = FIRSTBASE; base; base = base->next) {
1114                         if (base->lay & locallay) {
1115                                 base->lay -= locallay;
1116                                 if (base->lay == 0) base->lay = v3d->layact;
1117                                 if (base->object != scene->obedit) base->flag |= SELECT;
1118                                 base->object->lay = base->lay;
1119                         }
1120                 }
1121         }
1122
1123         return ok;
1124 }
1125
1126 static void restore_localviewdata(ScrArea *sa, int free)
1127 {
1128         ARegion *ar;
1129         View3D *v3d = sa->spacedata.first;
1130         
1131         if (v3d->localvd == NULL) return;
1132         
1133         v3d->near = v3d->localvd->near;
1134         v3d->far = v3d->localvd->far;
1135         v3d->lay = v3d->localvd->lay;
1136         v3d->layact = v3d->localvd->layact;
1137         v3d->drawtype = v3d->localvd->drawtype;
1138         v3d->camera = v3d->localvd->camera;
1139         
1140         if (free) {
1141                 MEM_freeN(v3d->localvd);
1142                 v3d->localvd = NULL;
1143         }
1144         
1145         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1146                 if (ar->regiontype == RGN_TYPE_WINDOW) {
1147                         RegionView3D *rv3d = ar->regiondata;
1148                         
1149                         if (rv3d->localvd) {
1150                                 rv3d->dist = rv3d->localvd->dist;
1151                                 copy_v3_v3(rv3d->ofs, rv3d->localvd->ofs);
1152                                 copy_qt_qt(rv3d->viewquat, rv3d->localvd->viewquat);
1153                                 rv3d->view = rv3d->localvd->view;
1154                                 rv3d->persp = rv3d->localvd->persp;
1155                                 rv3d->camzoom = rv3d->localvd->camzoom;
1156
1157                                 if (free) {
1158                                         MEM_freeN(rv3d->localvd);
1159                                         rv3d->localvd = NULL;
1160                                 }
1161                         }
1162                 }
1163         }
1164 }
1165
1166 static int view3d_localview_exit(Main *bmain, Scene *scene, ScrArea *sa)
1167 {
1168         View3D *v3d = sa->spacedata.first;
1169         struct Base *base;
1170         unsigned int locallay;
1171         
1172         if (v3d->localvd) {
1173                 
1174                 locallay = v3d->lay & 0xFF000000;
1175                 
1176                 restore_localviewdata(sa, 1); /* 1 = free */
1177
1178                 /* for when in other window the layers have changed */
1179                 if (v3d->scenelock) v3d->lay = scene->lay;
1180                 
1181                 for (base = FIRSTBASE; base; base = base->next) {
1182                         if (base->lay & locallay) {
1183                                 base->lay -= locallay;
1184                                 if (base->lay == 0) base->lay = v3d->layact;
1185                                 if (base->object != scene->obedit) {
1186                                         base->flag |= SELECT;
1187                                         base->object->flag |= SELECT;
1188                                 }
1189                                 base->object->lay = base->lay;
1190                         }
1191                 }
1192                 
1193                 DAG_on_visible_update(bmain, FALSE);
1194
1195                 return TRUE;
1196         }
1197         else {
1198                 return FALSE;
1199         }
1200 }
1201
1202 static int localview_exec(bContext *C, wmOperator *op)
1203 {
1204         Main *bmain = CTX_data_main(C);
1205         Scene *scene = CTX_data_scene(C);
1206         ScrArea *sa = CTX_wm_area(C);
1207         View3D *v3d = CTX_wm_view3d(C);
1208         int change;
1209         
1210         if (v3d->localvd) {
1211                 change = view3d_localview_exit(bmain, scene, sa);
1212         }
1213         else {
1214                 change = view3d_localview_init(bmain, scene, sa, op->reports);
1215         }
1216
1217         if (change) {
1218                 DAG_id_type_tag(bmain, ID_OB);
1219                 ED_area_tag_redraw(CTX_wm_area(C));
1220
1221                 return OPERATOR_FINISHED;
1222         }
1223         else {
1224                 return OPERATOR_CANCELLED;
1225         }
1226 }
1227
1228 void VIEW3D_OT_localview(wmOperatorType *ot)
1229 {
1230         /* identifiers */
1231         ot->name = "Local View";
1232         ot->description = "Toggle display of selected object(s) separately and centered in view";
1233         ot->idname = "VIEW3D_OT_localview";
1234         
1235         /* api callbacks */
1236         ot->exec = localview_exec;
1237         ot->flag = OPTYPE_UNDO; /* localview changes object layer bitflags */
1238         
1239         ot->poll = ED_operator_view3d_active;
1240 }
1241
1242 #ifdef WITH_GAMEENGINE
1243
1244 static ListBase queue_back;
1245 static void SaveState(bContext *C, wmWindow *win)
1246 {
1247         Object *obact = CTX_data_active_object(C);
1248         
1249         glPushAttrib(GL_ALL_ATTRIB_BITS);
1250
1251         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1252                 GPU_paint_set_mipmap(1);
1253         
1254         queue_back = win->queue;
1255         
1256         win->queue.first = win->queue.last = NULL;
1257         
1258         //XXX waitcursor(1);
1259 }
1260
1261 static void RestoreState(bContext *C, wmWindow *win)
1262 {
1263         Object *obact = CTX_data_active_object(C);
1264         
1265         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1266                 GPU_paint_set_mipmap(0);
1267
1268         //XXX curarea->win_swap = 0;
1269         //XXX curarea->head_swap = 0;
1270         //XXX allqueue(REDRAWVIEW3D, 1);
1271         //XXX allqueue(REDRAWBUTSALL, 0);
1272         //XXX reset_slowparents();
1273         //XXX waitcursor(0);
1274         //XXX G.qual = 0;
1275         
1276         if (win) /* check because closing win can set to NULL */
1277                 win->queue = queue_back;
1278         
1279         GPU_state_init();
1280         GPU_set_tpage(NULL, 0, 0);
1281
1282         glPopAttrib();
1283 }
1284
1285 /* was space_set_commmandline_options in 2.4x */
1286 static void game_set_commmandline_options(GameData *gm)
1287 {
1288         SYS_SystemHandle syshandle;
1289         int test;
1290
1291         if ((syshandle = SYS_GetSystem())) {
1292                 /* User defined settings */
1293                 test = (U.gameflags & USER_DISABLE_MIPMAP);
1294                 GPU_set_mipmap(!test);
1295                 SYS_WriteCommandLineInt(syshandle, "nomipmap", test);
1296
1297                 /* File specific settings: */
1298                 /* Only test the first one. These two are switched
1299                  * simultaneously. */
1300                 test = (gm->flag & GAME_SHOW_FRAMERATE);
1301                 SYS_WriteCommandLineInt(syshandle, "show_framerate", test);
1302                 SYS_WriteCommandLineInt(syshandle, "show_profile", test);
1303
1304                 test = (gm->flag & GAME_SHOW_DEBUG_PROPS);
1305                 SYS_WriteCommandLineInt(syshandle, "show_properties", test);
1306
1307                 test = (gm->flag & GAME_SHOW_PHYSICS);
1308                 SYS_WriteCommandLineInt(syshandle, "show_physics", test);
1309
1310                 test = (gm->flag & GAME_ENABLE_ALL_FRAMES);
1311                 SYS_WriteCommandLineInt(syshandle, "fixedtime", test);
1312
1313                 test = (gm->flag & GAME_ENABLE_ANIMATION_RECORD);
1314                 SYS_WriteCommandLineInt(syshandle, "animation_record", test);
1315
1316                 test = (gm->flag & GAME_IGNORE_DEPRECATION_WARNINGS);
1317                 SYS_WriteCommandLineInt(syshandle, "ignore_deprecation_warnings", test);
1318
1319                 test = (gm->matmode == GAME_MAT_MULTITEX);
1320                 SYS_WriteCommandLineInt(syshandle, "blender_material", test);
1321                 test = (gm->matmode == GAME_MAT_GLSL);
1322                 SYS_WriteCommandLineInt(syshandle, "blender_glsl_material", test);
1323                 test = (gm->flag & GAME_DISPLAY_LISTS);
1324                 SYS_WriteCommandLineInt(syshandle, "displaylists", test);
1325
1326
1327         }
1328 }
1329
1330 #endif /* WITH_GAMEENGINE */
1331
1332 static int game_engine_poll(bContext *C)
1333 {
1334         /* we need a context and area to launch BGE
1335          * it's a temporary solution to avoid crash at load time
1336          * if we try to auto run the BGE. Ideally we want the
1337          * context to be set as soon as we load the file. */
1338
1339         if (CTX_wm_window(C) == NULL) return 0;
1340         if (CTX_wm_screen(C) == NULL) return 0;
1341         if (CTX_wm_area(C) == NULL) return 0;
1342
1343         if (CTX_data_mode_enum(C) != CTX_MODE_OBJECT)
1344                 return 0;
1345
1346         return 1;
1347 }
1348
1349 int ED_view3d_context_activate(bContext *C)
1350 {
1351         bScreen *sc = CTX_wm_screen(C);
1352         ScrArea *sa = CTX_wm_area(C);
1353         ARegion *ar;
1354
1355         /* sa can be NULL when called from python */
1356         if (sa == NULL || sa->spacetype != SPACE_VIEW3D)
1357                 for (sa = sc->areabase.first; sa; sa = sa->next)
1358                         if (sa->spacetype == SPACE_VIEW3D)
1359                                 break;
1360
1361         if (!sa)
1362                 return 0;
1363         
1364         for (ar = sa->regionbase.first; ar; ar = ar->next)
1365                 if (ar->regiontype == RGN_TYPE_WINDOW)
1366                         break;
1367         
1368         if (!ar)
1369                 return 0;
1370         
1371         /* bad context switch .. */
1372         CTX_wm_area_set(C, sa);
1373         CTX_wm_region_set(C, ar);
1374
1375         return 1;
1376 }
1377
1378 static int game_engine_exec(bContext *C, wmOperator *op)
1379 {
1380 #ifdef WITH_GAMEENGINE
1381         Scene *startscene = CTX_data_scene(C);
1382         ScrArea /* *sa, */ /* UNUSED */ *prevsa = CTX_wm_area(C);
1383         ARegion *ar, *prevar = CTX_wm_region(C);
1384         wmWindow *prevwin = CTX_wm_window(C);
1385         RegionView3D *rv3d;
1386         rcti cam_frame;
1387
1388         (void)op; /* unused */
1389         
1390         /* bad context switch .. */
1391         if (!ED_view3d_context_activate(C))
1392                 return OPERATOR_CANCELLED;
1393         
1394         /* redraw to hide any menus/popups, we don't go back to
1395          * the window manager until after this operator exits */
1396         WM_redraw_windows(C);
1397
1398         rv3d = CTX_wm_region_view3d(C);
1399         /* sa = CTX_wm_area(C); */ /* UNUSED */
1400         ar = CTX_wm_region(C);
1401
1402         view3d_operator_needs_opengl(C);
1403         
1404         game_set_commmandline_options(&startscene->gm);
1405
1406         if ((rv3d->persp == RV3D_CAMOB) &&
1407             (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) &&
1408             (startscene->gm.stereoflag != STEREO_DOME))
1409         {
1410                 /* Letterbox */
1411                 rctf cam_framef;
1412                 ED_view3d_calc_camera_border(startscene, ar, CTX_wm_view3d(C), rv3d, &cam_framef, FALSE);
1413                 cam_frame.xmin = cam_framef.xmin + ar->winrct.xmin;
1414                 cam_frame.xmax = cam_framef.xmax + ar->winrct.xmin;
1415                 cam_frame.ymin = cam_framef.ymin + ar->winrct.ymin;
1416                 cam_frame.ymax = cam_framef.ymax + ar->winrct.ymin;
1417                 BLI_rcti_isect(&ar->winrct, &cam_frame, &cam_frame);
1418         }
1419         else {
1420                 cam_frame.xmin = ar->winrct.xmin;
1421                 cam_frame.xmax = ar->winrct.xmax;
1422                 cam_frame.ymin = ar->winrct.ymin;
1423                 cam_frame.ymax = ar->winrct.ymax;
1424         }
1425
1426
1427         SaveState(C, prevwin);
1428
1429         StartKetsjiShell(C, ar, &cam_frame, 1);
1430
1431         /* window wasnt closed while the BGE was running */
1432         if (BLI_findindex(&CTX_wm_manager(C)->windows, prevwin) == -1) {
1433                 prevwin = NULL;
1434                 CTX_wm_window_set(C, NULL);
1435         }
1436         
1437         ED_area_tag_redraw(CTX_wm_area(C));
1438
1439         if (prevwin) {
1440                 /* restore context, in case it changed in the meantime, for
1441                  * example by working in another window or closing it */
1442                 CTX_wm_region_set(C, prevar);
1443                 CTX_wm_window_set(C, prevwin);
1444                 CTX_wm_area_set(C, prevsa);
1445         }
1446
1447         RestoreState(C, prevwin);
1448
1449         //XXX restore_all_scene_cfra(scene_cfra_store);
1450         BKE_scene_set_background(CTX_data_main(C), startscene);
1451         //XXX BKE_scene_update_for_newframe(bmain, scene, scene->lay);
1452
1453         return OPERATOR_FINISHED;
1454 #else
1455         (void)C; /* unused */
1456         BKE_report(op->reports, RPT_ERROR, "Game engine is disabled in this build");
1457         return OPERATOR_CANCELLED;
1458 #endif
1459 }
1460
1461 void VIEW3D_OT_game_start(wmOperatorType *ot)
1462 {
1463         
1464         /* identifiers */
1465         ot->name = "Start Game Engine";
1466         ot->description = "Start game engine";
1467         ot->idname = "VIEW3D_OT_game_start";
1468         
1469         /* api callbacks */
1470         ot->exec = game_engine_exec;
1471         
1472         ot->poll = game_engine_poll;
1473 }
1474
1475 /* ************************************** */
1476
1477 static void UNUSED_FUNCTION(view3d_align_axis_to_vector)(View3D *v3d, RegionView3D *rv3d, int axisidx, float vec[3])
1478 {
1479         float alignaxis[3] = {0.0, 0.0, 0.0};
1480         float norm[3], axis[3], angle, new_quat[4];
1481         
1482         if (axisidx > 0) alignaxis[axisidx - 1] = 1.0;
1483         else alignaxis[-axisidx - 1] = -1.0;
1484
1485         normalize_v3_v3(norm, vec);
1486
1487         angle = (float)acos(dot_v3v3(alignaxis, norm));
1488         cross_v3_v3v3(axis, alignaxis, norm);
1489         axis_angle_to_quat(new_quat, axis, -angle);
1490         
1491         rv3d->view = RV3D_VIEW_USER;
1492         
1493         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
1494                 /* switch out of camera view */
1495                 float orig_ofs[3];
1496                 float orig_dist = rv3d->dist;
1497                 float orig_lens = v3d->lens;
1498                 
1499                 copy_v3_v3(orig_ofs, rv3d->ofs);
1500                 rv3d->persp = RV3D_PERSP;
1501                 rv3d->dist = 0.0;
1502                 ED_view3d_from_object(v3d->camera, rv3d->ofs, NULL, NULL, &v3d->lens);
1503                 view3d_smooth_view(NULL, NULL, NULL, NULL, NULL, orig_ofs, new_quat, &orig_dist, &orig_lens); /* XXX */
1504         }
1505         else {
1506                 if (rv3d->persp == RV3D_CAMOB) rv3d->persp = RV3D_PERSP;  /* switch out of camera mode */
1507                 view3d_smooth_view(NULL, NULL, NULL, NULL, NULL, NULL, new_quat, NULL, NULL); /* XXX */
1508         }
1509 }
1510
1511 float ED_view3d_pixel_size(struct RegionView3D *rv3d, const float co[3])
1512 {
1513         return (rv3d->persmat[3][3] + (
1514                     rv3d->persmat[0][3] * co[0] +
1515                     rv3d->persmat[1][3] * co[1] +
1516                     rv3d->persmat[2][3] * co[2])
1517                 ) * rv3d->pixsize;
1518 }
1519
1520 /* view matrix properties utilities */
1521
1522 /* unused */
1523 #if 0
1524 void ED_view3d_operator_properties_viewmat(wmOperatorType *ot)
1525 {
1526         PropertyRNA *prop;
1527
1528         prop = RNA_def_int(ot->srna, "region_width", 0, 0, INT_MAX, "Region Width", "", 0, INT_MAX);
1529         RNA_def_property_flag(prop, PROP_HIDDEN);
1530
1531         prop = RNA_def_int(ot->srna, "region_height", 0, 0, INT_MAX, "Region height", "", 0, INT_MAX);
1532         RNA_def_property_flag(prop, PROP_HIDDEN);
1533
1534         prop = RNA_def_float_matrix(ot->srna, "perspective_matrix", 4, 4, NULL, 0.0f, 0.0f, "", "Perspective Matrix", 0.0f, 0.0f);
1535         RNA_def_property_flag(prop, PROP_HIDDEN);
1536 }
1537
1538 void ED_view3d_operator_properties_viewmat_set(bContext *C, wmOperator *op)
1539 {
1540         ARegion *ar = CTX_wm_region(C);
1541         RegionView3D *rv3d = ED_view3d_context_rv3d(C);
1542
1543         if (!RNA_struct_property_is_set(op->ptr, "region_width"))
1544                 RNA_int_set(op->ptr, "region_width", ar->winx);
1545
1546         if (!RNA_struct_property_is_set(op->ptr, "region_height"))
1547                 RNA_int_set(op->ptr, "region_height", ar->winy);
1548
1549         if (!RNA_struct_property_is_set(op->ptr, "perspective_matrix"))
1550                 RNA_float_set_array(op->ptr, "perspective_matrix", (float *)rv3d->persmat);
1551 }
1552
1553 void ED_view3d_operator_properties_viewmat_get(wmOperator *op, int *winx, int *winy, float persmat[4][4])
1554 {
1555         *winx = RNA_int_get(op->ptr, "region_width");
1556         *winy = RNA_int_get(op->ptr, "region_height");
1557
1558         RNA_float_get_array(op->ptr, "perspective_matrix", (float *)persmat);
1559 }
1560 #endif