Gizmo: move transform to a persistent option
[blender.git] / source / blender / blenkernel / intern / scene.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24
25 #include <stddef.h>
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "MEM_guardedalloc.h"
30
31 #include "DNA_anim_types.h"
32 #include "DNA_collection_types.h"
33 #include "DNA_linestyle_types.h"
34 #include "DNA_mesh_types.h"
35 #include "DNA_node_types.h"
36 #include "DNA_object_types.h"
37 #include "DNA_rigidbody_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_screen_types.h"
40 #include "DNA_sequence_types.h"
41 #include "DNA_space_types.h"
42 #include "DNA_view3d_types.h"
43 #include "DNA_windowmanager_types.h"
44 #include "DNA_workspace_types.h"
45 #include "DNA_gpencil_types.h"
46
47 #include "BLI_math.h"
48 #include "BLI_blenlib.h"
49 #include "BLI_utildefines.h"
50 #include "BLI_callbacks.h"
51 #include "BLI_string.h"
52 #include "BLI_string_utils.h"
53 #include "BLI_threads.h"
54 #include "BLI_task.h"
55
56 #include "BLT_translation.h"
57
58 #include "BKE_anim.h"
59 #include "BKE_animsys.h"
60 #include "BKE_action.h"
61 #include "BKE_armature.h"
62 #include "BKE_cachefile.h"
63 #include "BKE_collection.h"
64 #include "BKE_colortools.h"
65 #include "BKE_editmesh.h"
66 #include "BKE_fcurve.h"
67 #include "BKE_freestyle.h"
68 #include "BKE_gpencil.h"
69 #include "BKE_icons.h"
70 #include "BKE_idprop.h"
71 #include "BKE_image.h"
72 #include "BKE_layer.h"
73 #include "BKE_library.h"
74 #include "BKE_library_remap.h"
75 #include "BKE_linestyle.h"
76 #include "BKE_main.h"
77 #include "BKE_mask.h"
78 #include "BKE_node.h"
79 #include "BKE_object.h"
80 #include "BKE_paint.h"
81 #include "BKE_rigidbody.h"
82 #include "BKE_scene.h"
83 #include "BKE_screen.h"
84 #include "BKE_sequencer.h"
85 #include "BKE_sound.h"
86 #include "BKE_unit.h"
87 #include "BKE_workspace.h"
88 #include "BKE_world.h"
89
90 #include "DEG_depsgraph.h"
91 #include "DEG_depsgraph_build.h"
92 #include "DEG_depsgraph_debug.h"
93 #include "DEG_depsgraph_query.h"
94
95 #include "RE_engine.h"
96
97 #include "engines/eevee/eevee_lightcache.h"
98
99 #include "PIL_time.h"
100
101 #include "IMB_colormanagement.h"
102 #include "IMB_imbuf.h"
103
104 #include "bmesh.h"
105
106 const char *RE_engine_id_BLENDER_EEVEE = "BLENDER_EEVEE";
107 const char *RE_engine_id_BLENDER_WORKBENCH = "BLENDER_WORKBENCH";
108 const char *RE_engine_id_CYCLES = "CYCLES";
109
110 void free_avicodecdata(AviCodecData *acd)
111 {
112         if (acd) {
113                 if (acd->lpFormat) {
114                         MEM_freeN(acd->lpFormat);
115                         acd->lpFormat = NULL;
116                         acd->cbFormat = 0;
117                 }
118                 if (acd->lpParms) {
119                         MEM_freeN(acd->lpParms);
120                         acd->lpParms = NULL;
121                         acd->cbParms = 0;
122                 }
123         }
124 }
125
126 static void remove_sequencer_fcurves(Scene *sce)
127 {
128         AnimData *adt = BKE_animdata_from_id(&sce->id);
129
130         if (adt && adt->action) {
131                 FCurve *fcu, *nextfcu;
132
133                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
134                         nextfcu = fcu->next;
135
136                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
137                                 action_groups_remove_channel(adt->action, fcu);
138                                 free_fcurve(fcu);
139                         }
140                 }
141         }
142 }
143
144 /* flag -- copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). */
145 ToolSettings *BKE_toolsettings_copy(ToolSettings *toolsettings, const int flag)
146 {
147         if (toolsettings == NULL) {
148                 return NULL;
149         }
150         ToolSettings *ts = MEM_dupallocN(toolsettings);
151         if (ts->vpaint) {
152                 ts->vpaint = MEM_dupallocN(ts->vpaint);
153                 BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, flag);
154         }
155         if (ts->wpaint) {
156                 ts->wpaint = MEM_dupallocN(ts->wpaint);
157                 BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, flag);
158         }
159         if (ts->sculpt) {
160                 ts->sculpt = MEM_dupallocN(ts->sculpt);
161                 BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, flag);
162         }
163         if (ts->uvsculpt) {
164                 ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
165                 BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, flag);
166         }
167         if (ts->gp_paint) {
168                 ts->gp_paint = MEM_dupallocN(ts->gp_paint);
169                 BKE_paint_copy(&ts->gp_paint->paint, &ts->gp_paint->paint, flag);
170         }
171
172         BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, flag);
173         ts->imapaint.paintcursor = NULL;
174         ts->particle.paintcursor = NULL;
175         ts->particle.scene = NULL;
176         ts->particle.object = NULL;
177
178         /* duplicate Grease Pencil interpolation curve */
179         ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
180         /* duplicate Grease Pencil multiframe fallof */
181         ts->gp_sculpt.cur_falloff = curvemapping_copy(ts->gp_sculpt.cur_falloff);
182         ts->gp_sculpt.cur_primitive = curvemapping_copy(ts->gp_sculpt.cur_primitive);
183         return ts;
184 }
185
186 void BKE_toolsettings_free(ToolSettings *toolsettings)
187 {
188         if (toolsettings == NULL) {
189                 return;
190         }
191         if (toolsettings->vpaint) {
192                 BKE_paint_free(&toolsettings->vpaint->paint);
193                 MEM_freeN(toolsettings->vpaint);
194         }
195         if (toolsettings->wpaint) {
196                 BKE_paint_free(&toolsettings->wpaint->paint);
197                 MEM_freeN(toolsettings->wpaint);
198         }
199         if (toolsettings->sculpt) {
200                 BKE_paint_free(&toolsettings->sculpt->paint);
201                 MEM_freeN(toolsettings->sculpt);
202         }
203         if (toolsettings->uvsculpt) {
204                 BKE_paint_free(&toolsettings->uvsculpt->paint);
205                 MEM_freeN(toolsettings->uvsculpt);
206         }
207         if (toolsettings->gp_paint) {
208                 BKE_paint_free(&toolsettings->gp_paint->paint);
209                 MEM_freeN(toolsettings->gp_paint);
210         }
211         BKE_paint_free(&toolsettings->imapaint.paint);
212
213         /* free Grease Pencil interpolation curve */
214         if (toolsettings->gp_interpolate.custom_ipo) {
215                 curvemapping_free(toolsettings->gp_interpolate.custom_ipo);
216         }
217         /* free Grease Pencil multiframe falloff curve */
218         if (toolsettings->gp_sculpt.cur_falloff) {
219                 curvemapping_free(toolsettings->gp_sculpt.cur_falloff);
220         }
221         if (toolsettings->gp_sculpt.cur_primitive) {
222                 curvemapping_free(toolsettings->gp_sculpt.cur_primitive);
223         }
224
225         MEM_freeN(toolsettings);
226 }
227
228 /**
229  * Only copy internal data of Scene ID from source to already allocated/initialized destination.
230  * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs.
231  *
232  * WARNING! This function will not handle ID user count!
233  *
234  * \param flag: Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
235  */
236 void BKE_scene_copy_data(Main *bmain, Scene *sce_dst, const Scene *sce_src, const int flag)
237 {
238         /* We never handle usercount here for own data. */
239         const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
240
241         sce_dst->ed = NULL;
242         sce_dst->depsgraph_hash = NULL;
243         sce_dst->fps_info = NULL;
244
245         /* Master Collection */
246         if (sce_src->master_collection) {
247                 sce_dst->master_collection = BKE_collection_copy_master(bmain, sce_src->master_collection, flag);
248         }
249
250         /* View Layers */
251         BLI_duplicatelist(&sce_dst->view_layers, &sce_src->view_layers);
252         for (ViewLayer *view_layer_src = sce_src->view_layers.first, *view_layer_dst = sce_dst->view_layers.first;
253              view_layer_src;
254              view_layer_src = view_layer_src->next, view_layer_dst = view_layer_dst->next)
255         {
256                 BKE_view_layer_copy_data(sce_dst, sce_src, view_layer_dst, view_layer_src, flag_subdata);
257         }
258
259         BLI_duplicatelist(&(sce_dst->markers), &(sce_src->markers));
260         BLI_duplicatelist(&(sce_dst->transform_spaces), &(sce_src->transform_spaces));
261         BLI_duplicatelist(&(sce_dst->r.views), &(sce_src->r.views));
262         BKE_keyingsets_copy(&(sce_dst->keyingsets), &(sce_src->keyingsets));
263
264         if (sce_src->nodetree) {
265                 /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
266                  *       (see BKE_libblock_copy_ex()). */
267                 BKE_id_copy_ex(bmain, (ID *)sce_src->nodetree, (ID **)&sce_dst->nodetree, flag);
268                 BKE_libblock_relink_ex(bmain, sce_dst->nodetree, (void *)(&sce_src->id), &sce_dst->id, false);
269         }
270
271         if (sce_src->rigidbody_world) {
272                 sce_dst->rigidbody_world = BKE_rigidbody_world_copy(sce_src->rigidbody_world, flag_subdata);
273         }
274
275         /* copy color management settings */
276         BKE_color_managed_display_settings_copy(&sce_dst->display_settings, &sce_src->display_settings);
277         BKE_color_managed_view_settings_copy(&sce_dst->view_settings, &sce_src->view_settings);
278         BKE_color_managed_colorspace_settings_copy(&sce_dst->sequencer_colorspace_settings, &sce_src->sequencer_colorspace_settings);
279
280         BKE_color_managed_display_settings_copy(&sce_dst->r.im_format.display_settings, &sce_src->r.im_format.display_settings);
281         BKE_color_managed_view_settings_copy(&sce_dst->r.im_format.view_settings, &sce_src->r.im_format.view_settings);
282
283         BKE_color_managed_display_settings_copy(&sce_dst->r.bake.im_format.display_settings, &sce_src->r.bake.im_format.display_settings);
284         BKE_color_managed_view_settings_copy(&sce_dst->r.bake.im_format.view_settings, &sce_src->r.bake.im_format.view_settings);
285
286         curvemapping_copy_data(&sce_dst->r.mblur_shutter_curve, &sce_src->r.mblur_shutter_curve);
287
288         /* tool settings */
289         sce_dst->toolsettings = BKE_toolsettings_copy(sce_dst->toolsettings, flag_subdata);
290
291         /* make a private copy of the avicodecdata */
292         if (sce_src->r.avicodecdata) {
293                 sce_dst->r.avicodecdata = MEM_dupallocN(sce_src->r.avicodecdata);
294                 sce_dst->r.avicodecdata->lpFormat = MEM_dupallocN(sce_dst->r.avicodecdata->lpFormat);
295                 sce_dst->r.avicodecdata->lpParms = MEM_dupallocN(sce_dst->r.avicodecdata->lpParms);
296         }
297
298         if (sce_src->r.ffcodecdata.properties) { /* intentionally check sce_dst not sce_src. */  /* XXX ??? comment outdated... */
299                 sce_dst->r.ffcodecdata.properties = IDP_CopyProperty_ex(sce_src->r.ffcodecdata.properties, flag_subdata);
300         }
301
302         /* before scene copy */
303         BKE_sound_create_scene(sce_dst);
304
305         /* Copy sequencer, this is local data! */
306         if (sce_src->ed) {
307                 sce_dst->ed = MEM_callocN(sizeof(*sce_dst->ed), __func__);
308                 sce_dst->ed->seqbasep = &sce_dst->ed->seqbase;
309                 BKE_sequence_base_dupli_recursive(
310                             sce_src, sce_dst, &sce_dst->ed->seqbase, &sce_src->ed->seqbase, SEQ_DUPE_ALL, flag_subdata);
311         }
312
313         if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
314                 BKE_previewimg_id_copy(&sce_dst->id, &sce_src->id);
315         }
316         else {
317                 sce_dst->preview = NULL;
318         }
319
320         sce_dst->eevee.light_cache = NULL;
321         sce_dst->eevee.light_cache_info[0] = '\0';
322         /* TODO Copy the cache. */
323 }
324
325 Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type)
326 {
327         Scene *sce_copy;
328
329         /* TODO this should/could most likely be replaced by call to more generic code at some point...
330          * But for now, let's keep it well isolated here. */
331         if (type == SCE_COPY_EMPTY) {
332                 ListBase rv;
333
334                 sce_copy = BKE_scene_add(bmain, sce->id.name + 2);
335
336                 rv = sce_copy->r.views;
337                 curvemapping_free_data(&sce_copy->r.mblur_shutter_curve);
338                 sce_copy->r = sce->r;
339                 sce_copy->r.views = rv;
340                 sce_copy->unit = sce->unit;
341                 sce_copy->physics_settings = sce->physics_settings;
342                 sce_copy->audio = sce->audio;
343                 sce_copy->eevee = sce->eevee;
344                 sce_copy->eevee.light_cache = NULL;
345                 sce_copy->eevee.light_cache_info[0] = '\0';
346
347                 if (sce->id.properties)
348                         sce_copy->id.properties = IDP_CopyProperty(sce->id.properties);
349
350                 MEM_freeN(sce_copy->toolsettings);
351                 BKE_sound_destroy_scene(sce_copy);
352
353                 /* copy color management settings */
354                 BKE_color_managed_display_settings_copy(&sce_copy->display_settings, &sce->display_settings);
355                 BKE_color_managed_view_settings_copy(&sce_copy->view_settings, &sce->view_settings);
356                 BKE_color_managed_colorspace_settings_copy(&sce_copy->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings);
357
358                 BKE_color_managed_display_settings_copy(&sce_copy->r.im_format.display_settings, &sce->r.im_format.display_settings);
359                 BKE_color_managed_view_settings_copy(&sce_copy->r.im_format.view_settings, &sce->r.im_format.view_settings);
360
361                 BKE_color_managed_display_settings_copy(&sce_copy->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings);
362                 BKE_color_managed_view_settings_copy(&sce_copy->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings);
363
364                 curvemapping_copy_data(&sce_copy->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
365
366                 /* viewport display settings */
367                 sce_copy->display = sce->display;
368
369                 /* tool settings */
370                 sce_copy->toolsettings = BKE_toolsettings_copy(sce->toolsettings, 0);
371
372                 /* make a private copy of the avicodecdata */
373                 if (sce->r.avicodecdata) {
374                         sce_copy->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
375                         sce_copy->r.avicodecdata->lpFormat = MEM_dupallocN(sce_copy->r.avicodecdata->lpFormat);
376                         sce_copy->r.avicodecdata->lpParms = MEM_dupallocN(sce_copy->r.avicodecdata->lpParms);
377                 }
378
379                 if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
380                         sce_copy->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
381                 }
382
383                 /* before scene copy */
384                 BKE_sound_create_scene(sce_copy);
385
386                 /* grease pencil */
387                 sce_copy->gpd = NULL;
388
389                 sce_copy->preview = NULL;
390
391                 return sce_copy;
392         }
393         else {
394                 BKE_id_copy_ex(bmain, (ID *)sce, (ID **)&sce_copy, LIB_ID_COPY_ACTIONS);
395                 id_us_min(&sce_copy->id);
396                 id_us_ensure_real(&sce_copy->id);
397
398                 /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks... */
399
400                 if (type == SCE_COPY_FULL) {
401                         /* Copy Freestyle LineStyle datablocks. */
402                         for (ViewLayer *view_layer_dst = sce_copy->view_layers.first; view_layer_dst; view_layer_dst = view_layer_dst->next) {
403                                 for (FreestyleLineSet *lineset = view_layer_dst->freestyle_config.linesets.first; lineset; lineset = lineset->next) {
404                                         if (lineset->linestyle) {
405                                                 id_us_min(&lineset->linestyle->id);
406                                                 BKE_id_copy_ex(
407                                                             bmain,
408                                                             (ID *)lineset->linestyle,
409                                                             (ID **)&lineset->linestyle,
410                                                             LIB_ID_COPY_ACTIONS);
411                                         }
412                                 }
413                         }
414
415                         /* Full copy of world (included animations) */
416                         if (sce_copy->world) {
417                                 id_us_min(&sce_copy->world->id);
418                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->world, (ID **)&sce_copy->world, LIB_ID_COPY_ACTIONS);
419                         }
420
421                         /* Full copy of GreasePencil. */
422                         if (sce_copy->gpd) {
423                                 id_us_min(&sce_copy->gpd->id);
424                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->gpd, (ID **)&sce_copy->gpd, LIB_ID_COPY_ACTIONS);
425                         }
426                 }
427                 else {
428                         /* Remove sequencer if not full copy */
429                         /* XXX Why in Hell? :/ */
430                         remove_sequencer_fcurves(sce_copy);
431                         BKE_sequencer_editing_free(sce_copy, true);
432                 }
433
434                 /* NOTE: part of SCE_COPY_FULL operations
435                  * are done outside of blenkernel with ED_object_single_users! */
436
437                 return sce_copy;
438         }
439 }
440
441 void BKE_scene_groups_relink(Scene *sce)
442 {
443         if (sce->rigidbody_world)
444                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
445 }
446
447 void BKE_scene_make_local(Main *bmain, Scene *sce, const bool lib_local)
448 {
449         /* For now should work, may need more work though to support all possible corner cases
450          * (also scene_copy probably needs some love). */
451         BKE_id_make_local_generic(bmain, &sce->id, true, lib_local);
452 }
453
454 /** Free (or release) any data used by this scene (does not free the scene itself). */
455 void BKE_scene_free_ex(Scene *sce, const bool do_id_user)
456 {
457         BKE_animdata_free((ID *)sce, false);
458
459         BKE_sequencer_editing_free(sce, do_id_user);
460
461         BKE_keyingsets_free(&sce->keyingsets);
462
463         /* is no lib link block, but scene extension */
464         if (sce->nodetree) {
465                 ntreeFreeNestedTree(sce->nodetree);
466                 MEM_freeN(sce->nodetree);
467                 sce->nodetree = NULL;
468         }
469
470         if (sce->rigidbody_world) {
471                 BKE_rigidbody_free_world(sce);
472         }
473
474         if (sce->r.avicodecdata) {
475                 free_avicodecdata(sce->r.avicodecdata);
476                 MEM_freeN(sce->r.avicodecdata);
477                 sce->r.avicodecdata = NULL;
478         }
479         if (sce->r.ffcodecdata.properties) {
480                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
481                 MEM_freeN(sce->r.ffcodecdata.properties);
482                 sce->r.ffcodecdata.properties = NULL;
483         }
484
485         BLI_freelistN(&sce->markers);
486         BLI_freelistN(&sce->transform_spaces);
487         BLI_freelistN(&sce->r.views);
488
489         BKE_toolsettings_free(sce->toolsettings);
490         sce->toolsettings = NULL;
491
492         BKE_scene_free_depsgraph_hash(sce);
493
494         MEM_SAFE_FREE(sce->fps_info);
495
496         BKE_sound_destroy_scene(sce);
497
498         BKE_color_managed_view_settings_free(&sce->view_settings);
499
500         BKE_previewimg_free(&sce->preview);
501         curvemapping_free_data(&sce->r.mblur_shutter_curve);
502
503         for (ViewLayer *view_layer = sce->view_layers.first, *view_layer_next; view_layer; view_layer = view_layer_next) {
504                 view_layer_next = view_layer->next;
505
506                 BLI_remlink(&sce->view_layers, view_layer);
507                 BKE_view_layer_free_ex(view_layer, do_id_user);
508         }
509
510         /* Master Collection */
511         // TODO: what to do with do_id_user? it's also true when just
512         // closing the file which seems wrong? should decrement users
513         // for objects directly in the master collection? then other
514         // collections in the scene need to do it too?
515         if (sce->master_collection) {
516                 BKE_collection_free(sce->master_collection);
517                 MEM_freeN(sce->master_collection);
518                 sce->master_collection = NULL;
519         }
520
521         if (sce->eevee.light_cache) {
522                 EEVEE_lightcache_free(sce->eevee.light_cache);
523                 sce->eevee.light_cache = NULL;
524         }
525
526         /* These are freed on doversion. */
527         BLI_assert(sce->layer_properties == NULL);
528 }
529
530 void BKE_scene_free(Scene *sce)
531 {
532         BKE_scene_free_ex(sce, true);
533 }
534
535 void BKE_scene_init(Scene *sce)
536 {
537         ParticleEditSettings *pset;
538         int a;
539         const char *colorspace_name;
540         SceneRenderView *srv;
541         CurveMapping *mblur_shutter_curve;
542
543         BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(sce, id));
544
545
546         sce->cursor.rotation_mode = ROT_MODE_XYZ;
547         sce->cursor.rotation_quaternion[0] = 1.0f;
548         sce->cursor.rotation_axis[1] = 1.0f;
549
550         sce->r.mode = R_OSA;
551         sce->r.cfra = 1;
552         sce->r.sfra = 1;
553         sce->r.efra = 250;
554         sce->r.frame_step = 1;
555         sce->r.xsch = 1920;
556         sce->r.ysch = 1080;
557         sce->r.xasp = 1;
558         sce->r.yasp = 1;
559         sce->r.tilex = 256;
560         sce->r.tiley = 256;
561         sce->r.size = 100;
562
563         sce->r.im_format.planes = R_IMF_PLANES_RGBA;
564         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
565         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
566         sce->r.im_format.quality = 90;
567         sce->r.im_format.compress = 15;
568
569         sce->r.displaymode = R_OUTPUT_WINDOW;
570         sce->r.framapto = 100;
571         sce->r.images = 100;
572         sce->r.framelen = 1.0;
573         sce->r.blurfac = 0.5;
574         sce->r.frs_sec = 24;
575         sce->r.frs_sec_base = 1;
576
577         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
578          *            images would look in the same way as in current blender
579          *
580          *            perhaps at some point should be completely deprecated?
581          */
582         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
583
584         sce->r.gauss = 1.5;
585         sce->r.dither_intensity = 1.0f;
586
587         sce->r.bake_mode = 0;
588         sce->r.bake_filter = 16;
589         sce->r.bake_flag = R_BAKE_CLEAR;
590         sce->r.bake_samples = 256;
591         sce->r.bake_biasdist = 0.001;
592
593         sce->r.bake.flag = R_BAKE_CLEAR;
594         sce->r.bake.pass_filter = R_BAKE_PASS_FILTER_ALL;
595         sce->r.bake.width = 512;
596         sce->r.bake.height = 512;
597         sce->r.bake.margin = 16;
598         sce->r.bake.normal_space = R_BAKE_SPACE_TANGENT;
599         sce->r.bake.normal_swizzle[0] = R_BAKE_POSX;
600         sce->r.bake.normal_swizzle[1] = R_BAKE_POSY;
601         sce->r.bake.normal_swizzle[2] = R_BAKE_POSZ;
602         BLI_strncpy(sce->r.bake.filepath, U.renderdir, sizeof(sce->r.bake.filepath));
603
604         sce->r.bake.im_format.planes = R_IMF_PLANES_RGBA;
605         sce->r.bake.im_format.imtype = R_IMF_IMTYPE_PNG;
606         sce->r.bake.im_format.depth = R_IMF_CHAN_DEPTH_8;
607         sce->r.bake.im_format.quality = 90;
608         sce->r.bake.im_format.compress = 15;
609
610         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
611         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME | R_STAMP_MEMORY;
612         sce->r.stamp_font_id = 12;
613         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
614         sce->r.fg_stamp[3] = 1.0f;
615         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
616         sce->r.bg_stamp[3] = 0.25f;
617
618         sce->r.seq_prev_type = OB_SOLID;
619         sce->r.seq_rend_type = OB_SOLID;
620         sce->r.seq_flag = 0;
621
622         sce->r.threads = 1;
623
624         sce->r.simplify_subsurf = 6;
625         sce->r.simplify_particles = 1.0f;
626
627         sce->r.border.xmin = 0.0f;
628         sce->r.border.ymin = 0.0f;
629         sce->r.border.xmax = 1.0f;
630         sce->r.border.ymax = 1.0f;
631
632         sce->r.preview_start_resolution = 64;
633
634         sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE;
635         sce->r.unit_line_thickness = 1.0f;
636
637         mblur_shutter_curve = &sce->r.mblur_shutter_curve;
638         curvemapping_set_defaults(mblur_shutter_curve, 1, 0.0f, 0.0f, 1.0f, 1.0f);
639         curvemapping_initialize(mblur_shutter_curve);
640         curvemap_reset(mblur_shutter_curve->cm,
641                        &mblur_shutter_curve->clipr,
642                        CURVE_PRESET_MAX,
643                        CURVEMAP_SLOPE_POS_NEG);
644
645         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
646
647         sce->toolsettings->object_flag |= SCE_OBJECT_MODE_LOCK;
648         sce->toolsettings->doublimit = 0.001;
649         sce->toolsettings->vgroup_weight = 1.0f;
650         sce->toolsettings->uvcalc_margin = 0.001f;
651         sce->toolsettings->uvcalc_flag = UVCALC_TRANSFORM_CORRECT;
652         sce->toolsettings->unwrapper = 1;
653         sce->toolsettings->select_thresh = 0.01f;
654
655         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
656         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
657         sce->toolsettings->autokey_mode = U.autokey_mode;
658
659
660         sce->toolsettings->transform_pivot_point = V3D_AROUND_CENTER_MEDIAN;
661         sce->toolsettings->snap_mode = SCE_SNAP_MODE_INCREMENT;
662         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
663         sce->toolsettings->snap_uv_mode = SCE_SNAP_MODE_INCREMENT;
664         sce->toolsettings->snap_transform_mode_flag = SCE_SNAP_TRANSFORM_MODE_TRANSLATE;
665
666         sce->toolsettings->curve_paint_settings.curve_type = CU_BEZIER;
667         sce->toolsettings->curve_paint_settings.flag |= CURVE_PAINT_FLAG_CORNERS_DETECT;
668         sce->toolsettings->curve_paint_settings.error_threshold = 8;
669         sce->toolsettings->curve_paint_settings.radius_max = 1.0f;
670         sce->toolsettings->curve_paint_settings.corner_angle = DEG2RADF(70.0f);
671
672         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
673         sce->toolsettings->statvis.overhang_min = 0;
674         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
675         sce->toolsettings->statvis.thickness_max = 0.1f;
676         sce->toolsettings->statvis.thickness_samples = 1;
677         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
678         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
679
680         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
681         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
682
683         sce->toolsettings->proportional_size = 1.0f;
684
685         sce->toolsettings->imapaint.paint.flags |= PAINT_SHOW_BRUSH;
686         sce->toolsettings->imapaint.normal_angle = 80;
687         sce->toolsettings->imapaint.seam_bleed = 2;
688
689         /* grease pencil multiframe falloff curve */
690         sce->toolsettings->gp_sculpt.cur_falloff = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
691         CurveMapping *gp_falloff_curve = sce->toolsettings->gp_sculpt.cur_falloff;
692         curvemapping_initialize(gp_falloff_curve);
693         curvemap_reset(
694                 gp_falloff_curve->cm,
695                 &gp_falloff_curve->clipr,
696                 CURVE_PRESET_GAUSS,
697                 CURVEMAP_SLOPE_POSITIVE);
698
699         sce->toolsettings->gp_sculpt.cur_primitive = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
700         CurveMapping *gp_primitive_curve = sce->toolsettings->gp_sculpt.cur_primitive;
701         curvemapping_initialize(gp_primitive_curve);
702         curvemap_reset(
703                 gp_primitive_curve->cm,
704                 &gp_primitive_curve->clipr,
705                 CURVE_PRESET_BELL,
706                 CURVEMAP_SLOPE_POSITIVE);
707
708         sce->toolsettings->gp_sculpt.guide.spacing = 20.0f;
709
710         sce->physics_settings.gravity[0] = 0.0f;
711         sce->physics_settings.gravity[1] = 0.0f;
712         sce->physics_settings.gravity[2] = -9.81f;
713         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
714
715         sce->unit.system = USER_UNIT_METRIC;
716         sce->unit.scale_length = 1.0f;
717         sce->unit.length_unit = bUnit_GetBaseUnitOfType(USER_UNIT_METRIC, B_UNIT_LENGTH);
718         sce->unit.mass_unit = bUnit_GetBaseUnitOfType(USER_UNIT_METRIC, B_UNIT_MASS);
719         sce->unit.time_unit = bUnit_GetBaseUnitOfType(USER_UNIT_METRIC, B_UNIT_TIME);
720
721         pset = &sce->toolsettings->particle;
722         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
723         pset->emitterdist = 0.25f;
724         pset->totrekey = 5;
725         pset->totaddkey = 5;
726         pset->brushtype = PE_BRUSH_COMB;
727         pset->draw_step = 2;
728         pset->fade_frames = 2;
729         pset->selectmode = SCE_SELECT_PATH;
730
731         for (a = 0; a < ARRAY_SIZE(pset->brush); a++) {
732                 pset->brush[a].strength = 0.5f;
733                 pset->brush[a].size = 50;
734                 pset->brush[a].step = 10;
735                 pset->brush[a].count = 10;
736         }
737         pset->brush[PE_BRUSH_CUT].strength = 1.0f;
738
739         sce->r.ffcodecdata.audio_mixrate = 48000;
740         sce->r.ffcodecdata.audio_volume = 1.0f;
741         sce->r.ffcodecdata.audio_bitrate = 192;
742         sce->r.ffcodecdata.audio_channels = 2;
743
744         BLI_strncpy(sce->r.engine, RE_engine_id_BLENDER_EEVEE, sizeof(sce->r.engine));
745
746         sce->audio.distance_model = 2.0f;
747         sce->audio.doppler_factor = 1.0f;
748         sce->audio.speed_of_sound = 343.3f;
749         sce->audio.volume = 1.0f;
750         sce->audio.flag = AUDIO_SYNC;
751
752         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
753
754         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
755         sce->r.osa = 8;
756
757         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
758
759         /* multiview - stereo */
760         BKE_scene_add_render_view(sce, STEREO_LEFT_NAME);
761         srv = sce->r.views.first;
762         BLI_strncpy(srv->suffix, STEREO_LEFT_SUFFIX, sizeof(srv->suffix));
763
764         BKE_scene_add_render_view(sce, STEREO_RIGHT_NAME);
765         srv = sce->r.views.last;
766         BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix));
767
768         BKE_sound_create_scene(sce);
769
770         /* color management */
771         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
772
773         BKE_color_managed_display_settings_init(&sce->display_settings);
774         BKE_color_managed_view_settings_init_render(&sce->view_settings,
775                                                     &sce->display_settings,
776                                                     "Filmic");
777         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
778                     sizeof(sce->sequencer_colorspace_settings.name));
779
780         /* Those next two sets (render and baking settings) are not currently in use,
781          * but are exposed to RNA API and hence must have valid data. */
782         BKE_color_managed_display_settings_init(&sce->r.im_format.display_settings);
783         BKE_color_managed_view_settings_init_render(&sce->r.im_format.view_settings,
784                                                     &sce->r.im_format.display_settings,
785                                                     "Filmic");
786
787         BKE_color_managed_display_settings_init(&sce->r.bake.im_format.display_settings);
788         BKE_color_managed_view_settings_init_render(&sce->r.bake.im_format.view_settings,
789                                                     &sce->r.bake.im_format.display_settings,
790                                                     "Filmic");
791
792         /* Safe Areas */
793         copy_v2_fl2(sce->safe_areas.title, 10.0f / 100.0f, 5.0f / 100.0f);
794         copy_v2_fl2(sce->safe_areas.action, 3.5f / 100.0f, 3.5f / 100.0f);
795         copy_v2_fl2(sce->safe_areas.title_center, 17.5f / 100.0f, 5.0f / 100.0f);
796         copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f);
797
798         sce->preview = NULL;
799
800         /* GP Sculpt brushes */
801         {
802                 GP_Sculpt_Settings *gset = &sce->toolsettings->gp_sculpt;
803                 GP_Sculpt_Data *gp_brush;
804                 float curcolor_add[3], curcolor_sub[3];
805                 ARRAY_SET_ITEMS(curcolor_add, 1.0f, 0.6f, 0.6f);
806                 ARRAY_SET_ITEMS(curcolor_sub, 0.6f, 0.6f, 1.0f);
807
808                 gp_brush = &gset->brush[GP_SCULPT_TYPE_SMOOTH];
809                 gp_brush->size = 25;
810                 gp_brush->strength = 0.3f;
811                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_SMOOTH_PRESSURE | GP_SCULPT_FLAG_ENABLE_CURSOR;
812                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
813                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
814
815                 gp_brush = &gset->brush[GP_SCULPT_TYPE_THICKNESS];
816                 gp_brush->size = 25;
817                 gp_brush->strength = 0.5f;
818                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
819                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
820                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
821
822                 gp_brush = &gset->brush[GP_SCULPT_TYPE_STRENGTH];
823                 gp_brush->size = 25;
824                 gp_brush->strength = 0.5f;
825                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
826                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
827                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
828
829                 gp_brush = &gset->brush[GP_SCULPT_TYPE_GRAB];
830                 gp_brush->size = 50;
831                 gp_brush->strength = 0.3f;
832                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
833                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
834                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
835
836                 gp_brush = &gset->brush[GP_SCULPT_TYPE_PUSH];
837                 gp_brush->size = 25;
838                 gp_brush->strength = 0.3f;
839                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
840                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
841                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
842
843                 gp_brush = &gset->brush[GP_SCULPT_TYPE_TWIST];
844                 gp_brush->size = 50;
845                 gp_brush->strength = 0.3f;
846                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
847                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
848                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
849
850                 gp_brush = &gset->brush[GP_SCULPT_TYPE_PINCH];
851                 gp_brush->size = 50;
852                 gp_brush->strength = 0.5f;
853                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
854                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
855                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
856
857                 gp_brush = &gset->brush[GP_SCULPT_TYPE_RANDOMIZE];
858                 gp_brush->size = 25;
859                 gp_brush->strength = 0.5f;
860                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
861                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
862                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
863         }
864
865         /* GP Stroke Placement */
866         sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE;
867         sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE;
868         sce->toolsettings->gpencil_seq_align = GP_PROJECT_VIEWSPACE;
869         sce->toolsettings->gpencil_ima_align = GP_PROJECT_VIEWSPACE;
870
871         /* Annotations */
872         sce->toolsettings->annotate_v3d_align = GP_PROJECT_VIEWSPACE | GP_PROJECT_CURSOR;
873         sce->toolsettings->annotate_thickness = 3;
874
875         for (int i = 0; i < ARRAY_SIZE(sce->orientation_slots); i++) {
876                 sce->orientation_slots[i].index_custom = -1;
877         }
878
879         /* Master Collection */
880         sce->master_collection = BKE_collection_master_add();
881
882         BKE_view_layer_add(sce, "View Layer");
883
884         /* SceneDisplay */
885         copy_v3_v3(sce->display.light_direction, (float[3]){M_SQRT1_3, M_SQRT1_3, M_SQRT1_3});
886         sce->display.shadow_shift = 0.1f;
887         sce->display.shadow_focus = 0.0f;
888
889         sce->display.matcap_ssao_distance = 0.2f;
890         sce->display.matcap_ssao_attenuation = 1.0f;
891         sce->display.matcap_ssao_samples = 16;
892
893         /* OpenGL Render. */
894         BKE_screen_view3d_shading_init(&sce->display.shading);
895
896         /* SceneEEVEE */
897         sce->eevee.gi_diffuse_bounces = 3;
898         sce->eevee.gi_cubemap_resolution = 512;
899         sce->eevee.gi_visibility_resolution = 32;
900         sce->eevee.gi_cubemap_draw_size = 0.3f;
901         sce->eevee.gi_irradiance_draw_size = 0.1f;
902         sce->eevee.gi_irradiance_smoothing = 0.1f;
903         sce->eevee.gi_filter_quality = 1.0f;
904
905         sce->eevee.taa_samples = 16;
906         sce->eevee.taa_render_samples = 64;
907
908         sce->eevee.sss_samples = 7;
909         sce->eevee.sss_jitter_threshold = 0.3f;
910
911         sce->eevee.ssr_quality = 0.25f;
912         sce->eevee.ssr_max_roughness = 0.5f;
913         sce->eevee.ssr_thickness = 0.2f;
914         sce->eevee.ssr_border_fade = 0.075f;
915         sce->eevee.ssr_firefly_fac = 10.0f;
916
917         sce->eevee.volumetric_start = 0.1f;
918         sce->eevee.volumetric_end = 100.0f;
919         sce->eevee.volumetric_tile_size = 8;
920         sce->eevee.volumetric_samples = 64;
921         sce->eevee.volumetric_sample_distribution = 0.8f;
922         sce->eevee.volumetric_light_clamp = 0.0f;
923         sce->eevee.volumetric_shadow_samples = 16;
924
925         sce->eevee.gtao_distance = 0.2f;
926         sce->eevee.gtao_factor = 1.0f;
927         sce->eevee.gtao_quality = 0.25f;
928
929         sce->eevee.bokeh_max_size = 100.0f;
930         sce->eevee.bokeh_threshold = 1.0f;
931
932         copy_v3_fl(sce->eevee.bloom_color, 1.0f);
933         sce->eevee.bloom_threshold = 0.8f;
934         sce->eevee.bloom_knee = 0.5f;
935         sce->eevee.bloom_intensity = 0.05f;
936         sce->eevee.bloom_radius = 6.5f;
937         sce->eevee.bloom_clamp = 0.0f;
938
939         sce->eevee.motion_blur_samples = 8;
940         sce->eevee.motion_blur_shutter = 0.5f;
941
942         sce->eevee.shadow_method = SHADOW_ESM;
943         sce->eevee.shadow_cube_size = 512;
944         sce->eevee.shadow_cascade_size = 1024;
945
946         sce->eevee.light_cache = NULL;
947         sce->eevee.light_threshold = 0.01f;
948
949         sce->eevee.overscan = 3.0f;
950
951         sce->eevee.flag =
952                 SCE_EEVEE_VOLUMETRIC_LIGHTS |
953                 SCE_EEVEE_GTAO_BENT_NORMALS |
954                 SCE_EEVEE_GTAO_BOUNCE |
955                 SCE_EEVEE_TAA_REPROJECTION |
956                 SCE_EEVEE_SSR_HALF_RESOLUTION;
957 }
958
959 Scene *BKE_scene_add(Main *bmain, const char *name)
960 {
961         Scene *sce;
962
963         sce = BKE_libblock_alloc(bmain, ID_SCE, name, 0);
964         id_us_min(&sce->id);
965         id_us_ensure_real(&sce->id);
966
967         BKE_scene_init(sce);
968
969         return sce;
970 }
971
972 /**
973  * Check if there is any instance of the object in the scene
974  */
975 bool BKE_scene_object_find(Scene *scene, Object *ob)
976 {
977         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
978                 if (BLI_findptr(&view_layer->object_bases, ob, offsetof(Base, object))) {
979                     return true;
980                 }
981         }
982         return false;
983 }
984
985 Object *BKE_scene_object_find_by_name(Scene *scene, const char *name)
986 {
987         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
988                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
989                         if (STREQ(base->object->id.name + 2, name)) {
990                                 return base->object;
991                         }
992                 }
993         }
994         return NULL;
995 }
996
997 /**
998  * Sets the active scene, mainly used when running in background mode (``--scene`` command line argument).
999  * This is also called to set the scene directly, bypassing windowing code.
1000  * Otherwise #WM_window_set_active_scene is used when changing scenes by the user.
1001  */
1002 void BKE_scene_set_background(Main *bmain, Scene *scene)
1003 {
1004         Object *ob;
1005
1006         /* check for cyclic sets, for reading old files but also for definite security (py?) */
1007         BKE_scene_validate_setscene(bmain, scene);
1008
1009         /* deselect objects (for dataselect) */
1010         for (ob = bmain->objects.first; ob; ob = ob->id.next)
1011                 ob->flag &= ~SELECT;
1012
1013         /* copy layers and flags from bases to objects */
1014         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
1015                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
1016                         ob = base->object;
1017                         /* collection patch... */
1018                         BKE_scene_object_base_flag_sync_from_base(base);
1019                 }
1020         }
1021         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
1022 }
1023
1024 /* called from creator_args.c */
1025 Scene *BKE_scene_set_name(Main *bmain, const char *name)
1026 {
1027         Scene *sce = (Scene *)BKE_libblock_find_name(bmain, ID_SCE, name);
1028         if (sce) {
1029                 BKE_scene_set_background(bmain, sce);
1030                 printf("Scene switch for render: '%s' in file: '%s'\n", name, BKE_main_blendfile_path(bmain));
1031                 return sce;
1032         }
1033
1034         printf("Can't find scene: '%s' in file: '%s'\n", name, BKE_main_blendfile_path(bmain));
1035         return NULL;
1036 }
1037
1038 /* Used by metaballs, return *all* objects (including duplis) existing in the scene (including scene's sets) */
1039 int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter,
1040         Scene **scene, int val, Base **base, Object **ob)
1041 {
1042         bool run_again = true;
1043
1044         /* init */
1045         if (val == 0) {
1046                 iter->phase = F_START;
1047                 iter->dupob = NULL;
1048                 iter->duplilist = NULL;
1049                 iter->dupli_refob = NULL;
1050         }
1051         else {
1052                 /* run_again is set when a duplilist has been ended */
1053                 while (run_again) {
1054                         run_again = false;
1055
1056                         /* the first base */
1057                         if (iter->phase == F_START) {
1058                                 ViewLayer *view_layer = (depsgraph) ?
1059                                         DEG_get_evaluated_view_layer(depsgraph) :
1060                                         BKE_view_layer_context_active_PLACEHOLDER(*scene);
1061                                 *base = view_layer->object_bases.first;
1062                                 if (*base) {
1063                                         *ob = (*base)->object;
1064                                         iter->phase = F_SCENE;
1065                                 }
1066                                 else {
1067                                         /* exception: empty scene layer */
1068                                         while ((*scene)->set) {
1069                                                 (*scene) = (*scene)->set;
1070                                                 ViewLayer *view_layer_set = BKE_view_layer_default_render((*scene));
1071                                                 if (view_layer_set->object_bases.first) {
1072                                                         *base = view_layer_set->object_bases.first;
1073                                                         *ob = (*base)->object;
1074                                                         iter->phase = F_SCENE;
1075                                                         break;
1076                                                 }
1077                                         }
1078                                 }
1079                         }
1080                         else {
1081                                 if (*base && iter->phase != F_DUPLI) {
1082                                         *base = (*base)->next;
1083                                         if (*base) {
1084                                                 *ob = (*base)->object;
1085                                         }
1086                                         else {
1087                                                 if (iter->phase == F_SCENE) {
1088                                                         /* (*scene) is finished, now do the set */
1089                                                         while ((*scene)->set) {
1090                                                                 (*scene) = (*scene)->set;
1091                                                                 ViewLayer *view_layer_set = BKE_view_layer_default_render((*scene));
1092                                                                 if (view_layer_set->object_bases.first) {
1093                                                                         *base = view_layer_set->object_bases.first;
1094                                                                         *ob = (*base)->object;
1095                                                                         break;
1096                                                                 }
1097                                                         }
1098                                                 }
1099                                         }
1100                                 }
1101                         }
1102
1103                         if (*base == NULL) {
1104                                 iter->phase = F_START;
1105                         }
1106                         else {
1107                                 if (iter->phase != F_DUPLI) {
1108                                         if (depsgraph && (*base)->object->transflag & OB_DUPLI) {
1109                                                 /* collections cannot be duplicated for metaballs yet,
1110                                                  * this enters eternal loop because of
1111                                                  * makeDispListMBall getting called inside of collection_duplilist */
1112                                                 if ((*base)->object->instance_collection == NULL) {
1113                                                         iter->duplilist = object_duplilist(depsgraph, (*scene), (*base)->object);
1114
1115                                                         iter->dupob = iter->duplilist->first;
1116
1117                                                         if (!iter->dupob) {
1118                                                                 free_object_duplilist(iter->duplilist);
1119                                                                 iter->duplilist = NULL;
1120                                                         }
1121                                                         iter->dupli_refob = NULL;
1122                                                 }
1123                                         }
1124                                 }
1125                                 /* handle dupli's */
1126                                 if (iter->dupob) {
1127                                         (*base)->flag_legacy |= OB_FROMDUPLI;
1128                                         *ob = iter->dupob->ob;
1129                                         iter->phase = F_DUPLI;
1130
1131                                         if (iter->dupli_refob != *ob) {
1132                                                 if (iter->dupli_refob) {
1133                                                         /* Restore previous object's real matrix. */
1134                                                         copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1135                                                 }
1136                                                 /* Backup new object's real matrix. */
1137                                                 iter->dupli_refob = *ob;
1138                                                 copy_m4_m4(iter->omat, iter->dupli_refob->obmat);
1139                                         }
1140                                         copy_m4_m4((*ob)->obmat, iter->dupob->mat);
1141
1142                                         iter->dupob = iter->dupob->next;
1143                                 }
1144                                 else if (iter->phase == F_DUPLI) {
1145                                         iter->phase = F_SCENE;
1146                                         (*base)->flag_legacy &= ~OB_FROMDUPLI;
1147
1148                                         if (iter->dupli_refob) {
1149                                                 /* Restore last object's real matrix. */
1150                                                 copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1151                                                 iter->dupli_refob = NULL;
1152                                         }
1153
1154                                         free_object_duplilist(iter->duplilist);
1155                                         iter->duplilist = NULL;
1156                                         run_again = true;
1157                                 }
1158                         }
1159                 }
1160         }
1161
1162         return iter->phase;
1163 }
1164
1165 Scene *BKE_scene_find_from_collection(const Main *bmain, const Collection *collection)
1166 {
1167         for (Scene *scene = bmain->scenes.first; scene; scene = scene->id.next) {
1168                 for (ViewLayer *layer = scene->view_layers.first; layer; layer = layer->next) {
1169                         if (BKE_view_layer_has_collection(layer, collection)) {
1170                                 return scene;
1171                         }
1172                 }
1173         }
1174
1175         return NULL;
1176 }
1177
1178 #ifdef DURIAN_CAMERA_SWITCH
1179 Object *BKE_scene_camera_switch_find(Scene *scene)
1180 {
1181         if (scene->r.mode & R_NO_CAMERA_SWITCH) {
1182                 return NULL;
1183         }
1184
1185         TimeMarker *m;
1186         int cfra = scene->r.cfra;
1187         int frame = -(MAXFRAME + 1);
1188         int min_frame = MAXFRAME + 1;
1189         Object *camera = NULL;
1190         Object *first_camera = NULL;
1191
1192         for (m = scene->markers.first; m; m = m->next) {
1193                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
1194                         if ((m->frame <= cfra) && (m->frame > frame)) {
1195                                 camera = m->camera;
1196                                 frame = m->frame;
1197
1198                                 if (frame == cfra)
1199                                         break;
1200                         }
1201
1202                         if (m->frame < min_frame) {
1203                                 first_camera = m->camera;
1204                                 min_frame = m->frame;
1205                         }
1206                 }
1207         }
1208
1209         if (camera == NULL) {
1210                 /* If there's no marker to the left of current frame,
1211                  * use camera from left-most marker to solve all sort
1212                  * of Schrodinger uncertainties.
1213                  */
1214                 return first_camera;
1215         }
1216
1217         return camera;
1218 }
1219 #endif
1220
1221 int BKE_scene_camera_switch_update(Scene *scene)
1222 {
1223 #ifdef DURIAN_CAMERA_SWITCH
1224         Object *camera = BKE_scene_camera_switch_find(scene);
1225         if (camera) {
1226                 scene->camera = camera;
1227                 DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE);
1228                 return 1;
1229         }
1230 #else
1231         (void)scene;
1232 #endif
1233         return 0;
1234 }
1235
1236 char *BKE_scene_find_marker_name(Scene *scene, int frame)
1237 {
1238         ListBase *markers = &scene->markers;
1239         TimeMarker *m1, *m2;
1240
1241         /* search through markers for match */
1242         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
1243                 if (m1->frame == frame)
1244                         return m1->name;
1245
1246                 if (m1 == m2)
1247                         break;
1248
1249                 if (m2->frame == frame)
1250                         return m2->name;
1251         }
1252
1253         return NULL;
1254 }
1255
1256 /* return the current marker for this frame,
1257  * we can have more than 1 marker per frame, this just returns the first :/ */
1258 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
1259 {
1260         TimeMarker *marker, *best_marker = NULL;
1261         int best_frame = -MAXFRAME * 2;
1262         for (marker = scene->markers.first; marker; marker = marker->next) {
1263                 if (marker->frame == frame) {
1264                         return marker->name;
1265                 }
1266
1267                 if (marker->frame > best_frame && marker->frame < frame) {
1268                         best_marker = marker;
1269                         best_frame = marker->frame;
1270                 }
1271         }
1272
1273         return best_marker ? best_marker->name : NULL;
1274 }
1275
1276 int BKE_scene_frame_snap_by_seconds(Scene *scene, double interval_in_seconds, int cfra)
1277 {
1278         const int fps = round_db_to_int(FPS * interval_in_seconds);
1279         const int second_prev = cfra - mod_i(cfra, fps);
1280         const int second_next = second_prev + fps;
1281         const int delta_prev = cfra - second_prev;
1282         const int delta_next = second_next - cfra;
1283         return (delta_prev < delta_next) ? second_prev : second_next;
1284 }
1285
1286 void BKE_scene_remove_rigidbody_object(struct Main *bmain, Scene *scene, Object *ob)
1287 {
1288         /* remove rigid body constraint from world before removing object */
1289         if (ob->rigidbody_constraint)
1290                 BKE_rigidbody_remove_constraint(scene, ob);
1291         /* remove rigid body object from world before removing object */
1292         if (ob->rigidbody_object)
1293                 BKE_rigidbody_remove_object(bmain, scene, ob);
1294 }
1295
1296 /* checks for cycle, returns 1 if it's all OK */
1297 bool BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1298 {
1299         Scene *sce_iter;
1300         int a, totscene;
1301
1302         if (sce->set == NULL) return true;
1303         totscene = BLI_listbase_count(&bmain->scenes);
1304
1305         for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) {
1306                 /* more iterations than scenes means we have a cycle */
1307                 if (a > totscene) {
1308                         /* the tested scene gets zero'ed, that's typically current scene */
1309                         sce->set = NULL;
1310                         return false;
1311                 }
1312         }
1313
1314         return true;
1315 }
1316
1317 /* This function is needed to cope with fractional frames - including two Blender rendering features
1318  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering.
1319  */
1320 float BKE_scene_frame_get(const Scene *scene)
1321 {
1322         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1323 }
1324
1325 /* This function is used to obtain arbitrary fractional frames */
1326 float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame)
1327 {
1328         float ctime = frame;
1329         ctime += scene->r.subframe;
1330         ctime *= scene->r.framelen;
1331
1332         return ctime;
1333 }
1334 /**
1335  * Sets the frame int/float components.
1336  */
1337 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1338 {
1339         double intpart;
1340         scene->r.subframe = modf(cfra, &intpart);
1341         scene->r.cfra = (int)intpart;
1342 }
1343
1344
1345 /* -------------------------------------------------------------------- */
1346 /** \name Scene Orientation Slots
1347  * \{ */
1348
1349 TransformOrientationSlot *BKE_scene_orientation_slot_get(Scene *scene, int slot_index)
1350 {
1351         if ((scene->orientation_slots[slot_index].flag & SELECT) == 0) {
1352                 slot_index = SCE_ORIENT_DEFAULT;
1353         }
1354         return &scene->orientation_slots[slot_index];
1355 }
1356
1357 TransformOrientationSlot *BKE_scene_orientation_slot_get_from_flag(Scene *scene, int flag)
1358 {
1359         BLI_assert(flag && !(flag & ~(V3D_GIZMO_TYPE_MASK_TRANSLATE | V3D_GIZMO_TYPE_MASK_ROTATE | V3D_GIZMO_TYPE_MASK_SCALE)));
1360         int slot_index = SCE_ORIENT_DEFAULT;
1361         if (flag & V3D_GIZMO_TYPE_MASK_TRANSLATE) {
1362                 slot_index = SCE_ORIENT_TRANSLATE;
1363         }
1364         else if (flag & V3D_GIZMO_TYPE_MASK_ROTATE) {
1365                 slot_index = SCE_ORIENT_ROTATE;
1366         }
1367         else if (flag & V3D_GIZMO_TYPE_MASK_SCALE) {
1368                 slot_index = SCE_ORIENT_SCALE;
1369         }
1370         return BKE_scene_orientation_slot_get(scene, slot_index);
1371 }
1372
1373 /**
1374  * Activate a transform orientation in a 3D view based on an enum value.
1375  *
1376  * \param orientation: If this is #V3D_ORIENT_CUSTOM or greater, the custom transform orientation
1377  * with index \a orientation - #V3D_ORIENT_CUSTOM gets activated.
1378  */
1379 void BKE_scene_orientation_slot_set_index(TransformOrientationSlot *orient_slot, int orientation)
1380 {
1381         const bool is_custom = orientation >= V3D_ORIENT_CUSTOM;
1382         orient_slot->type = is_custom ? V3D_ORIENT_CUSTOM : orientation;
1383         orient_slot->index_custom = is_custom ? (orientation - V3D_ORIENT_CUSTOM) : -1;
1384 }
1385
1386 int BKE_scene_orientation_slot_get_index(const TransformOrientationSlot *orient_slot)
1387 {
1388         return (orient_slot->type == V3D_ORIENT_CUSTOM) ? (orient_slot->type + orient_slot->index_custom) : orient_slot->type;
1389 }
1390
1391 /** \} */
1392
1393
1394 /* That's like really a bummer, because currently animation data for armatures
1395  * might want to use pose, and pose might be missing on the object.
1396  * This happens when changing visible layers, which leads to situations when
1397  * pose is missing or marked for recalc, animation will change it and then
1398  * object update will restore the pose.
1399  *
1400  * This could be solved by the new dependency graph, but for until then we'll
1401  * do an extra pass on the objects to ensure it's all fine.
1402  */
1403 #define POSE_ANIMATION_WORKAROUND
1404
1405 #ifdef POSE_ANIMATION_WORKAROUND
1406 static void scene_armature_depsgraph_workaround(Main *bmain, Depsgraph *depsgraph)
1407 {
1408         Object *ob;
1409         if (BLI_listbase_is_empty(&bmain->armatures) || !DEG_id_type_updated(depsgraph, ID_OB)) {
1410                 return;
1411         }
1412         for (ob = bmain->objects.first; ob; ob = ob->id.next) {
1413                 if (ob->type == OB_ARMATURE && ob->adt) {
1414                         if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
1415                                 BKE_pose_rebuild(bmain, ob, ob->data, true);
1416                         }
1417                 }
1418         }
1419 }
1420 #endif
1421
1422 static bool check_rendered_viewport_visible(Main *bmain)
1423 {
1424         wmWindowManager *wm = bmain->wm.first;
1425         wmWindow *window;
1426         for (window = wm->windows.first; window != NULL; window = window->next) {
1427                 const bScreen *screen = BKE_workspace_active_screen_get(window->workspace_hook);
1428                 Scene *scene = window->scene;
1429                 RenderEngineType *type = RE_engines_find(scene->r.engine);
1430
1431                 if (type->draw_engine || !type->render) {
1432                         continue;
1433                 }
1434
1435                 for (ScrArea *area = screen->areabase.first; area != NULL; area = area->next) {
1436                         View3D *v3d = area->spacedata.first;
1437                         if (area->spacetype != SPACE_VIEW3D) {
1438                                 continue;
1439                         }
1440                         if (v3d->shading.type == OB_RENDER) {
1441                                 return true;
1442                         }
1443                 }
1444         }
1445         return false;
1446 }
1447
1448 /* TODO(campbell): shouldn't we be able to use 'DEG_get_view_layer' here?
1449  * Currently this is NULL on load, so don't. */
1450 static void prepare_mesh_for_viewport_render(
1451         Main *bmain, const ViewLayer *view_layer)
1452 {
1453         /* This is needed to prepare mesh to be used by the render
1454          * engine from the viewport rendering. We do loading here
1455          * so all the objects which shares the same mesh datablock
1456          * are nicely tagged for update and updated.
1457          *
1458          * This makes it so viewport render engine doesn't need to
1459          * call loading of the edit data for the mesh objects.
1460          */
1461
1462         Object *obedit = OBEDIT_FROM_VIEW_LAYER(view_layer);
1463         if (obedit) {
1464                 Mesh *mesh = obedit->data;
1465                 if ((obedit->type == OB_MESH) &&
1466                     ((obedit->id.recalc & ID_RECALC_ALL) ||
1467                      (mesh->id.recalc & ID_RECALC_ALL)))
1468                 {
1469                         if (check_rendered_viewport_visible(bmain)) {
1470                                 BMesh *bm = mesh->edit_mesh->bm;
1471                                 BM_mesh_bm_to_me(
1472                                         bmain, bm, mesh,
1473                                         (&(struct BMeshToMeshParams){
1474                                             .calc_object_remap = true,
1475                                         }));
1476                                 DEG_id_tag_update(&mesh->id, 0);
1477                         }
1478                 }
1479         }
1480 }
1481
1482 /* TODO(sergey): This actually should become view_layer_graph or so.
1483  * Same applies to update_for_newframe.
1484  */
1485 void BKE_scene_graph_update_tagged(Depsgraph *depsgraph,
1486                                    Main *bmain)
1487 {
1488         Scene *scene = DEG_get_input_scene(depsgraph);
1489         ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1490
1491         bool run_callbacks = DEG_id_type_any_updated(depsgraph);
1492         if (run_callbacks) {
1493                 BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_DEPSGRAPH_UPDATE_PRE);
1494         }
1495
1496         /* TODO(sergey): Some functions here are changing global state,
1497          * for example, clearing update tags from bmain.
1498          */
1499         /* (Re-)build dependency graph if needed. */
1500         DEG_graph_relations_update(depsgraph, bmain, scene, view_layer);
1501         /* Uncomment this to check if graph was properly tagged for update. */
1502         // DEG_debug_graph_relations_validate(depsgraph, bmain, scene);
1503         /* Flush editing data if needed. */
1504         prepare_mesh_for_viewport_render(bmain, view_layer);
1505         /* Flush recalc flags to dependencies. */
1506         DEG_graph_flush_update(bmain, depsgraph);
1507         /* Update all objects: drivers, matrices, displists, etc. flags set
1508          * by depgraph or manual, no layer check here, gets correct flushed.
1509          */
1510         DEG_evaluate_on_refresh(depsgraph);
1511         /* Update sound system animation (TODO, move to depsgraph). */
1512         BKE_sound_update_scene(bmain, scene);
1513
1514         /* Notify python about depsgraph update */
1515         if (run_callbacks) {
1516                 BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_DEPSGRAPH_UPDATE_POST);
1517         }
1518         /* Inform editors about possible changes. */
1519         DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, false);
1520         /* Clear recalc flags. */
1521         DEG_ids_clear_recalc(bmain, depsgraph);
1522 }
1523
1524 /* applies changes right away, does all sets too */
1525 void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph,
1526                                          Main *bmain)
1527 {
1528         Scene *scene = DEG_get_input_scene(depsgraph);
1529         ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1530
1531         /* TODO(sergey): Some functions here are changing global state,
1532          * for example, clearing update tags from bmain.
1533          */
1534         const float ctime = BKE_scene_frame_get(scene);
1535         /* Keep this first. */
1536         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1537         /* Update animated image textures for particles, modifiers, gpu, etc,
1538          * call this at the start so modifiers with textures don't lag 1 frame.
1539          */
1540         BKE_image_editors_update_frame(bmain, scene->r.cfra);
1541         BKE_sound_set_cfra(scene->r.cfra);
1542         DEG_graph_relations_update(depsgraph, bmain, scene, view_layer);
1543         /* Update animated cache files for modifiers.
1544          *
1545          * TODO(sergey): Make this a depsgraph node?
1546          */
1547         BKE_cachefile_update_frame(bmain, depsgraph, scene, ctime,
1548                                    (((double)scene->r.frs_sec) / (double)scene->r.frs_sec_base));
1549 #ifdef POSE_ANIMATION_WORKAROUND
1550         scene_armature_depsgraph_workaround(bmain, depsgraph);
1551 #endif
1552         /* Update all objects: drivers, matrices, displists, etc. flags set
1553          * by depgraph or manual, no layer check here, gets correct flushed.
1554          */
1555         DEG_evaluate_on_framechange(bmain, depsgraph, ctime);
1556         /* Update sound system animation (TODO, move to depsgraph). */
1557         BKE_sound_update_scene(bmain, scene);
1558         /* Notify editors and python about recalc. */
1559         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1560         /* Inform editors about possible changes. */
1561         DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, true);
1562         /* clear recalc flags */
1563         DEG_ids_clear_recalc(bmain, depsgraph);
1564 }
1565
1566 /** Ensures given scene/view_layer pair has a valid, up-to-date depsgraph.
1567  *
1568  * \warning Sets matching depsgraph as active, so should only be called from the active editing context
1569  *          (usually, from operators).
1570  */
1571 void BKE_scene_view_layer_graph_evaluated_ensure(Main *bmain, Scene *scene, ViewLayer *view_layer)
1572 {
1573         Depsgraph *depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true);
1574         DEG_make_active(depsgraph);
1575         BKE_scene_graph_update_tagged(depsgraph, bmain);
1576 }
1577
1578 /* return default view */
1579 SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name)
1580 {
1581         SceneRenderView *srv;
1582
1583         if (!name)
1584                 name = DATA_("RenderView");
1585
1586         srv = MEM_callocN(sizeof(SceneRenderView), "new render view");
1587         BLI_strncpy(srv->name, name, sizeof(srv->name));
1588         BLI_uniquename(&sce->r.views, srv, DATA_("RenderView"), '.', offsetof(SceneRenderView, name), sizeof(srv->name));
1589         BLI_addtail(&sce->r.views, srv);
1590
1591         return srv;
1592 }
1593
1594 bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
1595 {
1596         const int act = BLI_findindex(&scene->r.views, srv);
1597
1598         if (act == -1) {
1599                 return false;
1600         }
1601         else if (scene->r.views.first == scene->r.views.last) {
1602                 /* ensure 1 view is kept */
1603                 return false;
1604         }
1605
1606         BLI_remlink(&scene->r.views, srv);
1607         MEM_freeN(srv);
1608
1609         scene->r.actview = 0;
1610
1611         return true;
1612 }
1613
1614 /* render simplification */
1615
1616 int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
1617 {
1618         if (r->mode & R_SIMPLIFY) {
1619                 if (for_render)
1620                         return min_ii(r->simplify_subsurf_render, lvl);
1621                 else
1622                         return min_ii(r->simplify_subsurf, lvl);
1623         }
1624         else {
1625                 return lvl;
1626         }
1627 }
1628
1629 int get_render_child_particle_number(const RenderData *r, int num, bool for_render)
1630 {
1631         if (r->mode & R_SIMPLIFY) {
1632                 if (for_render)
1633                         return (int)(r->simplify_particles_render * num);
1634                 else
1635                         return (int)(r->simplify_particles * num);
1636         }
1637         else {
1638                 return num;
1639         }
1640 }
1641
1642 /**
1643  * Helper function for the SETLOOPER and SETLOOPER_VIEW_LAYER macros
1644  *
1645  * It iterates over the bases of the active layer and then the bases
1646  * of the active layer of the background (set) scenes recursively.
1647  */
1648 Base *_setlooper_base_step(Scene **sce_iter, ViewLayer *view_layer, Base *base)
1649 {
1650         if (base && base->next) {
1651                 /* Common case, step to the next. */
1652                 return base->next;
1653         }
1654         else if ((base == NULL) && (view_layer != NULL)) {
1655                 /* First time looping, return the scenes first base. */
1656                 /* For the first loop we should get the layer from workspace when available. */
1657                 if (view_layer->object_bases.first) {
1658                         return (Base *)view_layer->object_bases.first;
1659                 }
1660                 /* No base on this scene layer. */
1661                 goto next_set;
1662         }
1663         else {
1664 next_set:
1665                 /* Reached the end, get the next base in the set. */
1666                 while ((*sce_iter = (*sce_iter)->set)) {
1667                         ViewLayer *view_layer_set = BKE_view_layer_default_render((*sce_iter));
1668                         base = (Base *)view_layer_set->object_bases.first;
1669
1670                         if (base) {
1671                                 return base;
1672                         }
1673                 }
1674         }
1675
1676         return NULL;
1677 }
1678
1679 bool BKE_scene_use_shading_nodes_custom(Scene *scene)
1680 {
1681         RenderEngineType *type = RE_engines_find(scene->r.engine);
1682         return (type && type->flag & RE_USE_SHADING_NODES_CUSTOM);
1683 }
1684
1685 bool BKE_scene_use_spherical_stereo(Scene *scene)
1686 {
1687         RenderEngineType *type = RE_engines_find(scene->r.engine);
1688         return (type && type->flag & RE_USE_SPHERICAL_STEREO);
1689 }
1690
1691 bool BKE_scene_uses_blender_eevee(const Scene *scene)
1692 {
1693         return STREQ(scene->r.engine, RE_engine_id_BLENDER_EEVEE);
1694 }
1695
1696 bool BKE_scene_uses_blender_workbench(const Scene *scene)
1697 {
1698         return STREQ(scene->r.engine, RE_engine_id_BLENDER_WORKBENCH);
1699 }
1700
1701 bool BKE_scene_uses_cycles(const Scene *scene)
1702 {
1703         return STREQ(scene->r.engine, RE_engine_id_CYCLES);
1704 }
1705
1706 void BKE_scene_base_flag_to_objects(ViewLayer *view_layer)
1707 {
1708         Base *base = view_layer->object_bases.first;
1709
1710         while (base) {
1711                 BKE_scene_object_base_flag_sync_from_base(base);
1712                 base = base->next;
1713         }
1714 }
1715
1716 void BKE_scene_object_base_flag_sync_from_base(Base *base)
1717 {
1718         Object *ob = base->object;
1719
1720         ob->flag = base->flag;
1721
1722         if ((base->flag & BASE_SELECTED) != 0) {
1723                 ob->flag |= SELECT;
1724         }
1725         else {
1726                 ob->flag &= ~SELECT;
1727         }
1728 }
1729
1730 void BKE_scene_object_base_flag_sync_from_object(Base *base)
1731 {
1732         Object *ob = base->object;
1733         base->flag = ob->flag;
1734
1735         if ((ob->flag & SELECT) != 0 && (base->flag & BASE_SELECTABLE) != 0) {
1736                 base->flag |= BASE_SELECTED;
1737         }
1738         else {
1739                 base->flag &= ~BASE_SELECTED;
1740         }
1741 }
1742
1743 void BKE_scene_disable_color_management(Scene *scene)
1744 {
1745         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1746         ColorManagedViewSettings *view_settings = &scene->view_settings;
1747         const char *view;
1748         const char *none_display_name;
1749
1750         none_display_name = IMB_colormanagement_display_get_none_name();
1751
1752         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
1753
1754         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1755
1756         if (view) {
1757                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1758         }
1759 }
1760
1761 bool BKE_scene_check_color_management_enabled(const Scene *scene)
1762 {
1763         return !STREQ(scene->display_settings.display_device, "None");
1764 }
1765
1766 bool BKE_scene_check_rigidbody_active(const Scene *scene)
1767 {
1768         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1769 }
1770
1771 int BKE_render_num_threads(const RenderData *rd)
1772 {
1773         int threads;
1774
1775         /* override set from command line? */
1776         threads = BLI_system_num_threads_override_get();
1777
1778         if (threads > 0)
1779                 return threads;
1780
1781         /* fixed number of threads specified in scene? */
1782         if (rd->mode & R_FIXED_THREADS)
1783                 threads = rd->threads;
1784         else
1785                 threads = BLI_system_thread_count();
1786
1787         return max_ii(threads, 1);
1788 }
1789
1790 int BKE_scene_num_threads(const Scene *scene)
1791 {
1792         return BKE_render_num_threads(&scene->r);
1793 }
1794
1795 int BKE_render_preview_pixel_size(const RenderData *r)
1796 {
1797         if (r->preview_pixel_size == 0) {
1798                 return (U.pixelsize > 1.5f) ? 2 : 1;
1799         }
1800         return r->preview_pixel_size;
1801 }
1802
1803 /* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently)
1804  * and unit->scale_length.
1805  */
1806 double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value)
1807 {
1808         if (unit->system == USER_UNIT_NONE) {
1809                 /* Never apply scale_length when not using a unit setting! */
1810                 return value;
1811         }
1812
1813         switch (unit_type) {
1814                 case B_UNIT_LENGTH:
1815                         return value * (double)unit->scale_length;
1816                 case B_UNIT_AREA:
1817                 case B_UNIT_POWER:
1818                         return value * pow(unit->scale_length, 2);
1819                 case B_UNIT_VOLUME:
1820                         return value * pow(unit->scale_length, 3);
1821                 case B_UNIT_MASS:
1822                         return value * pow(unit->scale_length, 3);
1823                 case B_UNIT_CAMERA:  /* *Do not* use scene's unit scale for camera focal lens! See T42026. */
1824                 default:
1825                         return value;
1826         }
1827 }
1828
1829 /******************** multiview *************************/
1830
1831 int BKE_scene_multiview_num_views_get(const RenderData *rd)
1832 {
1833         SceneRenderView *srv;
1834         int totviews = 0;
1835
1836         if ((rd->scemode & R_MULTIVIEW) == 0)
1837                 return 1;
1838
1839         if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
1840                 srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1841                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1842                         totviews++;
1843                 }
1844
1845                 srv = BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1846                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1847                         totviews++;
1848                 }
1849         }
1850         else {
1851                 for (srv = rd->views.first; srv; srv = srv->next) {
1852                         if ((srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1853                                 totviews++;
1854                         }
1855                 }
1856         }
1857         return totviews;
1858 }
1859
1860 bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
1861 {
1862         SceneRenderView *srv[2];
1863
1864         if ((rd->scemode & R_MULTIVIEW) == 0)
1865                 return false;
1866
1867         srv[0] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1868         srv[1] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1869
1870         return (srv[0] && ((srv[0]->viewflag & SCE_VIEW_DISABLE) == 0) &&
1871                 srv[1] && ((srv[1]->viewflag & SCE_VIEW_DISABLE) == 0));
1872 }
1873
1874 /* return whether to render this SceneRenderView */
1875 bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
1876 {
1877         if (srv == NULL)
1878                 return false;
1879
1880         if ((rd->scemode & R_MULTIVIEW) == 0)
1881                 return false;
1882
1883         if ((srv->viewflag & SCE_VIEW_DISABLE))
1884                 return false;
1885
1886         if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW)
1887                 return true;
1888
1889         /* SCE_VIEWS_SETUP_BASIC */
1890         if (STREQ(srv->name, STEREO_LEFT_NAME) ||
1891             STREQ(srv->name, STEREO_RIGHT_NAME))
1892         {
1893                 return true;
1894         }
1895
1896         return false;
1897 }
1898
1899 /* return true if viewname is the first or if the name is NULL or not found */
1900 bool BKE_scene_multiview_is_render_view_first(const RenderData *rd, const char *viewname)
1901 {
1902         SceneRenderView *srv;
1903
1904         if ((rd->scemode & R_MULTIVIEW) == 0)
1905                 return true;
1906
1907         if ((!viewname) || (!viewname[0]))
1908                 return true;
1909
1910         for (srv = rd->views.first; srv; srv = srv->next) {
1911                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1912                         return STREQ(viewname, srv->name);
1913                 }
1914         }
1915
1916         return true;
1917 }
1918
1919 /* return true if viewname is the last or if the name is NULL or not found */
1920 bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *viewname)
1921 {
1922         SceneRenderView *srv;
1923
1924         if ((rd->scemode & R_MULTIVIEW) == 0)
1925                 return true;
1926
1927         if ((!viewname) || (!viewname[0]))
1928                 return true;
1929
1930         for (srv = rd->views.last; srv; srv = srv->prev) {
1931                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1932                         return STREQ(viewname, srv->name);
1933                 }
1934         }
1935
1936         return true;
1937 }
1938
1939 SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, const int view_id)
1940 {
1941         SceneRenderView *srv;
1942         size_t nr;
1943
1944         if ((rd->scemode & R_MULTIVIEW) == 0)
1945                 return NULL;
1946
1947         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
1948                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1949                         if (nr++ == view_id)
1950                                 return srv;
1951                 }
1952         }
1953         return srv;
1954 }
1955
1956 const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const int view_id)
1957 {
1958         SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id);
1959
1960         if (srv)
1961                 return srv->name;
1962         else
1963                 return "";
1964 }
1965
1966 int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
1967 {
1968         SceneRenderView *srv;
1969         size_t nr;
1970
1971         if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0))
1972                 return 0;
1973
1974         if ((!viewname) || (!viewname[0]))
1975                 return 0;
1976
1977         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
1978                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1979                         if (STREQ(viewname, srv->name)) {
1980                                 return nr;
1981                         }
1982                         else {
1983                                 nr += 1;
1984                         }
1985                 }
1986         }
1987
1988         return 0;
1989 }
1990
1991 void BKE_scene_multiview_filepath_get(
1992         SceneRenderView *srv, const char *filepath,
1993         char *r_filepath)
1994 {
1995         BLI_strncpy(r_filepath, filepath, FILE_MAX);
1996         BLI_path_suffix(r_filepath, FILE_MAX, srv->suffix, "");
1997 }
1998
1999 /**
2000  * When multiview is not used the filepath is as usual (e.g., ``Image.jpg``).
2001  * When multiview is on, even if only one view is enabled the view is incorporated
2002  * into the file name (e.g., ``Image_L.jpg``). That allows for the user to re-render
2003  * individual views.
2004  */
2005 void BKE_scene_multiview_view_filepath_get(
2006         const RenderData *rd, const char *filepath, const char *viewname,
2007         char *r_filepath)
2008 {
2009         SceneRenderView *srv;
2010         char suffix[FILE_MAX];
2011
2012         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2013         if (srv)
2014                 BLI_strncpy(suffix, srv->suffix, sizeof(suffix));
2015         else
2016                 BLI_strncpy(suffix, viewname, sizeof(suffix));
2017
2018         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2019         BLI_path_suffix(r_filepath, FILE_MAX, suffix, "");
2020 }
2021
2022 const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char *viewname)
2023 {
2024         SceneRenderView *srv;
2025
2026         if ((viewname == NULL) || (viewname[0] == '\0'))
2027                 return viewname;
2028
2029         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2030         if (srv)
2031                 return srv->suffix;
2032         else
2033                 return viewname;
2034 }
2035
2036 const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id)
2037 {
2038         if ((rd->scemode & R_MULTIVIEW) == 0) {
2039                 return "";
2040         }
2041         else {
2042                 const char *viewname = BKE_scene_multiview_render_view_name_get(rd, view_id);
2043                 return BKE_scene_multiview_view_suffix_get(rd, viewname);
2044         }
2045 }
2046
2047 void BKE_scene_multiview_view_prefix_get(Scene *scene, const char *name, char *rprefix, const char **rext)
2048 {
2049         SceneRenderView *srv;
2050         size_t index_act;
2051         const char *suf_act;
2052         const char delims[] = {'.', '\0'};
2053
2054         rprefix[0] = '\0';
2055
2056         /* begin of extension */
2057         index_act = BLI_str_rpartition(name, delims, rext, &suf_act);
2058         if (*rext == NULL)
2059                 return;
2060         BLI_assert(index_act > 0);
2061         UNUSED_VARS_NDEBUG(index_act);
2062
2063         for (srv = scene->r.views.first; srv; srv = srv->next) {
2064                 if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
2065                         size_t len = strlen(srv->suffix);
2066                         if (strlen(*rext) >= len && STREQLEN(*rext - len, srv->suffix, len)) {
2067                                 BLI_strncpy(rprefix, name, strlen(name) - strlen(*rext) - len + 1);
2068                                 break;
2069                         }
2070                 }
2071         }
2072 }
2073
2074 void BKE_scene_multiview_videos_dimensions_get(
2075         const RenderData *rd, const size_t width, const size_t height,
2076         size_t *r_width, size_t *r_height)
2077 {
2078         if ((rd->scemode & R_MULTIVIEW) &&
2079             rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D)
2080         {
2081                 IMB_stereo3d_write_dimensions(
2082                         rd->im_format.stereo3d_format.display_mode,
2083                         (rd->im_format.stereo3d_format.flag & S3D_SQUEEZED_FRAME) != 0,
2084                         width, height,
2085                         r_width, r_height);
2086         }
2087         else {
2088                 *r_width = width;
2089                 *r_height = height;
2090         }
2091 }
2092
2093 int BKE_scene_multiview_num_videos_get(const RenderData *rd)
2094 {
2095         if (BKE_imtype_is_movie(rd->im_format.imtype) == false)
2096                 return 0;
2097
2098         if ((rd->scemode & R_MULTIVIEW) == 0)
2099                 return 1;
2100
2101         if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2102                 return 1;
2103         }
2104         else {
2105                 /* R_IMF_VIEWS_INDIVIDUAL */
2106                 return BKE_scene_multiview_num_views_get(rd);
2107         }
2108 }
2109
2110 /* Manipulation of depsgraph storage. */
2111
2112 /* This is a key which identifies depsgraph. */
2113 typedef struct DepsgraphKey {
2114         ViewLayer *view_layer;
2115         /* TODO(sergey): Need to include window somehow (same layer might be in a
2116          * different states in different windows).
2117          */
2118 } DepsgraphKey;
2119
2120 static unsigned int depsgraph_key_hash(const void *key_v)
2121 {
2122         const DepsgraphKey *key = key_v;
2123         unsigned int hash = BLI_ghashutil_ptrhash(key->view_layer);
2124         /* TODO(sergey): Include hash from other fields in the key. */
2125         return hash;
2126 }
2127
2128 static bool depsgraph_key_compare(const void *key_a_v, const void *key_b_v)
2129 {
2130         const DepsgraphKey *key_a = key_a_v;
2131         const DepsgraphKey *key_b = key_b_v;
2132         /* TODO(sergey): Compare rest of  */
2133         return !(key_a->view_layer == key_b->view_layer);
2134 }
2135
2136 static void depsgraph_key_free(void *key_v)
2137 {
2138         DepsgraphKey *key = key_v;
2139         MEM_freeN(key);
2140 }
2141
2142 static void depsgraph_key_value_free(void *value)
2143 {
2144         Depsgraph *depsgraph = value;
2145         DEG_graph_free(depsgraph);
2146 }
2147
2148 void BKE_scene_allocate_depsgraph_hash(Scene *scene)
2149 {
2150         scene->depsgraph_hash = BLI_ghash_new(depsgraph_key_hash,
2151                                               depsgraph_key_compare,
2152                                               "Scene Depsgraph Hash");
2153 }
2154
2155 void BKE_scene_ensure_depsgraph_hash(Scene *scene)
2156 {
2157         if (scene->depsgraph_hash == NULL) {
2158                 BKE_scene_allocate_depsgraph_hash(scene);
2159         }
2160 }
2161
2162 void BKE_scene_free_depsgraph_hash(Scene *scene)
2163 {
2164         if (scene->depsgraph_hash == NULL) {
2165                 return;
2166         }
2167         BLI_ghash_free(scene->depsgraph_hash,
2168                        depsgraph_key_free,
2169                        depsgraph_key_value_free);
2170 }
2171
2172 /* Query depsgraph for a specific contexts. */
2173
2174 Depsgraph *BKE_scene_get_depsgraph(Scene *scene,
2175                                    ViewLayer *view_layer,
2176                                    bool allocate)
2177 {
2178         BLI_assert(scene != NULL);
2179         BLI_assert(view_layer != NULL);
2180         /* Make sure hash itself exists. */
2181         if (allocate) {
2182                 BKE_scene_ensure_depsgraph_hash(scene);
2183         }
2184         if (scene->depsgraph_hash == NULL) {
2185                 return NULL;
2186         }
2187         /* Either ensure item is in the hash or simply return NULL if it's not,
2188          * depending on whether caller wants us to create depsgraph or not.
2189          */
2190         DepsgraphKey key;
2191         key.view_layer = view_layer;
2192         Depsgraph *depsgraph;
2193         if (allocate) {
2194                 DepsgraphKey **key_ptr;
2195                 Depsgraph **depsgraph_ptr;
2196                 if (!BLI_ghash_ensure_p_ex(scene->depsgraph_hash,
2197                                            &key,
2198                                            (void ***)&key_ptr,
2199                                            (void ***)&depsgraph_ptr))
2200                 {
2201                         *key_ptr = MEM_mallocN(sizeof(DepsgraphKey), __func__);
2202                         **key_ptr = key;
2203                         *depsgraph_ptr = DEG_graph_new(scene, view_layer, DAG_EVAL_VIEWPORT);
2204                         /* TODO(sergey): Would be cool to avoid string format print,
2205                          * but is a bit tricky because we can't know in advance  whether
2206                          * we will ever enable debug messages for this depsgraph.
2207                          */
2208                         char name[1024];
2209                         BLI_snprintf(name, sizeof(name), "%s :: %s", scene->id.name, view_layer->name);
2210                         DEG_debug_name_set(*depsgraph_ptr, name);
2211                 }
2212                 depsgraph = *depsgraph_ptr;
2213         }
2214         else {
2215                 depsgraph = BLI_ghash_lookup(scene->depsgraph_hash, &key);
2216         }
2217         return depsgraph;
2218 }
2219
2220 /* -------------------------------------------------------------------- */
2221 /** \name Scene Orientation
2222  * \{ */
2223
2224 void BKE_scene_transform_orientation_remove(
2225         Scene *scene, TransformOrientation *orientation)
2226 {
2227         const int orientation_index = BKE_scene_transform_orientation_get_index(scene, orientation);
2228
2229         for (int i = 0; i < ARRAY_SIZE(scene->orientation_slots); i++) {
2230                 TransformOrientationSlot *orient_slot = &scene->orientation_slots[i];
2231                 if (orient_slot->index_custom == orientation_index) {
2232                         /* could also use orientation_index-- */
2233                         orient_slot->type = V3D_ORIENT_GLOBAL;
2234                         orient_slot->index_custom = -1;
2235                 }
2236         }
2237
2238         BLI_freelinkN(&scene->transform_spaces, orientation);
2239 }
2240
2241 TransformOrientation *BKE_scene_transform_orientation_find(
2242         const Scene *scene, const int index)
2243 {
2244         return BLI_findlink(&scene->transform_spaces, index);
2245 }
2246
2247 /**
2248  * \return the index that \a orientation has within \a scene's transform-orientation list or -1 if not found.
2249  */
2250 int BKE_scene_transform_orientation_get_index(
2251         const Scene *scene, const TransformOrientation *orientation)
2252 {
2253         return BLI_findindex(&scene->transform_spaces, orientation);
2254 }
2255
2256 /** \} */
2257
2258
2259 /* -------------------------------------------------------------------- */
2260 /** \name Scene Cursor Rotation
2261  *
2262  * Matches #BKE_object_rot_to_mat3 and #BKE_object_mat3_to_rot.
2263  * \{ */
2264
2265 void BKE_scene_cursor_rot_to_mat3(const View3DCursor *cursor, float mat[3][3])
2266 {
2267         if (cursor->rotation_mode > 0) {
2268                 eulO_to_mat3(mat, cursor->rotation_euler, cursor->rotation_mode);
2269         }
2270         else if (cursor->rotation_mode == ROT_MODE_AXISANGLE) {
2271                 axis_angle_to_mat3(mat, cursor->rotation_axis, cursor->rotation_angle);
2272         }
2273         else {
2274                 float tquat[4];
2275                 normalize_qt_qt(tquat, cursor->rotation_quaternion);
2276                 quat_to_mat3(mat, tquat);
2277         }
2278 }
2279
2280 void BKE_scene_cursor_rot_to_quat(const View3DCursor *cursor, float quat[4])
2281 {
2282         if (cursor->rotation_mode > 0) {
2283                 eulO_to_quat(quat, cursor->rotation_euler, cursor->rotation_mode);
2284         }
2285         else if (cursor->rotation_mode == ROT_MODE_AXISANGLE) {
2286                 axis_angle_to_quat(quat, cursor->rotation_axis, cursor->rotation_angle);
2287         }
2288         else {
2289                 normalize_qt_qt(quat, cursor->rotation_quaternion);
2290         }
2291 }
2292
2293 void BKE_scene_cursor_mat3_to_rot(View3DCursor *cursor, const float mat[3][3], bool use_compat)
2294 {
2295         BLI_ASSERT_UNIT_M3(mat);
2296
2297         switch (cursor->rotation_mode) {
2298                 case ROT_MODE_QUAT:
2299                 {
2300                         mat3_normalized_to_quat(cursor->rotation_quaternion, mat);
2301                         break;
2302                 }
2303                 case ROT_MODE_AXISANGLE:
2304                 {
2305                         mat3_to_axis_angle(cursor->rotation_axis, &cursor->rotation_angle, mat);
2306                         break;
2307                 }
2308                 default:
2309                 {
2310                         if (use_compat) {
2311                                 mat3_to_compatible_eulO(cursor->rotation_euler, cursor->rotation_euler, cursor->rotation_mode, mat);
2312                         }
2313                         else {
2314                                 mat3_to_eulO(cursor->rotation_euler, cursor->rotation_mode, mat);
2315                         }
2316                         break;
2317                 }
2318         }
2319 }
2320
2321 void BKE_scene_cursor_quat_to_rot(View3DCursor *cursor, const float quat[4], bool use_compat)
2322 {
2323         BLI_ASSERT_UNIT_QUAT(quat);
2324
2325         switch (cursor->rotation_mode) {
2326                 case ROT_MODE_QUAT:
2327                 {
2328                         copy_qt_qt(cursor->rotation_quaternion, quat);
2329                         break;
2330                 }
2331                 case ROT_MODE_AXISANGLE:
2332                 {
2333                         quat_to_axis_angle(cursor->rotation_axis, &cursor->rotation_angle, quat);
2334                         break;
2335                 }
2336                 default:
2337                 {
2338                         if (use_compat) {
2339                                 quat_to_compatible_eulO(cursor->rotation_euler, cursor->rotation_euler, cursor->rotation_mode, quat);
2340                         }
2341                         else {
2342                                 quat_to_eulO(cursor->rotation_euler, cursor->rotation_mode, quat);
2343                         }
2344                         break;
2345                 }
2346         }
2347 }
2348
2349
2350 /** \} */