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