Fix T58275: WITH_OPENSUBDIV not enabled by default with some CMake versions.
[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 #include "DNA_camera_types.h"
32 #include "DNA_scene_types.h"
33 #include "DNA_object_types.h"
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_math.h"
38 #include "BLI_rect.h"
39 #include "BLI_utildefines.h"
40
41 #include "BKE_action.h"
42 #include "BKE_camera.h"
43 #include "BKE_context.h"
44 #include "BKE_depsgraph.h"
45 #include "BKE_object.h"
46 #include "BKE_global.h"
47 #include "BKE_main.h"
48 #include "BKE_report.h"
49 #include "BKE_scene.h"
50
51 #include "BIF_gl.h"
52
53 #include "UI_resources.h"
54
55 #include "GPU_select.h"
56
57 #include "WM_api.h"
58 #include "WM_types.h"
59
60 #include "ED_screen.h"
61
62 #ifdef WITH_GAMEENGINE
63 #  include "BLI_listbase.h"
64 #  include "BLI_callbacks.h"
65
66 #  include "GPU_draw.h"
67
68 #  include "BL_System.h"
69 #endif
70
71 #include "view3d_intern.h"  /* own include */
72
73 /* -------------------------------------------------------------------- */
74 /** \name Smooth View Operator & Utilities
75  *
76  * Use for view transitions to have smooth (animated) transitions.
77  * \{ */
78
79 /* This operator is one of the 'timer refresh' ones like animation playback */
80
81 struct SmoothView3DState {
82         float dist;
83         float lens;
84         float quat[4];
85         float ofs[3];
86 };
87
88 struct SmoothView3DStore {
89         /* source*/
90         struct SmoothView3DState src;  /* source */
91         struct SmoothView3DState dst;  /* destination */
92         struct SmoothView3DState org;  /* original */
93
94         bool to_camera;
95
96         bool use_dyn_ofs;
97         float dyn_ofs[3];
98
99         /* When smooth-view is enabled, store the 'rv3d->view' here,
100          * assign back when the view motion is completed. */
101         char org_view;
102
103         double time_allowed;
104 };
105
106 static void view3d_smooth_view_state_backup(struct SmoothView3DState *sms_state,
107                                             const View3D *v3d, const RegionView3D *rv3d)
108 {
109         copy_v3_v3(sms_state->ofs,   rv3d->ofs);
110         copy_qt_qt(sms_state->quat,  rv3d->viewquat);
111         sms_state->dist            = rv3d->dist;
112         sms_state->lens            = v3d->lens;
113 }
114
115 static void view3d_smooth_view_state_restore(const struct SmoothView3DState *sms_state,
116                                              View3D *v3d, RegionView3D *rv3d)
117 {
118         copy_v3_v3(rv3d->ofs,      sms_state->ofs);
119         copy_qt_qt(rv3d->viewquat, sms_state->quat);
120         rv3d->dist               = sms_state->dist;
121         v3d->lens                = sms_state->lens;
122 }
123
124 /* will start timer if appropriate */
125 /* the arguments are the desired situation */
126 void ED_view3d_smooth_view_ex(
127         /* avoid passing in the context */
128         wmWindowManager *wm, wmWindow *win, ScrArea *sa,
129         View3D *v3d, ARegion *ar, const int smooth_viewtx,
130         const V3D_SmoothParams *sview)
131 {
132         RegionView3D *rv3d = ar->regiondata;
133         struct SmoothView3DStore sms = {{0}};
134         bool ok = false;
135
136         /* initialize sms */
137         view3d_smooth_view_state_backup(&sms.dst, v3d, rv3d);
138         view3d_smooth_view_state_backup(&sms.src, v3d, rv3d);
139         /* if smoothview runs multiple times... */
140         if (rv3d->sms == NULL) {
141                 view3d_smooth_view_state_backup(&sms.org, v3d, rv3d);
142         }
143         else {
144                 sms.org = rv3d->sms->org;
145         }
146         sms.org_view = rv3d->view;
147
148         /* sms.to_camera = false; */  /* initizlized to zero anyway */
149
150         /* note on camera locking, this is a little confusing but works ok.
151          * we may be changing the view 'as if' there is no active camera, but in fact
152          * there is an active camera which is locked to the view.
153          *
154          * In the case where smooth view is moving _to_ a camera we don't want that
155          * camera to be moved or changed, so only when the camera is not being set should
156          * we allow camera option locking to initialize the view settings from the camera.
157          */
158         if (sview->camera == NULL && sview->camera_old == NULL) {
159                 ED_view3d_camera_lock_init(v3d, rv3d);
160         }
161
162         /* store the options we want to end with */
163         if (sview->ofs)
164                 copy_v3_v3(sms.dst.ofs, sview->ofs);
165         if (sview->quat)
166                 copy_qt_qt(sms.dst.quat, sview->quat);
167         if (sview->dist)
168                 sms.dst.dist = *sview->dist;
169         if (sview->lens)
170                 sms.dst.lens = *sview->lens;
171
172         if (sview->dyn_ofs) {
173                 BLI_assert(sview->ofs  == NULL);
174                 BLI_assert(sview->quat != NULL);
175
176                 copy_v3_v3(sms.dyn_ofs, sview->dyn_ofs);
177                 sms.use_dyn_ofs = true;
178
179                 /* calculate the final destination offset */
180                 view3d_orbit_apply_dyn_ofs(sms.dst.ofs, sms.src.ofs, sms.src.quat, sms.dst.quat, sms.dyn_ofs);
181         }
182
183         if (sview->camera) {
184                 sms.dst.dist = ED_view3d_offset_distance(sview->camera->obmat, sview->ofs, VIEW3D_DIST_FALLBACK);
185                 ED_view3d_from_object(sview->camera, sms.dst.ofs, sms.dst.quat, &sms.dst.dist, &sms.dst.lens);
186                 sms.to_camera = true; /* restore view3d values in end */
187         }
188
189         /* skip smooth viewing for render engine draw */
190         if (smooth_viewtx && v3d->drawtype != OB_RENDER) {
191                 bool changed = false; /* zero means no difference */
192
193                 if (sview->camera_old != sview->camera)
194                         changed = true;
195                 else if (sms.dst.dist != rv3d->dist)
196                         changed = true;
197                 else if (sms.dst.lens != v3d->lens)
198                         changed = true;
199                 else if (!equals_v3v3(sms.dst.ofs, rv3d->ofs))
200                         changed = true;
201                 else if (!equals_v4v4(sms.dst.quat, rv3d->viewquat))
202                         changed = true;
203
204                 /* The new view is different from the old one
205                  * so animate the view */
206                 if (changed) {
207                         /* original values */
208                         if (sview->camera_old) {
209                                 sms.src.dist = ED_view3d_offset_distance(sview->camera_old->obmat, rv3d->ofs, 0.0f);
210                                 /* this */
211                                 ED_view3d_from_object(sview->camera_old, sms.src.ofs, sms.src.quat, &sms.src.dist, &sms.src.lens);
212                         }
213                         /* grid draw as floor */
214                         if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
215                                 /* use existing if exists, means multiple calls to smooth view wont loose the original 'view' setting */
216                                 rv3d->view = RV3D_VIEW_USER;
217                         }
218
219                         sms.time_allowed = (double)smooth_viewtx / 1000.0;
220
221                         /* if this is view rotation only
222                          * we can decrease the time allowed by
223                          * the angle between quats
224                          * this means small rotations wont lag */
225                         if (sview->quat && !sview->ofs && !sview->dist) {
226                                 /* scale the time allowed by the rotation */
227                                 sms.time_allowed *= (double)fabsf(angle_signed_normalized_qtqt(sms.dst.quat, sms.src.quat)) / M_PI; /* 180deg == 1.0 */
228                         }
229
230                         /* ensure it shows correct */
231                         if (sms.to_camera) {
232                                 /* use ortho if we move from an ortho view to an ortho camera */
233                                 rv3d->persp = (((rv3d->is_persp == false) &&
234                                                 (sview->camera->type == OB_CAMERA) &&
235                                                 (((Camera *)sview->camera->data)->type == CAM_ORTHO)) ?
236                                                 RV3D_ORTHO : RV3D_PERSP);
237                         }
238
239                         rv3d->rflag |= RV3D_NAVIGATING;
240
241                         /* not essential but in some cases the caller will tag the area for redraw,
242                          * and in that case we can get a flicker of the 'org' user view but we want to see 'src' */
243                         view3d_smooth_view_state_restore(&sms.src, v3d, rv3d);
244
245                         /* keep track of running timer! */
246                         if (rv3d->sms == NULL) {
247                                 rv3d->sms = MEM_mallocN(sizeof(struct SmoothView3DStore), "smoothview v3d");
248                         }
249                         *rv3d->sms = sms;
250                         if (rv3d->smooth_timer) {
251                                 WM_event_remove_timer(wm, win, rv3d->smooth_timer);
252                         }
253                         /* TIMER1 is hardcoded in keymap */
254                         rv3d->smooth_timer = WM_event_add_timer(wm, win, TIMER1, 1.0 / 100.0); /* max 30 frs/sec */
255
256                         ok = true;
257                 }
258         }
259
260         /* if we get here nothing happens */
261         if (ok == false) {
262                 if (sms.to_camera == false) {
263                         copy_v3_v3(rv3d->ofs, sms.dst.ofs);
264                         copy_qt_qt(rv3d->viewquat, sms.dst.quat);
265                         rv3d->dist = sms.dst.dist;
266                         v3d->lens = sms.dst.lens;
267
268                         ED_view3d_camera_lock_sync(v3d, rv3d);
269                 }
270
271                 if (rv3d->viewlock & RV3D_BOXVIEW) {
272                         view3d_boxview_copy(sa, ar);
273                 }
274
275                 ED_region_tag_redraw(ar);
276         }
277 }
278
279 void ED_view3d_smooth_view(
280         bContext *C,
281         View3D *v3d, ARegion *ar, const int smooth_viewtx,
282         const struct V3D_SmoothParams *sview)
283 {
284         wmWindowManager *wm = CTX_wm_manager(C);
285         wmWindow *win = CTX_wm_window(C);
286         ScrArea *sa = CTX_wm_area(C);
287
288         ED_view3d_smooth_view_ex(
289                 wm, win, sa,
290                 v3d, ar, smooth_viewtx,
291                 sview);
292 }
293
294 /* only meant for timer usage */
295 static void view3d_smoothview_apply(bContext *C, View3D *v3d, ARegion *ar, bool sync_boxview)
296 {
297         RegionView3D *rv3d = ar->regiondata;
298         struct SmoothView3DStore *sms = rv3d->sms;
299         float step, step_inv;
300
301         if (sms->time_allowed != 0.0)
302                 step = (float)((rv3d->smooth_timer->duration) / sms->time_allowed);
303         else
304                 step = 1.0f;
305
306         /* end timer */
307         if (step >= 1.0f) {
308
309                 /* if we went to camera, store the original */
310                 if (sms->to_camera) {
311                         rv3d->persp = RV3D_CAMOB;
312                         view3d_smooth_view_state_restore(&sms->org, v3d, rv3d);
313                 }
314                 else {
315                         view3d_smooth_view_state_restore(&sms->dst, v3d, rv3d);
316
317                         ED_view3d_camera_lock_sync(v3d, rv3d);
318                         ED_view3d_camera_lock_autokey(v3d, rv3d, C, true, true);
319                 }
320
321                 if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
322                         rv3d->view = sms->org_view;
323                 }
324
325                 MEM_freeN(rv3d->sms);
326                 rv3d->sms = NULL;
327
328                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rv3d->smooth_timer);
329                 rv3d->smooth_timer = NULL;
330                 rv3d->rflag &= ~RV3D_NAVIGATING;
331         }
332         else {
333                 /* ease in/out */
334                 step = (3.0f * step * step - 2.0f * step * step * step);
335
336                 step_inv = 1.0f - step;
337
338                 interp_qt_qtqt(rv3d->viewquat, sms->src.quat, sms->dst.quat, step);
339
340                 if (sms->use_dyn_ofs) {
341                         view3d_orbit_apply_dyn_ofs(rv3d->ofs, sms->src.ofs, sms->src.quat, rv3d->viewquat, sms->dyn_ofs);
342                 }
343                 else {
344                         interp_v3_v3v3(rv3d->ofs, sms->src.ofs,  sms->dst.ofs,  step);
345                 }
346
347                 rv3d->dist = sms->dst.dist * step + sms->src.dist * step_inv;
348                 v3d->lens  = sms->dst.lens * step + sms->src.lens * step_inv;
349
350                 ED_view3d_camera_lock_sync(v3d, rv3d);
351                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
352                         ED_view3d_camera_lock_autokey(v3d, rv3d, C, true, true);
353                 }
354
355                 /* Event handling won't know if a UI item has been moved under the pointer. */
356                 WM_event_add_mousemove(C);
357         }
358
359         if (sync_boxview && (rv3d->viewlock & RV3D_BOXVIEW)) {
360                 view3d_boxview_copy(CTX_wm_area(C), ar);
361         }
362
363         /* note: this doesn't work right because the v3d->lens is now used in ortho mode r51636,
364          * when switching camera in quad-view the other ortho views would zoom & reset.
365          *
366          * For now only redraw all regions when smoothview finishes.
367          */
368         if (step >= 1.0f) {
369                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
370         }
371         else {
372                 ED_region_tag_redraw(ar);
373         }
374 }
375
376 static int view3d_smoothview_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
377 {
378         View3D *v3d = CTX_wm_view3d(C);
379         ARegion *ar = CTX_wm_region(C);
380         RegionView3D *rv3d = ar->regiondata;
381
382         /* escape if not our timer */
383         if (rv3d->smooth_timer == NULL || rv3d->smooth_timer != event->customdata) {
384                 return OPERATOR_PASS_THROUGH;
385         }
386
387         view3d_smoothview_apply(C, v3d, ar, true);
388
389         return OPERATOR_FINISHED;
390 }
391
392 /**
393  * Apply the smoothview immediately, use when we need to start a new view operation.
394  * (so we don't end up half-applying a view operation when pressing keys quickly).
395  */
396 void ED_view3d_smooth_view_force_finish(
397         bContext *C,
398         View3D *v3d, ARegion *ar)
399 {
400         RegionView3D *rv3d = ar->regiondata;
401
402         if (rv3d && rv3d->sms) {
403                 rv3d->sms->time_allowed = 0.0;  /* force finishing */
404                 view3d_smoothview_apply(C, v3d, ar, false);
405
406                 /* force update of view matrix so tools that run immediately after
407                  * can use them without redrawing first */
408                 Scene *scene = CTX_data_scene(C);
409                 ED_view3d_update_viewmat(scene, v3d, ar, NULL, NULL, NULL);
410         }
411 }
412
413 void VIEW3D_OT_smoothview(wmOperatorType *ot)
414 {
415         /* identifiers */
416         ot->name = "Smooth View";
417         ot->idname = "VIEW3D_OT_smoothview";
418
419         /* api callbacks */
420         ot->invoke = view3d_smoothview_invoke;
421
422         /* flags */
423         ot->flag = OPTYPE_INTERNAL;
424
425         ot->poll = ED_operator_view3d_active;
426 }
427
428 /** \} */
429
430 /* -------------------------------------------------------------------- */
431 /** \name Camera to View Operator
432  * \{ */
433
434 static int view3d_camera_to_view_exec(bContext *C, wmOperator *UNUSED(op))
435 {
436         View3D *v3d;
437         ARegion *ar;
438         RegionView3D *rv3d;
439
440         ObjectTfmProtectedChannels obtfm;
441
442         ED_view3d_context_user_region(C, &v3d, &ar);
443         rv3d = ar->regiondata;
444
445         ED_view3d_lastview_store(rv3d);
446
447         BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
448
449         ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
450
451         BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag);
452
453         DAG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
454         rv3d->persp = RV3D_CAMOB;
455
456         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, v3d->camera);
457
458         return OPERATOR_FINISHED;
459
460 }
461
462 static bool view3d_camera_to_view_poll(bContext *C)
463 {
464         View3D *v3d;
465         ARegion *ar;
466
467         if (ED_view3d_context_user_region(C, &v3d, &ar)) {
468                 RegionView3D *rv3d = ar->regiondata;
469                 if (v3d && v3d->camera && !ID_IS_LINKED(v3d->camera)) {
470                         if (rv3d && (rv3d->viewlock & RV3D_LOCKED) == 0) {
471                                 if (rv3d->persp != RV3D_CAMOB) {
472                                         return 1;
473                                 }
474                         }
475                 }
476         }
477
478         return 0;
479 }
480
481 void VIEW3D_OT_camera_to_view(wmOperatorType *ot)
482 {
483         /* identifiers */
484         ot->name = "Align Camera To View";
485         ot->description = "Set camera view to active view";
486         ot->idname = "VIEW3D_OT_camera_to_view";
487
488         /* api callbacks */
489         ot->exec = view3d_camera_to_view_exec;
490         ot->poll = view3d_camera_to_view_poll;
491
492         /* flags */
493         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
494 }
495
496 /** \} */
497
498 /* -------------------------------------------------------------------- */
499 /** \name Camera Fit Frame to Selected Operator
500  * \{ */
501
502 /* unlike VIEW3D_OT_view_selected this is for framing a render and not
503  * meant to take into account vertex/bone selection for eg. */
504 static int view3d_camera_to_view_selected_exec(bContext *C, wmOperator *op)
505 {
506         Main *bmain = CTX_data_main(C);
507         Scene *scene = CTX_data_scene(C);
508         View3D *v3d = CTX_wm_view3d(C);  /* can be NULL */
509         Object *camera_ob = v3d ? v3d->camera : scene->camera;
510
511         float r_co[3]; /* the new location to apply */
512         float r_scale; /* only for ortho cameras */
513
514         if (camera_ob == NULL) {
515                 BKE_report(op->reports, RPT_ERROR, "No active camera");
516                 return OPERATOR_CANCELLED;
517         }
518
519         /* this function does all the important stuff */
520         if (BKE_camera_view_frame_fit_to_scene(bmain, scene, v3d, camera_ob, r_co, &r_scale)) {
521                 ObjectTfmProtectedChannels obtfm;
522                 float obmat_new[4][4];
523
524                 if ((camera_ob->type == OB_CAMERA) && (((Camera *)camera_ob->data)->type == CAM_ORTHO)) {
525                         ((Camera *)camera_ob->data)->ortho_scale = r_scale;
526                 }
527
528                 copy_m4_m4(obmat_new, camera_ob->obmat);
529                 copy_v3_v3(obmat_new[3], r_co);
530
531                 /* only touch location */
532                 BKE_object_tfm_protected_backup(camera_ob, &obtfm);
533                 BKE_object_apply_mat4(camera_ob, obmat_new, true, true);
534                 BKE_object_tfm_protected_restore(camera_ob, &obtfm, OB_LOCK_SCALE | OB_LOCK_ROT4D);
535
536                 /* notifiers */
537                 DAG_id_tag_update(&camera_ob->id, OB_RECALC_OB);
538                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, camera_ob);
539                 return OPERATOR_FINISHED;
540         }
541         else {
542                 return OPERATOR_CANCELLED;
543         }
544 }
545
546 void VIEW3D_OT_camera_to_view_selected(wmOperatorType *ot)
547 {
548         /* identifiers */
549         ot->name = "Camera Fit Frame to Selected";
550         ot->description = "Move the camera so selected objects are framed";
551         ot->idname = "VIEW3D_OT_camera_to_view_selected";
552
553         /* api callbacks */
554         ot->exec = view3d_camera_to_view_selected_exec;
555         ot->poll = ED_operator_scene_editable;
556
557         /* flags */
558         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
559 }
560
561 /** \} */
562
563 /* -------------------------------------------------------------------- */
564 /** \name Object as Camera Operator
565  * \{ */
566
567 static void sync_viewport_camera_smoothview(bContext *C, View3D *v3d, Object *ob, const int smooth_viewtx)
568 {
569         Main *bmain = CTX_data_main(C);
570         for (bScreen *screen = bmain->screen.first; screen != NULL; screen = screen->id.next) {
571                 for (ScrArea *area = screen->areabase.first; area != NULL; area = area->next) {
572                         for (SpaceLink *space_link = area->spacedata.first; space_link != NULL; space_link = space_link->next) {
573                                 if (space_link->spacetype == SPACE_VIEW3D) {
574                                         View3D *other_v3d = (View3D *)space_link;
575                                         if (other_v3d == v3d) {
576                                                 continue;
577                                         }
578                                         if (other_v3d->camera == ob) {
579                                                 continue;
580                                         }
581                                         if (v3d->scenelock) {
582                                                 ListBase *lb = (space_link == area->spacedata.first)
583                                                                    ? &area->regionbase
584                                                                    : &space_link->regionbase;
585                                                 for (ARegion *other_ar = lb->first; other_ar != NULL; other_ar = other_ar->next) {
586                                                         if (other_ar->regiontype == RGN_TYPE_WINDOW) {
587                                                                 if (other_ar->regiondata) {
588                                                                         RegionView3D *other_rv3d = other_ar->regiondata;
589                                                                         if (other_rv3d->persp == RV3D_CAMOB) {
590                                                                                 Object *other_camera_old = other_v3d->camera;
591                                                                                 other_v3d->camera = ob;
592                                                                                 ED_view3d_lastview_store(other_rv3d);
593                                                                                 ED_view3d_smooth_view(
594                                                                                         C, other_v3d, other_ar, smooth_viewtx,
595                                                                                         &(const V3D_SmoothParams) {
596                                                                                             .camera_old = other_camera_old,
597                                                                                             .camera = other_v3d->camera,
598                                                                                             .ofs = other_rv3d->ofs,
599                                                                                             .quat = other_rv3d->viewquat,
600                                                                                             .dist = &other_rv3d->dist,
601                                                                                             .lens = &other_v3d->lens});
602                                                                         }
603                                                                         else {
604                                                                                 other_v3d->camera = ob;
605                                                                         }
606                                                                 }
607                                                         }
608                                                 }
609                                         }
610                                 }
611                         }
612                 }
613         }
614 }
615
616 static int view3d_setobjectascamera_exec(bContext *C, wmOperator *op)
617 {
618         View3D *v3d;
619         ARegion *ar;
620         RegionView3D *rv3d;
621
622         Scene *scene = CTX_data_scene(C);
623         Object *ob = CTX_data_active_object(C);
624
625         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
626
627         /* no NULL check is needed, poll checks */
628         ED_view3d_context_user_region(C, &v3d, &ar);
629         rv3d = ar->regiondata;
630
631         if (ob) {
632                 Object *camera_old = (rv3d->persp == RV3D_CAMOB) ? V3D_CAMERA_SCENE(scene, v3d) : NULL;
633                 rv3d->persp = RV3D_CAMOB;
634                 v3d->camera = ob;
635                 if (v3d->scenelock)
636                         scene->camera = ob;
637
638                 /* unlikely but looks like a glitch when set to the same */
639                 if (camera_old != ob) {
640                         ED_view3d_lastview_store(rv3d);
641
642                         ED_view3d_smooth_view(
643                                 C, v3d, ar, smooth_viewtx,
644                                 &(const V3D_SmoothParams) {
645                                     .camera_old = camera_old, .camera = v3d->camera,
646                                     .ofs = rv3d->ofs, .quat = rv3d->viewquat,
647                                     .dist = &rv3d->dist, .lens = &v3d->lens});
648                 }
649
650                 if (v3d->scenelock) {
651                         sync_viewport_camera_smoothview(C, v3d, ob, smooth_viewtx);
652                         WM_event_add_notifier(C, NC_SCENE, scene);
653                 }
654                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene);
655         }
656
657         return OPERATOR_FINISHED;
658 }
659
660 bool ED_operator_rv3d_user_region_poll(bContext *C)
661 {
662         View3D *v3d_dummy;
663         ARegion *ar_dummy;
664
665         return ED_view3d_context_user_region(C, &v3d_dummy, &ar_dummy);
666 }
667
668 void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
669 {
670         /* identifiers */
671         ot->name = "Set Active Object as Camera";
672         ot->description = "Set the active object as the active camera for this view or scene";
673         ot->idname = "VIEW3D_OT_object_as_camera";
674
675         /* api callbacks */
676         ot->exec = view3d_setobjectascamera_exec;
677         ot->poll = ED_operator_rv3d_user_region_poll;
678
679         /* flags */
680         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
681 }
682
683 /** \} */
684
685 /* -------------------------------------------------------------------- */
686 /** \name Window and View Matrix Calculation
687  * \{ */
688
689 /**
690  * \param rect optional for picking (can be NULL).
691  */
692 void view3d_winmatrix_set(ARegion *ar, const View3D *v3d, const rcti *rect)
693 {
694         RegionView3D *rv3d = ar->regiondata;
695         rctf viewplane;
696         float clipsta, clipend;
697         bool is_ortho;
698
699         is_ortho = ED_view3d_viewplane_get(v3d, rv3d, ar->winx, ar->winy, &viewplane, &clipsta, &clipend, NULL);
700         rv3d->is_persp = !is_ortho;
701
702 #if 0
703         printf("%s: %d %d %f %f %f %f %f %f\n", __func__, winx, winy,
704                viewplane.xmin, viewplane.ymin, viewplane.xmax, viewplane.ymax,
705                clipsta, clipend);
706 #endif
707
708         if (rect) {  /* picking */
709                 rctf r;
710                 r.xmin = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmin / (float)ar->winx));
711                 r.ymin = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymin / (float)ar->winy));
712                 r.xmax = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmax / (float)ar->winx));
713                 r.ymax = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymax / (float)ar->winy));
714                 viewplane = r;
715         }
716
717         if (is_ortho) {
718                 wmOrtho(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
719         }
720         else {
721                 wmFrustum(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
722         }
723
724         /* update matrix in 3d view region */
725         glGetFloatv(GL_PROJECTION_MATRIX, (float *)rv3d->winmat);
726 }
727
728 static void obmat_to_viewmat(RegionView3D *rv3d, Object *ob)
729 {
730         float bmat[4][4];
731
732         rv3d->view = RV3D_VIEW_USER; /* don't show the grid */
733
734         normalize_m4_m4(bmat, ob->obmat);
735         invert_m4_m4(rv3d->viewmat, bmat);
736
737         /* view quat calculation, needed for add object */
738         mat4_normalized_to_quat(rv3d->viewquat, rv3d->viewmat);
739 }
740
741 /**
742  * Sets #RegionView3D.viewmat
743  *
744  * \param scene: Scene for camera and cursor location.
745  * \param v3d: View 3D space data.
746  * \param rv3d: 3D region which stores the final matrices.
747  * \param rect_scale: Optional 2D scale argument,
748  * Use when displaying a sub-region, eg: when #view3d_winmatrix_set takes a 'rect' argument.
749  *
750  * \note don't set windows active in here, is used by renderwin too.
751  */
752 void view3d_viewmatrix_set(
753         Scene *scene,
754         const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2])
755 {
756         if (rv3d->persp == RV3D_CAMOB) {      /* obs/camera */
757                 if (v3d->camera) {
758                         BKE_object_where_is_calc(scene, v3d->camera);
759                         obmat_to_viewmat(rv3d, v3d->camera);
760                 }
761                 else {
762                         quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
763                         rv3d->viewmat[3][2] -= rv3d->dist;
764                 }
765         }
766         else {
767                 bool use_lock_ofs = false;
768
769
770                 /* should be moved to better initialize later on XXX */
771                 if (rv3d->viewlock & RV3D_LOCKED)
772                         ED_view3d_lock(rv3d);
773
774                 quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
775                 if (rv3d->persp == RV3D_PERSP) rv3d->viewmat[3][2] -= rv3d->dist;
776                 if (v3d->ob_centre) {
777                         Object *ob = v3d->ob_centre;
778                         float vec[3];
779
780                         copy_v3_v3(vec, ob->obmat[3]);
781                         if (ob->type == OB_ARMATURE && v3d->ob_centre_bone[0]) {
782                                 bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, v3d->ob_centre_bone);
783                                 if (pchan) {
784                                         copy_v3_v3(vec, pchan->pose_mat[3]);
785                                         mul_m4_v3(ob->obmat, vec);
786                                 }
787                         }
788                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
789                         use_lock_ofs = true;
790                 }
791                 else if (v3d->ob_centre_cursor) {
792                         float vec[3];
793                         copy_v3_v3(vec, ED_view3d_cursor3d_get(scene, (View3D *)v3d));
794                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
795                         use_lock_ofs = true;
796                 }
797                 else {
798                         translate_m4(rv3d->viewmat, rv3d->ofs[0], rv3d->ofs[1], rv3d->ofs[2]);
799                 }
800
801                 /* lock offset */
802                 if (use_lock_ofs) {
803                         float persmat[4][4], persinv[4][4];
804                         float vec[3];
805
806                         /* we could calculate the real persmat/persinv here
807                          * but it would be unreliable so better to later */
808                         mul_m4_m4m4(persmat, rv3d->winmat, rv3d->viewmat);
809                         invert_m4_m4(persinv, persmat);
810
811                         mul_v2_v2fl(vec, rv3d->ofs_lock, rv3d->is_persp ? rv3d->dist : 1.0f);
812                         vec[2] = 0.0f;
813
814                         if (rect_scale) {
815                                 /* Since 'RegionView3D.winmat' has been calculated and this function doesn't take the 'ARegion'
816                                  * we don't know about the region size.
817                                  * Use 'rect_scale' when drawing a sub-region to apply 2D offset,
818                                  * scaled by the difference between the sub-region and the region size.
819                                  */
820                                 vec[0] /= rect_scale[0];
821                                 vec[1] /= rect_scale[1];
822                         }
823
824                         mul_mat3_m4_v3(persinv, vec);
825                         translate_m4(rv3d->viewmat, vec[0], vec[1], vec[2]);
826                 }
827                 /* end lock offset */
828         }
829 }
830
831 /** \} */
832
833 /* -------------------------------------------------------------------- */
834 /** \name OpenGL Select Utilities
835  * \{ */
836
837 /**
838  * Optionally cache data for multiple calls to #view3d_opengl_select
839  *
840  * just avoid GPU_select headers outside this file
841  */
842 void view3d_opengl_select_cache_begin(void)
843 {
844         GPU_select_cache_begin();
845 }
846
847 void view3d_opengl_select_cache_end(void)
848 {
849         GPU_select_cache_end();
850 }
851
852 /**
853  * \warning be sure to account for a negative return value
854  * This is an error, "Too many objects in select buffer"
855  * and no action should be taken (can crash blender) if this happens
856  *
857  * \note (vc->obedit == NULL) can be set to explicitly skip edit-object selection.
858  */
859 int view3d_opengl_select(
860         ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const rcti *input,
861         eV3DSelectMode select_mode)
862 {
863         struct bThemeState theme_state;
864         Scene *scene = vc->scene;
865         View3D *v3d = vc->v3d;
866         ARegion *ar = vc->ar;
867         rcti rect;
868         int hits;
869         const bool use_obedit_skip = (scene->obedit != NULL) && (vc->obedit == NULL);
870         const bool is_pick_select = (U.gpu_select_pick_deph != 0);
871         const bool do_passes = (
872                 (is_pick_select == false) &&
873                 (select_mode == VIEW3D_SELECT_PICK_NEAREST) &&
874                 GPU_select_query_check_active());
875         const bool use_nearest = (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST);
876
877         char gpu_select_mode;
878
879         /* case not a border select */
880         if (input->xmin == input->xmax) {
881                 /* seems to be default value for bones only now */
882                 BLI_rcti_init_pt_radius(&rect, (const int[2]){input->xmin, input->ymin}, 12);
883         }
884         else {
885                 rect = *input;
886         }
887
888         if (is_pick_select) {
889                 if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST) {
890                         gpu_select_mode = GPU_SELECT_PICK_NEAREST;
891                 }
892                 else if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_ALL) {
893                         gpu_select_mode = GPU_SELECT_PICK_ALL;
894                 }
895                 else {
896                         gpu_select_mode = GPU_SELECT_ALL;
897                 }
898         }
899         else {
900                 if (do_passes) {
901                         gpu_select_mode = GPU_SELECT_NEAREST_FIRST_PASS;
902                 }
903                 else {
904                         gpu_select_mode = GPU_SELECT_ALL;
905                 }
906         }
907
908         /* Tools may request depth outside of regular drawing code. */
909         UI_Theme_Store(&theme_state);
910         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
911
912         /* Re-use cache (rect must be smaller then the cached)
913          * other context is assumed to be unchanged */
914         if (GPU_select_is_cached()) {
915                 GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
916                 GPU_select_cache_load_id();
917                 hits = GPU_select_end();
918                 goto finally;
919         }
920
921         G.f |= G_PICKSEL;
922
923         /* Important we use the 'viewmat' and don't re-calculate since
924          * the object & bone view locking takes 'rect' into account, see: T51629. */
925         ED_view3d_draw_setup_view(vc->win, scene, ar, v3d, vc->rv3d->viewmat, NULL, &rect);
926
927         if (v3d->drawtype > OB_WIRE) {
928                 v3d->zbuf = true;
929                 glEnable(GL_DEPTH_TEST);
930         }
931
932         if (vc->rv3d->rflag & RV3D_CLIPPING)
933                 ED_view3d_clipping_set(vc->rv3d);
934
935         GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
936
937         ED_view3d_draw_select_loop(vc, scene, v3d, ar, use_obedit_skip, use_nearest);
938
939         hits = GPU_select_end();
940
941         /* second pass, to get the closest object to camera */
942         if (do_passes && (hits > 0)) {
943                 GPU_select_begin(buffer, bufsize, &rect, GPU_SELECT_NEAREST_SECOND_PASS, hits);
944
945                 ED_view3d_draw_select_loop(vc, scene, v3d, ar, use_obedit_skip, use_nearest);
946
947                 GPU_select_end();
948         }
949
950         G.f &= ~G_PICKSEL;
951         ED_view3d_draw_setup_view(vc->win, scene, ar, v3d, vc->rv3d->viewmat, NULL, NULL);
952
953         if (v3d->drawtype > OB_WIRE) {
954                 v3d->zbuf = 0;
955                 glDisable(GL_DEPTH_TEST);
956         }
957
958         if (vc->rv3d->rflag & RV3D_CLIPPING)
959                 ED_view3d_clipping_disable();
960
961 finally:
962         if (hits < 0) printf("Too many objects in select buffer\n");  /* XXX make error message */
963
964         UI_Theme_Restore(&theme_state);
965
966         return hits;
967 }
968
969 /** \} */
970
971 /* -------------------------------------------------------------------- */
972 /** \name Local View Operators
973  * \{ */
974
975 static unsigned int free_localbit(Main *bmain)
976 {
977         unsigned int lay;
978         ScrArea *sa;
979         bScreen *sc;
980
981         lay = 0;
982
983         /* sometimes we loose a localview: when an area is closed */
984         /* check all areas: which localviews are in use? */
985         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
986                 for (sa = sc->areabase.first; sa; sa = sa->next) {
987                         SpaceLink *sl = sa->spacedata.first;
988                         for (; sl; sl = sl->next) {
989                                 if (sl->spacetype == SPACE_VIEW3D) {
990                                         View3D *v3d = (View3D *) sl;
991                                         lay |= v3d->lay;
992                                 }
993                         }
994                 }
995         }
996
997         if ((lay & 0x01000000) == 0) return 0x01000000;
998         if ((lay & 0x02000000) == 0) return 0x02000000;
999         if ((lay & 0x04000000) == 0) return 0x04000000;
1000         if ((lay & 0x08000000) == 0) return 0x08000000;
1001         if ((lay & 0x10000000) == 0) return 0x10000000;
1002         if ((lay & 0x20000000) == 0) return 0x20000000;
1003         if ((lay & 0x40000000) == 0) return 0x40000000;
1004         if ((lay & 0x80000000) == 0) return 0x80000000;
1005
1006         return 0;
1007 }
1008
1009 int ED_view3d_scene_layer_set(int lay, const bool *values, int *active)
1010 {
1011         int i, tot = 0;
1012
1013         /* ensure we always have some layer selected */
1014         for (i = 0; i < 20; i++)
1015                 if (values[i])
1016                         tot++;
1017
1018         if (tot == 0)
1019                 return lay;
1020
1021         for (i = 0; i < 20; i++) {
1022
1023                 if (active) {
1024                         /* if this value has just been switched on, make that layer active */
1025                         if (values[i] && (lay & (1 << i)) == 0) {
1026                                 *active = (1 << i);
1027                         }
1028                 }
1029
1030                 if (values[i]) lay |= (1 << i);
1031                 else lay &= ~(1 << i);
1032         }
1033
1034         /* ensure always an active layer */
1035         if (active && (lay & *active) == 0) {
1036                 for (i = 0; i < 20; i++) {
1037                         if (lay & (1 << i)) {
1038                                 *active = 1 << i;
1039                                 break;
1040                         }
1041                 }
1042         }
1043
1044         return lay;
1045 }
1046
1047 static bool view3d_localview_init(
1048         wmWindowManager *wm, wmWindow *win,
1049         Main *bmain, Scene *scene, ScrArea *sa, const int smooth_viewtx,
1050         ReportList *reports)
1051 {
1052         View3D *v3d = sa->spacedata.first;
1053         Base *base;
1054         float min[3], max[3], box[3], mid[3];
1055         float size = 0.0f;
1056         unsigned int locallay;
1057         bool ok = false;
1058
1059         if (v3d->localvd) {
1060                 return ok;
1061         }
1062
1063         INIT_MINMAX(min, max);
1064
1065         locallay = free_localbit(bmain);
1066
1067         if (locallay == 0) {
1068                 BKE_report(reports, RPT_ERROR, "No more than 8 local views");
1069                 ok = false;
1070         }
1071         else {
1072                 if (scene->obedit) {
1073                         BKE_object_minmax(scene->obedit, min, max, false);
1074
1075                         ok = true;
1076
1077                         BASACT->lay |= locallay;
1078                         scene->obedit->lay = BASACT->lay;
1079                 }
1080                 else {
1081                         for (base = FIRSTBASE; base; base = base->next) {
1082                                 if (TESTBASE(v3d, base)) {
1083                                         BKE_object_minmax(base->object, min, max, false);
1084                                         base->lay |= locallay;
1085                                         base->object->lay = base->lay;
1086                                         ok = true;
1087                                 }
1088                         }
1089                 }
1090
1091                 sub_v3_v3v3(box, max, min);
1092                 size = max_fff(box[0], box[1], box[2]);
1093         }
1094
1095         if (ok == true) {
1096                 ARegion *ar;
1097
1098                 v3d->localvd = MEM_mallocN(sizeof(View3D), "localview");
1099
1100                 memcpy(v3d->localvd, v3d, sizeof(View3D));
1101
1102                 mid_v3_v3v3(mid, min, max);
1103
1104                 copy_v3_v3(v3d->cursor, mid);
1105
1106                 for (ar = sa->regionbase.first; ar; ar = ar->next) {
1107                         if (ar->regiontype == RGN_TYPE_WINDOW) {
1108                                 RegionView3D *rv3d = ar->regiondata;
1109                                 bool ok_dist = true;
1110
1111                                 /* new view values */
1112                                 Object *camera_old = NULL;
1113                                 float dist_new, ofs_new[3];
1114
1115                                 rv3d->localvd = MEM_mallocN(sizeof(RegionView3D), "localview region");
1116                                 memcpy(rv3d->localvd, rv3d, sizeof(RegionView3D));
1117
1118                                 negate_v3_v3(ofs_new, mid);
1119
1120                                 if (rv3d->persp == RV3D_CAMOB) {
1121                                         rv3d->persp = RV3D_PERSP;
1122                                         camera_old = v3d->camera;
1123                                 }
1124
1125                                 if (rv3d->persp == RV3D_ORTHO) {
1126                                         if (size < 0.0001f) {
1127                                                 ok_dist = false;
1128                                         }
1129                                 }
1130
1131                                 if (ok_dist) {
1132                                         dist_new = ED_view3d_radius_to_dist(v3d, ar, rv3d->persp, true, (size / 2) * VIEW3D_MARGIN);
1133                                         if (rv3d->persp == RV3D_PERSP) {
1134                                                 /* don't zoom closer than the near clipping plane */
1135                                                 dist_new = max_ff(dist_new, v3d->near * 1.5f);
1136                                         }
1137                                 }
1138
1139                                 ED_view3d_smooth_view_ex(
1140                                         wm, win, sa, v3d, ar, smooth_viewtx,
1141                                             &(const V3D_SmoothParams) {
1142                                                 .camera_old = camera_old,
1143                                                 .ofs = ofs_new, .quat = rv3d->viewquat,
1144                                                 .dist = ok_dist ? &dist_new : NULL, .lens = &v3d->lens});
1145                         }
1146                 }
1147
1148                 v3d->lay = locallay;
1149         }
1150         else {
1151                 /* clear flags */
1152                 for (base = FIRSTBASE; base; base = base->next) {
1153                         if (base->lay & locallay) {
1154                                 base->lay -= locallay;
1155                                 if (base->lay == 0) base->lay = v3d->layact;
1156                                 if (base->object != scene->obedit) base->flag |= SELECT;
1157                                 base->object->lay = base->lay;
1158                         }
1159                 }
1160         }
1161
1162         DAG_on_visible_update(bmain, false);
1163
1164         return ok;
1165 }
1166
1167 static void restore_localviewdata(wmWindowManager *wm, wmWindow *win, Main *bmain, ScrArea *sa, const int smooth_viewtx)
1168 {
1169         const bool free = true;
1170         ARegion *ar;
1171         View3D *v3d = sa->spacedata.first;
1172         Object *camera_old, *camera_new;
1173
1174         if (v3d->localvd == NULL) return;
1175
1176         camera_old = v3d->camera;
1177         camera_new = v3d->localvd->camera;
1178
1179         v3d->lay = v3d->localvd->lay;
1180         v3d->layact = v3d->localvd->layact;
1181         v3d->drawtype = v3d->localvd->drawtype;
1182         v3d->camera = v3d->localvd->camera;
1183
1184         if (free) {
1185                 MEM_freeN(v3d->localvd);
1186                 v3d->localvd = NULL;
1187         }
1188
1189         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1190                 if (ar->regiontype == RGN_TYPE_WINDOW) {
1191                         RegionView3D *rv3d = ar->regiondata;
1192
1193                         if (rv3d->localvd) {
1194                                 Object *camera_old_rv3d, *camera_new_rv3d;
1195
1196                                 camera_old_rv3d = (rv3d->persp          == RV3D_CAMOB) ? camera_old : NULL;
1197                                 camera_new_rv3d = (rv3d->localvd->persp == RV3D_CAMOB) ? camera_new : NULL;
1198
1199                                 rv3d->view = rv3d->localvd->view;
1200                                 rv3d->persp = rv3d->localvd->persp;
1201                                 rv3d->camzoom = rv3d->localvd->camzoom;
1202
1203                                 ED_view3d_smooth_view_ex(
1204                                         wm, win, sa,
1205                                         v3d, ar, smooth_viewtx,
1206                                         &(const V3D_SmoothParams) {
1207                                             .camera_old = camera_old_rv3d, .camera = camera_new_rv3d,
1208                                             .ofs = rv3d->localvd->ofs, .quat = rv3d->localvd->viewquat,
1209                                             .dist = &rv3d->localvd->dist});
1210
1211                                 if (free) {
1212                                         MEM_freeN(rv3d->localvd);
1213                                         rv3d->localvd = NULL;
1214                                 }
1215                         }
1216
1217                         ED_view3d_shade_update(bmain, v3d, sa);
1218                 }
1219         }
1220 }
1221
1222 static bool view3d_localview_exit(
1223         wmWindowManager *wm, wmWindow *win,
1224         Main *bmain, Scene *scene, ScrArea *sa, const int smooth_viewtx)
1225 {
1226         View3D *v3d = sa->spacedata.first;
1227         struct Base *base;
1228         unsigned int locallay;
1229
1230         if (v3d->localvd) {
1231
1232                 locallay = v3d->lay & 0xFF000000;
1233
1234                 restore_localviewdata(wm, win, bmain, sa, smooth_viewtx);
1235
1236                 /* for when in other window the layers have changed */
1237                 if (v3d->scenelock) v3d->lay = scene->lay;
1238
1239                 for (base = FIRSTBASE; base; base = base->next) {
1240                         if (base->lay & locallay) {
1241                                 base->lay -= locallay;
1242                                 if (base->lay == 0) base->lay = v3d->layact;
1243                                 if (base->object != scene->obedit) {
1244                                         base->flag |= SELECT;
1245                                         base->object->flag |= SELECT;
1246                                 }
1247                                 base->object->lay = base->lay;
1248                         }
1249                 }
1250
1251                 DAG_on_visible_update(bmain, false);
1252
1253                 return true;
1254         }
1255         else {
1256                 return false;
1257         }
1258 }
1259
1260 static int localview_exec(bContext *C, wmOperator *op)
1261 {
1262         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
1263         wmWindowManager *wm = CTX_wm_manager(C);
1264         wmWindow *win = CTX_wm_window(C);
1265         Main *bmain = CTX_data_main(C);
1266         Scene *scene = CTX_data_scene(C);
1267         ScrArea *sa = CTX_wm_area(C);
1268         View3D *v3d = CTX_wm_view3d(C);
1269         bool changed;
1270
1271         if (v3d->localvd) {
1272                 changed = view3d_localview_exit(wm, win, bmain, scene, sa, smooth_viewtx);
1273         }
1274         else {
1275                 changed = view3d_localview_init(wm, win, bmain, scene, sa, smooth_viewtx, op->reports);
1276         }
1277
1278         if (changed) {
1279                 DAG_id_type_tag(bmain, ID_OB);
1280                 ED_area_tag_redraw(sa);
1281
1282                 /* unselected objects become selected when exiting */
1283                 if (v3d->localvd == NULL) {
1284                         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
1285                 }
1286
1287                 return OPERATOR_FINISHED;
1288         }
1289         else {
1290                 return OPERATOR_CANCELLED;
1291         }
1292 }
1293
1294 void VIEW3D_OT_localview(wmOperatorType *ot)
1295 {
1296         /* identifiers */
1297         ot->name = "Local View";
1298         ot->description = "Toggle display of selected object(s) separately and centered in view";
1299         ot->idname = "VIEW3D_OT_localview";
1300
1301         /* api callbacks */
1302         ot->exec = localview_exec;
1303         ot->flag = OPTYPE_UNDO; /* localview changes object layer bitflags */
1304
1305         ot->poll = ED_operator_view3d_active;
1306 }
1307
1308 /** \} */
1309
1310 /* -------------------------------------------------------------------- */
1311 /** \name Game Engine Operator
1312  *
1313  * Start the game engine (handles context switching).
1314  * \{ */
1315
1316 #ifdef WITH_GAMEENGINE
1317
1318 static ListBase queue_back;
1319 static void game_engine_save_state(bContext *C, wmWindow *win)
1320 {
1321         Main *bmain = CTX_data_main(C);
1322         Object *obact = CTX_data_active_object(C);
1323
1324         glPushAttrib(GL_ALL_ATTRIB_BITS);
1325
1326         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1327                 GPU_paint_set_mipmap(bmain, 1);
1328
1329         queue_back = win->queue;
1330
1331         BLI_listbase_clear(&win->queue);
1332 }
1333
1334 static void game_engine_restore_state(bContext *C, wmWindow *win)
1335 {
1336         Main *bmain = CTX_data_main(C);
1337         Object *obact = CTX_data_active_object(C);
1338
1339         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1340                 GPU_paint_set_mipmap(bmain, 0);
1341
1342         /* check because closing win can set to NULL */
1343         if (win) {
1344                 win->queue = queue_back;
1345         }
1346
1347         GPU_state_init();
1348         GPU_set_tpage(NULL, 0, 0);
1349
1350         glPopAttrib();
1351 }
1352
1353 /* was space_set_commmandline_options in 2.4x */
1354 static void game_set_commmandline_options(GameData *gm)
1355 {
1356         SYS_SystemHandle syshandle;
1357         int test;
1358
1359         if ((syshandle = SYS_GetSystem())) {
1360                 /* User defined settings */
1361                 test = (U.gameflags & USER_DISABLE_MIPMAP);
1362                 GPU_set_mipmap(G_MAIN, !test);
1363                 SYS_WriteCommandLineInt(syshandle, "nomipmap", test);
1364
1365                 /* File specific settings: */
1366                 /* Only test the first one. These two are switched
1367                  * simultaneously. */
1368                 test = (gm->flag & GAME_SHOW_FRAMERATE);
1369                 SYS_WriteCommandLineInt(syshandle, "show_framerate", test);
1370                 SYS_WriteCommandLineInt(syshandle, "show_profile", test);
1371
1372                 test = (gm->flag & GAME_SHOW_DEBUG_PROPS);
1373                 SYS_WriteCommandLineInt(syshandle, "show_properties", test);
1374
1375                 test = (gm->flag & GAME_SHOW_PHYSICS);
1376                 SYS_WriteCommandLineInt(syshandle, "show_physics", test);
1377
1378                 test = (gm->flag & GAME_ENABLE_ALL_FRAMES);
1379                 SYS_WriteCommandLineInt(syshandle, "fixedtime", test);
1380
1381                 test = (gm->flag & GAME_ENABLE_ANIMATION_RECORD);
1382                 SYS_WriteCommandLineInt(syshandle, "animation_record", test);
1383
1384                 test = (gm->flag & GAME_IGNORE_DEPRECATION_WARNINGS);
1385                 SYS_WriteCommandLineInt(syshandle, "ignore_deprecation_warnings", test);
1386
1387                 test = (gm->matmode == GAME_MAT_MULTITEX);
1388                 SYS_WriteCommandLineInt(syshandle, "blender_material", test);
1389                 test = (gm->matmode == GAME_MAT_GLSL);
1390                 SYS_WriteCommandLineInt(syshandle, "blender_glsl_material", test);
1391                 test = (gm->flag & GAME_DISPLAY_LISTS);
1392                 SYS_WriteCommandLineInt(syshandle, "displaylists", test);
1393
1394
1395         }
1396 }
1397
1398 #endif /* WITH_GAMEENGINE */
1399
1400 static bool game_engine_poll(bContext *C)
1401 {
1402         bScreen *screen;
1403         /* we need a context and area to launch BGE
1404          * it's a temporary solution to avoid crash at load time
1405          * if we try to auto run the BGE. Ideally we want the
1406          * context to be set as soon as we load the file. */
1407
1408         if (CTX_wm_window(C) == NULL) return 0;
1409         if ((screen = CTX_wm_screen(C)) == NULL) return 0;
1410
1411         if (CTX_data_mode_enum(C) != CTX_MODE_OBJECT)
1412                 return 0;
1413
1414         if (!BKE_scene_uses_blender_game(screen->scene))
1415                 return 0;
1416
1417         return 1;
1418 }
1419
1420 static int game_engine_exec(bContext *C, wmOperator *op)
1421 {
1422 #ifdef WITH_GAMEENGINE
1423         Scene *startscene = CTX_data_scene(C);
1424         Main *bmain = CTX_data_main(C);
1425         ScrArea /* *sa, */ /* UNUSED */ *prevsa = CTX_wm_area(C);
1426         ARegion *ar, *prevar = CTX_wm_region(C);
1427         wmWindow *prevwin = CTX_wm_window(C);
1428         RegionView3D *rv3d;
1429         rcti cam_frame;
1430
1431         UNUSED_VARS(op);
1432
1433         /* bad context switch .. */
1434         if (!ED_view3d_context_activate(C))
1435                 return OPERATOR_CANCELLED;
1436
1437         /* redraw to hide any menus/popups, we don't go back to
1438          * the window manager until after this operator exits */
1439         WM_redraw_windows(C);
1440
1441         BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_PRE);
1442
1443         rv3d = CTX_wm_region_view3d(C);
1444         /* sa = CTX_wm_area(C); */ /* UNUSED */
1445         ar = CTX_wm_region(C);
1446
1447         view3d_operator_needs_opengl(C);
1448
1449         game_set_commmandline_options(&startscene->gm);
1450
1451         if ((rv3d->persp == RV3D_CAMOB) &&
1452             (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) &&
1453             (startscene->gm.stereoflag != STEREO_DOME))
1454         {
1455                 /* Letterbox */
1456                 rctf cam_framef;
1457                 ED_view3d_calc_camera_border(startscene, ar, CTX_wm_view3d(C), rv3d, &cam_framef, false);
1458                 cam_frame.xmin = cam_framef.xmin + ar->winrct.xmin;
1459                 cam_frame.xmax = cam_framef.xmax + ar->winrct.xmin;
1460                 cam_frame.ymin = cam_framef.ymin + ar->winrct.ymin;
1461                 cam_frame.ymax = cam_framef.ymax + ar->winrct.ymin;
1462                 BLI_rcti_isect(&ar->winrct, &cam_frame, &cam_frame);
1463         }
1464         else {
1465                 cam_frame.xmin = ar->winrct.xmin;
1466                 cam_frame.xmax = ar->winrct.xmax;
1467                 cam_frame.ymin = ar->winrct.ymin;
1468                 cam_frame.ymax = ar->winrct.ymax;
1469         }
1470
1471
1472         game_engine_save_state(C, prevwin);
1473
1474         StartKetsjiShell(C, ar, &cam_frame, 1);
1475
1476         /* window wasnt closed while the BGE was running */
1477         if (BLI_findindex(&CTX_wm_manager(C)->windows, prevwin) == -1) {
1478                 prevwin = NULL;
1479                 CTX_wm_window_set(C, NULL);
1480         }
1481
1482         ED_area_tag_redraw(CTX_wm_area(C));
1483
1484         if (prevwin) {
1485                 /* restore context, in case it changed in the meantime, for
1486                  * example by working in another window or closing it */
1487                 CTX_wm_region_set(C, prevar);
1488                 CTX_wm_window_set(C, prevwin);
1489                 CTX_wm_area_set(C, prevsa);
1490         }
1491
1492         game_engine_restore_state(C, prevwin);
1493
1494         //XXX restore_all_scene_cfra(scene_cfra_store);
1495         BKE_scene_set_background(CTX_data_main(C), startscene);
1496         //XXX BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, scene->lay);
1497
1498         BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_POST);
1499
1500         return OPERATOR_FINISHED;
1501 #else
1502         UNUSED_VARS(C);
1503         BKE_report(op->reports, RPT_ERROR, "Game engine is disabled in this build");
1504         return OPERATOR_CANCELLED;
1505 #endif
1506 }
1507
1508 void VIEW3D_OT_game_start(wmOperatorType *ot)
1509 {
1510         /* identifiers */
1511         ot->name = "Start Game Engine";
1512         ot->description = "Start game engine";
1513         ot->idname = "VIEW3D_OT_game_start";
1514
1515         /* api callbacks */
1516         ot->exec = game_engine_exec;
1517
1518         ot->poll = game_engine_poll;
1519 }
1520
1521 /** \} */