e8aebb2dbaaed8f70170f1458988cd518bb5e1ba
[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_WORKBENCH = "BLENDER_WORKBENCH";
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                                                 id_us_min(&lineset->linestyle->id);
407                                                 /* XXX Not copying anim/actions here? */
408                                                 BKE_id_copy_ex(bmain, (ID *)lineset->linestyle, (ID **)&lineset->linestyle, 0, false);
409                                         }
410                                 }
411                         }
412
413                         /* Full copy of world (included animations) */
414                         if (sce_copy->world) {
415                                 id_us_min(&sce_copy->world->id);
416                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->world, (ID **)&sce_copy->world, LIB_ID_COPY_ACTIONS, false);
417                         }
418
419                         /* Collections */
420                         BKE_collection_copy_full(bmain, sce_copy->master_collection);
421
422                         /* Full copy of GreasePencil. */
423                         /* XXX Not copying anim/actions here? */
424                         if (sce_copy->gpd) {
425                                 id_us_min(&sce_copy->gpd->id);
426                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->gpd, (ID **)&sce_copy->gpd, 0, false);
427                         }
428                 }
429                 else {
430                         /* Remove sequencer if not full copy */
431                         /* XXX Why in Hell? :/ */
432                         remove_sequencer_fcurves(sce_copy);
433                         BKE_sequencer_editing_free(sce_copy, true);
434                 }
435
436                 /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
437                  * are done outside of blenkernel with ED_object_single_users! */
438
439                 /*  camera */
440                 /* XXX This is most certainly useless? Object have not yet been duplicated... */
441                 if (ELEM(type, SCE_COPY_LINK_DATA, SCE_COPY_FULL)) {
442                         ID_NEW_REMAP(sce_copy->camera);
443                 }
444
445                 return sce_copy;
446         }
447 }
448
449 void BKE_scene_groups_relink(Scene *sce)
450 {
451         if (sce->rigidbody_world)
452                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
453 }
454
455 void BKE_scene_make_local(Main *bmain, Scene *sce, const bool lib_local)
456 {
457         /* For now should work, may need more work though to support all possible corner cases
458          * (also scene_copy probably needs some love). */
459         BKE_id_make_local_generic(bmain, &sce->id, true, lib_local);
460 }
461
462 /** Free (or release) any data used by this scene (does not free the scene itself). */
463 void BKE_scene_free_ex(Scene *sce, const bool do_id_user)
464 {
465         BKE_animdata_free((ID *)sce, false);
466
467         BKE_sequencer_editing_free(sce, do_id_user);
468
469         BKE_keyingsets_free(&sce->keyingsets);
470
471         /* is no lib link block, but scene extension */
472         if (sce->nodetree) {
473                 ntreeFreeTree(sce->nodetree);
474                 MEM_freeN(sce->nodetree);
475                 sce->nodetree = NULL;
476         }
477
478         if (sce->rigidbody_world) {
479                 BKE_rigidbody_free_world(sce);
480         }
481
482         if (sce->r.avicodecdata) {
483                 free_avicodecdata(sce->r.avicodecdata);
484                 MEM_freeN(sce->r.avicodecdata);
485                 sce->r.avicodecdata = NULL;
486         }
487         if (sce->r.ffcodecdata.properties) {
488                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
489                 MEM_freeN(sce->r.ffcodecdata.properties);
490                 sce->r.ffcodecdata.properties = NULL;
491         }
492
493         BLI_freelistN(&sce->markers);
494         BLI_freelistN(&sce->transform_spaces);
495         BLI_freelistN(&sce->r.views);
496
497         BKE_toolsettings_free(sce->toolsettings);
498         sce->toolsettings = NULL;
499
500         BKE_scene_free_depsgraph_hash(sce);
501
502         MEM_SAFE_FREE(sce->fps_info);
503
504         BKE_sound_destroy_scene(sce);
505
506         BKE_color_managed_view_settings_free(&sce->view_settings);
507
508         BKE_previewimg_free(&sce->preview);
509         curvemapping_free_data(&sce->r.mblur_shutter_curve);
510
511         for (ViewLayer *view_layer = sce->view_layers.first, *view_layer_next; view_layer; view_layer = view_layer_next) {
512                 view_layer_next = view_layer->next;
513
514                 BLI_remlink(&sce->view_layers, view_layer);
515                 BKE_view_layer_free_ex(view_layer, do_id_user);
516         }
517
518         /* Master Collection */
519         // TODO: what to do with do_id_user? it's also true when just
520         // closing the file which seems wrong? should decrement users
521         // for objects directly in the master collection? then other
522         // collections in the scene need to do it too?
523         if (sce->master_collection) {
524                 BKE_collection_free(sce->master_collection);
525                 MEM_freeN(sce->master_collection);
526                 sce->master_collection = NULL;
527         }
528
529         if (sce->eevee.light_cache) {
530                 EEVEE_lightcache_free(sce->eevee.light_cache);
531                 sce->eevee.light_cache = NULL;
532         }
533
534         /* These are freed on doversion. */
535         BLI_assert(sce->layer_properties == NULL);
536 }
537
538 void BKE_scene_free(Scene *sce)
539 {
540         BKE_scene_free_ex(sce, true);
541 }
542
543 void BKE_scene_init(Scene *sce)
544 {
545         ParticleEditSettings *pset;
546         int a;
547         const char *colorspace_name;
548         SceneRenderView *srv;
549         CurveMapping *mblur_shutter_curve;
550
551         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(sce, id));
552
553         unit_qt(sce->cursor.rotation);
554
555         sce->r.mode = R_OSA;
556         sce->r.cfra = 1;
557         sce->r.sfra = 1;
558         sce->r.efra = 250;
559         sce->r.frame_step = 1;
560         sce->r.xsch = 1920;
561         sce->r.ysch = 1080;
562         sce->r.xasp = 1;
563         sce->r.yasp = 1;
564         sce->r.tilex = 256;
565         sce->r.tiley = 256;
566         sce->r.size = 100;
567
568         sce->r.im_format.planes = R_IMF_PLANES_RGBA;
569         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
570         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
571         sce->r.im_format.quality = 90;
572         sce->r.im_format.compress = 15;
573
574         sce->r.displaymode = R_OUTPUT_WINDOW;
575         sce->r.framapto = 100;
576         sce->r.images = 100;
577         sce->r.framelen = 1.0;
578         sce->r.blurfac = 0.5;
579         sce->r.frs_sec = 24;
580         sce->r.frs_sec_base = 1;
581
582         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
583          *            images would look in the same way as in current blender
584          *
585          *            perhaps at some point should be completely deprecated?
586          */
587         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
588
589         sce->r.dither_intensity = 1.0f;
590
591         sce->r.bake_mode = 0;
592         sce->r.bake_filter = 16;
593         sce->r.bake_flag = R_BAKE_CLEAR;
594         sce->r.bake_samples = 256;
595         sce->r.bake_biasdist = 0.001;
596
597         sce->r.bake.flag = R_BAKE_CLEAR;
598         sce->r.bake.pass_filter = R_BAKE_PASS_FILTER_ALL;
599         sce->r.bake.width = 512;
600         sce->r.bake.height = 512;
601         sce->r.bake.margin = 16;
602         sce->r.bake.normal_space = R_BAKE_SPACE_TANGENT;
603         sce->r.bake.normal_swizzle[0] = R_BAKE_POSX;
604         sce->r.bake.normal_swizzle[1] = R_BAKE_POSY;
605         sce->r.bake.normal_swizzle[2] = R_BAKE_POSZ;
606         BLI_strncpy(sce->r.bake.filepath, U.renderdir, sizeof(sce->r.bake.filepath));
607
608         sce->r.bake.im_format.planes = R_IMF_PLANES_RGBA;
609         sce->r.bake.im_format.imtype = R_IMF_IMTYPE_PNG;
610         sce->r.bake.im_format.depth = R_IMF_CHAN_DEPTH_8;
611         sce->r.bake.im_format.quality = 90;
612         sce->r.bake.im_format.compress = 15;
613
614         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
615         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;
616         sce->r.stamp_font_id = 12;
617         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
618         sce->r.fg_stamp[3] = 1.0f;
619         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
620         sce->r.bg_stamp[3] = 0.25f;
621
622         sce->r.seq_prev_type = OB_SOLID;
623         sce->r.seq_rend_type = OB_SOLID;
624         sce->r.seq_flag = 0;
625
626         sce->r.threads = 1;
627
628         sce->r.simplify_subsurf = 6;
629         sce->r.simplify_particles = 1.0f;
630
631         sce->r.border.xmin = 0.0f;
632         sce->r.border.ymin = 0.0f;
633         sce->r.border.xmax = 1.0f;
634         sce->r.border.ymax = 1.0f;
635
636         sce->r.preview_start_resolution = 64;
637
638         sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE;
639         sce->r.unit_line_thickness = 1.0f;
640
641         mblur_shutter_curve = &sce->r.mblur_shutter_curve;
642         curvemapping_set_defaults(mblur_shutter_curve, 1, 0.0f, 0.0f, 1.0f, 1.0f);
643         curvemapping_initialize(mblur_shutter_curve);
644         curvemap_reset(mblur_shutter_curve->cm,
645                        &mblur_shutter_curve->clipr,
646                        CURVE_PRESET_MAX,
647                        CURVEMAP_SLOPE_POS_NEG);
648
649         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
650
651         sce->toolsettings->object_flag |= SCE_OBJECT_MODE_LOCK;
652         sce->toolsettings->doublimit = 0.001;
653         sce->toolsettings->vgroup_weight = 1.0f;
654         sce->toolsettings->uvcalc_margin = 0.001f;
655         sce->toolsettings->uvcalc_flag = UVCALC_TRANSFORM_CORRECT;
656         sce->toolsettings->unwrapper = 1;
657         sce->toolsettings->select_thresh = 0.01f;
658         sce->toolsettings->gizmo_flag = SCE_GIZMO_SHOW_TRANSLATE | SCE_GIZMO_SHOW_ROTATE | SCE_GIZMO_SHOW_SCALE;
659
660         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
661         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
662         sce->toolsettings->autokey_mode = U.autokey_mode;
663
664
665         sce->toolsettings->transform_pivot_point = V3D_AROUND_CENTER_MEAN;
666         sce->toolsettings->snap_mode = SCE_SNAP_MODE_INCREMENT;
667         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
668         sce->toolsettings->snap_uv_mode = SCE_SNAP_MODE_INCREMENT;
669
670         sce->toolsettings->curve_paint_settings.curve_type = CU_BEZIER;
671         sce->toolsettings->curve_paint_settings.flag |= CURVE_PAINT_FLAG_CORNERS_DETECT;
672         sce->toolsettings->curve_paint_settings.error_threshold = 8;
673         sce->toolsettings->curve_paint_settings.radius_max = 1.0f;
674         sce->toolsettings->curve_paint_settings.corner_angle = DEG2RADF(70.0f);
675
676         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
677         sce->toolsettings->statvis.overhang_min = 0;
678         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
679         sce->toolsettings->statvis.thickness_max = 0.1f;
680         sce->toolsettings->statvis.thickness_samples = 1;
681         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
682         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
683
684         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
685         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
686
687         sce->toolsettings->proportional_size = 1.0f;
688
689         sce->toolsettings->imapaint.paint.flags |= PAINT_SHOW_BRUSH;
690         sce->toolsettings->imapaint.normal_angle = 80;
691         sce->toolsettings->imapaint.seam_bleed = 2;
692
693         /* grease pencil multiframe falloff curve */
694         sce->toolsettings->gp_sculpt.cur_falloff = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
695         CurveMapping *gp_falloff_curve = sce->toolsettings->gp_sculpt.cur_falloff;
696         curvemapping_initialize(gp_falloff_curve);
697         curvemap_reset(gp_falloff_curve->cm,
698                 &gp_falloff_curve->clipr,
699                 CURVE_PRESET_GAUSS,
700                 CURVEMAP_SLOPE_POSITIVE);
701
702         sce->physics_settings.gravity[0] = 0.0f;
703         sce->physics_settings.gravity[1] = 0.0f;
704         sce->physics_settings.gravity[2] = -9.81f;
705         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
706
707         sce->unit.system = USER_UNIT_METRIC;
708         sce->unit.scale_length = 1.0f;
709         sce->unit.length_unit = bUnit_GetBaseUnitOfType(USER_UNIT_METRIC, B_UNIT_LENGTH);
710         sce->unit.mass_unit = bUnit_GetBaseUnitOfType(USER_UNIT_METRIC, B_UNIT_MASS);
711         sce->unit.time_unit = bUnit_GetBaseUnitOfType(USER_UNIT_METRIC, B_UNIT_TIME);
712
713         pset = &sce->toolsettings->particle;
714         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
715         pset->emitterdist = 0.25f;
716         pset->totrekey = 5;
717         pset->totaddkey = 5;
718         pset->brushtype = PE_BRUSH_NONE;
719         pset->draw_step = 2;
720         pset->fade_frames = 2;
721         pset->selectmode = SCE_SELECT_PATH;
722
723         for (a = 0; a < ARRAY_SIZE(pset->brush); a++) {
724                 pset->brush[a].strength = 0.5f;
725                 pset->brush[a].size = 50;
726                 pset->brush[a].step = 10;
727                 pset->brush[a].count = 10;
728         }
729         pset->brush[PE_BRUSH_CUT].strength = 1.0f;
730
731         sce->r.ffcodecdata.audio_mixrate = 48000;
732         sce->r.ffcodecdata.audio_volume = 1.0f;
733         sce->r.ffcodecdata.audio_bitrate = 192;
734         sce->r.ffcodecdata.audio_channels = 2;
735
736         BLI_strncpy(sce->r.engine, RE_engine_id_BLENDER_EEVEE, sizeof(sce->r.engine));
737
738         sce->audio.distance_model = 2.0f;
739         sce->audio.doppler_factor = 1.0f;
740         sce->audio.speed_of_sound = 343.3f;
741         sce->audio.volume = 1.0f;
742         sce->audio.flag = AUDIO_SYNC;
743
744         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
745
746         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
747         sce->r.osa = 8;
748
749         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
750
751         /* multiview - stereo */
752         BKE_scene_add_render_view(sce, STEREO_LEFT_NAME);
753         srv = sce->r.views.first;
754         BLI_strncpy(srv->suffix, STEREO_LEFT_SUFFIX, sizeof(srv->suffix));
755
756         BKE_scene_add_render_view(sce, STEREO_RIGHT_NAME);
757         srv = sce->r.views.last;
758         BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix));
759
760         BKE_sound_create_scene(sce);
761
762         /* color management */
763         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
764
765         BKE_color_managed_display_settings_init(&sce->display_settings);
766         BKE_color_managed_view_settings_init(&sce->view_settings,
767                                              &sce->display_settings);
768         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
769                     sizeof(sce->sequencer_colorspace_settings.name));
770
771         /* Safe Areas */
772         copy_v2_fl2(sce->safe_areas.title, 3.5f / 100.0f, 3.5f / 100.0f);
773         copy_v2_fl2(sce->safe_areas.action, 10.0f / 100.0f, 5.0f / 100.0f);
774         copy_v2_fl2(sce->safe_areas.title_center, 17.5f / 100.0f, 5.0f / 100.0f);
775         copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f);
776
777         sce->preview = NULL;
778
779         /* GP Sculpt brushes */
780         {
781                 GP_Sculpt_Settings *gset = &sce->toolsettings->gp_sculpt;
782                 GP_Sculpt_Data *gp_brush;
783                 float curcolor_add[3], curcolor_sub[3];
784                 ARRAY_SET_ITEMS(curcolor_add, 1.0f, 0.6f, 0.6f);
785                 ARRAY_SET_ITEMS(curcolor_sub, 0.6f, 0.6f, 1.0f);
786
787                 gp_brush = &gset->brush[GP_SCULPT_TYPE_SMOOTH];
788                 gp_brush->size = 25;
789                 gp_brush->strength = 0.3f;
790                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_SMOOTH_PRESSURE | GP_SCULPT_FLAG_ENABLE_CURSOR;
791                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
792                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
793
794                 gp_brush = &gset->brush[GP_SCULPT_TYPE_THICKNESS];
795                 gp_brush->size = 25;
796                 gp_brush->strength = 0.5f;
797                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
798                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
799                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
800
801                 gp_brush = &gset->brush[GP_SCULPT_TYPE_STRENGTH];
802                 gp_brush->size = 25;
803                 gp_brush->strength = 0.5f;
804                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | GP_SCULPT_FLAG_ENABLE_CURSOR;
805                 copy_v3_v3(gp_brush->curcolor_add, curcolor_add);
806                 copy_v3_v3(gp_brush->curcolor_sub, curcolor_sub);
807
808                 gp_brush = &gset->brush[GP_SCULPT_TYPE_GRAB];
809                 gp_brush->size = 50;
810                 gp_brush->strength = 0.3f;
811                 gp_brush->flag = GP_SCULPT_FLAG_USE_FALLOFF | 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_PUSH];
816                 gp_brush->size = 25;
817                 gp_brush->strength = 0.3f;
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_TWIST];
823                 gp_brush->size = 50;
824                 gp_brush->strength = 0.3f;
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_PINCH];
830                 gp_brush->size = 50;
831                 gp_brush->strength = 0.5f;
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_RANDOMIZE];
837                 gp_brush->size = 25;
838                 gp_brush->strength = 0.5f;
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
844         /* GP Stroke Placement */
845         sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE;
846         sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE;
847         sce->toolsettings->gpencil_seq_align = GP_PROJECT_VIEWSPACE;
848         sce->toolsettings->gpencil_ima_align = GP_PROJECT_VIEWSPACE;
849
850         /* Annotations */
851         sce->toolsettings->annotate_v3d_align = GP_PROJECT_VIEWSPACE | GP_PROJECT_CURSOR;
852         sce->toolsettings->annotate_thickness = 3;
853
854         sce->orientation_index_custom = -1;
855
856         /* Master Collection */
857         sce->master_collection = BKE_collection_master_add();
858
859         BKE_view_layer_add(sce, "View Layer");
860
861         /* SceneDisplay */
862         copy_v3_v3(sce->display.light_direction, (float[3]){M_SQRT1_3, M_SQRT1_3, M_SQRT1_3});
863         sce->display.shadow_shift = 0.1f;
864         sce->display.shadow_focus = 0.0f;
865
866         sce->display.matcap_ssao_distance = 0.2f;
867         sce->display.matcap_ssao_attenuation = 1.0f;
868         sce->display.matcap_ssao_samples = 16;
869
870         /* OpenGL Render. */
871         BKE_screen_view3d_shading_init(&sce->display.shading);
872
873         /* SceneEEVEE */
874         sce->eevee.gi_diffuse_bounces = 3;
875         sce->eevee.gi_cubemap_resolution = 512;
876         sce->eevee.gi_visibility_resolution = 32;
877         sce->eevee.gi_cubemap_draw_size = 0.3f;
878         sce->eevee.gi_irradiance_draw_size = 0.1f;
879         sce->eevee.gi_irradiance_smoothing = 0.1f;
880         sce->eevee.gi_filter_quality = 1.0f;
881
882         sce->eevee.taa_samples = 16;
883         sce->eevee.taa_render_samples = 64;
884
885         sce->eevee.sss_samples = 7;
886         sce->eevee.sss_jitter_threshold = 0.3f;
887
888         sce->eevee.ssr_quality = 0.25f;
889         sce->eevee.ssr_max_roughness = 0.5f;
890         sce->eevee.ssr_thickness = 0.2f;
891         sce->eevee.ssr_border_fade = 0.075f;
892         sce->eevee.ssr_firefly_fac = 10.0f;
893
894         sce->eevee.volumetric_start = 0.1f;
895         sce->eevee.volumetric_end = 100.0f;
896         sce->eevee.volumetric_tile_size = 8;
897         sce->eevee.volumetric_samples = 64;
898         sce->eevee.volumetric_sample_distribution = 0.8f;
899         sce->eevee.volumetric_light_clamp = 0.0f;
900         sce->eevee.volumetric_shadow_samples = 16;
901
902         sce->eevee.gtao_distance = 0.2f;
903         sce->eevee.gtao_factor = 1.0f;
904         sce->eevee.gtao_quality = 0.25f;
905
906         sce->eevee.bokeh_max_size = 100.0f;
907         sce->eevee.bokeh_threshold = 1.0f;
908
909         copy_v3_fl(sce->eevee.bloom_color, 1.0f);
910         sce->eevee.bloom_threshold = 0.8f;
911         sce->eevee.bloom_knee = 0.5f;
912         sce->eevee.bloom_intensity = 0.8f;
913         sce->eevee.bloom_radius = 6.5f;
914         sce->eevee.bloom_clamp = 1.0f;
915
916         sce->eevee.motion_blur_samples = 8;
917         sce->eevee.motion_blur_shutter = 1.0f;
918
919         sce->eevee.shadow_method = SHADOW_ESM;
920         sce->eevee.shadow_cube_size = 512;
921         sce->eevee.shadow_cascade_size = 1024;
922
923         sce->eevee.light_cache = NULL;
924         sce->eevee.light_threshold = 0.01f;
925
926         sce->eevee.overscan = 3.0f;
927
928         sce->eevee.flag =
929                 SCE_EEVEE_VOLUMETRIC_LIGHTS |
930                 SCE_EEVEE_GTAO_BENT_NORMALS |
931                 SCE_EEVEE_GTAO_BOUNCE |
932                 SCE_EEVEE_TAA_REPROJECTION |
933                 SCE_EEVEE_SSR_HALF_RESOLUTION;
934 }
935
936 Scene *BKE_scene_add(Main *bmain, const char *name)
937 {
938         Scene *sce;
939
940         sce = BKE_libblock_alloc(bmain, ID_SCE, name, 0);
941         id_us_min(&sce->id);
942         id_us_ensure_real(&sce->id);
943
944         BKE_scene_init(sce);
945
946         return sce;
947 }
948
949 /**
950  * Check if there is any instance of the object in the scene
951  */
952 bool BKE_scene_object_find(Scene *scene, Object *ob)
953 {
954         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
955                 if (BLI_findptr(&view_layer->object_bases, ob, offsetof(Base, object))) {
956                     return true;
957                 }
958         }
959         return false;
960 }
961
962 Object *BKE_scene_object_find_by_name(Scene *scene, const char *name)
963 {
964         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
965                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
966                         if (STREQ(base->object->id.name + 2, name)) {
967                                 return base->object;
968                         }
969                 }
970         }
971         return NULL;
972 }
973
974 /**
975  * Sets the active scene, mainly used when running in background mode (``--scene`` command line argument).
976  * This is also called to set the scene directly, bypassing windowing code.
977  * Otherwise #WM_window_set_active_scene is used when changing scenes by the user.
978  */
979 void BKE_scene_set_background(Main *bmain, Scene *scene)
980 {
981         Object *ob;
982
983         /* check for cyclic sets, for reading old files but also for definite security (py?) */
984         BKE_scene_validate_setscene(bmain, scene);
985
986         /* deselect objects (for dataselect) */
987         for (ob = bmain->object.first; ob; ob = ob->id.next)
988                 ob->flag &= ~SELECT;
989
990         /* copy layers and flags from bases to objects */
991         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
992                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
993                         ob = base->object;
994                         /* collection patch... */
995                         BKE_scene_object_base_flag_sync_from_base(base);
996                 }
997         }
998         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
999 }
1000
1001 /* called from creator_args.c */
1002 Scene *BKE_scene_set_name(Main *bmain, const char *name)
1003 {
1004         Scene *sce = (Scene *)BKE_libblock_find_name(bmain, ID_SCE, name);
1005         if (sce) {
1006                 BKE_scene_set_background(bmain, sce);
1007                 printf("Scene switch for render: '%s' in file: '%s'\n", name, BKE_main_blendfile_path(bmain));
1008                 return sce;
1009         }
1010
1011         printf("Can't find scene: '%s' in file: '%s'\n", name, BKE_main_blendfile_path(bmain));
1012         return NULL;
1013 }
1014
1015 /* Used by metaballs, return *all* objects (including duplis) existing in the scene (including scene's sets) */
1016 int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter,
1017         Scene **scene, int val, Base **base, Object **ob)
1018 {
1019         bool run_again = true;
1020
1021         /* init */
1022         if (val == 0) {
1023                 iter->phase = F_START;
1024                 iter->dupob = NULL;
1025                 iter->duplilist = NULL;
1026                 iter->dupli_refob = NULL;
1027         }
1028         else {
1029                 /* run_again is set when a duplilist has been ended */
1030                 while (run_again) {
1031                         run_again = false;
1032
1033                         /* the first base */
1034                         if (iter->phase == F_START) {
1035                                 ViewLayer *view_layer = (depsgraph) ?
1036                                         DEG_get_evaluated_view_layer(depsgraph) :
1037                                         BKE_view_layer_context_active_PLACEHOLDER(*scene);
1038                                 *base = view_layer->object_bases.first;
1039                                 if (*base) {
1040                                         *ob = (*base)->object;
1041                                         iter->phase = F_SCENE;
1042                                 }
1043                                 else {
1044                                         /* exception: empty scene layer */
1045                                         while ((*scene)->set) {
1046                                                 (*scene) = (*scene)->set;
1047                                                 ViewLayer *view_layer_set = BKE_view_layer_default_render((*scene));
1048                                                 if (view_layer_set->object_bases.first) {
1049                                                         *base = view_layer_set->object_bases.first;
1050                                                         *ob = (*base)->object;
1051                                                         iter->phase = F_SCENE;
1052                                                         break;
1053                                                 }
1054                                         }
1055                                 }
1056                         }
1057                         else {
1058                                 if (*base && iter->phase != F_DUPLI) {
1059                                         *base = (*base)->next;
1060                                         if (*base) {
1061                                                 *ob = (*base)->object;
1062                                         }
1063                                         else {
1064                                                 if (iter->phase == F_SCENE) {
1065                                                         /* (*scene) is finished, now do the set */
1066                                                         while ((*scene)->set) {
1067                                                                 (*scene) = (*scene)->set;
1068                                                                 ViewLayer *view_layer_set = BKE_view_layer_default_render((*scene));
1069                                                                 if (view_layer_set->object_bases.first) {
1070                                                                         *base = view_layer_set->object_bases.first;
1071                                                                         *ob = (*base)->object;
1072                                                                         break;
1073                                                                 }
1074                                                         }
1075                                                 }
1076                                         }
1077                                 }
1078                         }
1079
1080                         if (*base == NULL) {
1081                                 iter->phase = F_START;
1082                         }
1083                         else {
1084                                 if (iter->phase != F_DUPLI) {
1085                                         if (depsgraph && (*base)->object->transflag & OB_DUPLI) {
1086                                                 /* collections cannot be duplicated for mballs yet,
1087                                                  * this enters eternal loop because of
1088                                                  * makeDispListMBall getting called inside of collection_duplilist */
1089                                                 if ((*base)->object->dup_group == NULL) {
1090                                                         iter->duplilist = object_duplilist(depsgraph, (*scene), (*base)->object);
1091
1092                                                         iter->dupob = iter->duplilist->first;
1093
1094                                                         if (!iter->dupob) {
1095                                                                 free_object_duplilist(iter->duplilist);
1096                                                                 iter->duplilist = NULL;
1097                                                         }
1098                                                         iter->dupli_refob = NULL;
1099                                                 }
1100                                         }
1101                                 }
1102                                 /* handle dupli's */
1103                                 if (iter->dupob) {
1104                                         (*base)->flag_legacy |= OB_FROMDUPLI;
1105                                         *ob = iter->dupob->ob;
1106                                         iter->phase = F_DUPLI;
1107
1108                                         if (iter->dupli_refob != *ob) {
1109                                                 if (iter->dupli_refob) {
1110                                                         /* Restore previous object's real matrix. */
1111                                                         copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1112                                                 }
1113                                                 /* Backup new object's real matrix. */
1114                                                 iter->dupli_refob = *ob;
1115                                                 copy_m4_m4(iter->omat, iter->dupli_refob->obmat);
1116                                         }
1117                                         copy_m4_m4((*ob)->obmat, iter->dupob->mat);
1118
1119                                         iter->dupob = iter->dupob->next;
1120                                 }
1121                                 else if (iter->phase == F_DUPLI) {
1122                                         iter->phase = F_SCENE;
1123                                         (*base)->flag_legacy &= ~OB_FROMDUPLI;
1124
1125                                         if (iter->dupli_refob) {
1126                                                 /* Restore last object's real matrix. */
1127                                                 copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1128                                                 iter->dupli_refob = NULL;
1129                                         }
1130
1131                                         free_object_duplilist(iter->duplilist);
1132                                         iter->duplilist = NULL;
1133                                         run_again = true;
1134                                 }
1135                         }
1136                 }
1137         }
1138
1139         return iter->phase;
1140 }
1141
1142 Scene *BKE_scene_find_from_collection(const Main *bmain, const Collection *collection)
1143 {
1144         for (Scene *scene = bmain->scene.first; scene; scene = scene->id.next) {
1145                 for (ViewLayer *layer = scene->view_layers.first; layer; layer = layer->next) {
1146                         if (BKE_view_layer_has_collection(layer, collection)) {
1147                                 return scene;
1148                         }
1149                 }
1150         }
1151
1152         return NULL;
1153 }
1154
1155 #ifdef DURIAN_CAMERA_SWITCH
1156 Object *BKE_scene_camera_switch_find(Scene *scene)
1157 {
1158         if (scene->r.mode & R_NO_CAMERA_SWITCH) {
1159                 return NULL;
1160         }
1161
1162         TimeMarker *m;
1163         int cfra = scene->r.cfra;
1164         int frame = -(MAXFRAME + 1);
1165         int min_frame = MAXFRAME + 1;
1166         Object *camera = NULL;
1167         Object *first_camera = NULL;
1168
1169         for (m = scene->markers.first; m; m = m->next) {
1170                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
1171                         if ((m->frame <= cfra) && (m->frame > frame)) {
1172                                 camera = m->camera;
1173                                 frame = m->frame;
1174
1175                                 if (frame == cfra)
1176                                         break;
1177                         }
1178
1179                         if (m->frame < min_frame) {
1180                                 first_camera = m->camera;
1181                                 min_frame = m->frame;
1182                         }
1183                 }
1184         }
1185
1186         if (camera == NULL) {
1187                 /* If there's no marker to the left of current frame,
1188                  * use camera from left-most marker to solve all sort
1189                  * of Schrodinger uncertainties.
1190                  */
1191                 return first_camera;
1192         }
1193
1194         return camera;
1195 }
1196 #endif
1197
1198 int BKE_scene_camera_switch_update(Scene *scene)
1199 {
1200 #ifdef DURIAN_CAMERA_SWITCH
1201         Object *camera = BKE_scene_camera_switch_find(scene);
1202         if (camera) {
1203                 scene->camera = camera;
1204                 DEG_id_tag_update(&scene->id, DEG_TAG_COPY_ON_WRITE);
1205                 return 1;
1206         }
1207 #else
1208         (void)scene;
1209 #endif
1210         return 0;
1211 }
1212
1213 char *BKE_scene_find_marker_name(Scene *scene, int frame)
1214 {
1215         ListBase *markers = &scene->markers;
1216         TimeMarker *m1, *m2;
1217
1218         /* search through markers for match */
1219         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
1220                 if (m1->frame == frame)
1221                         return m1->name;
1222
1223                 if (m1 == m2)
1224                         break;
1225
1226                 if (m2->frame == frame)
1227                         return m2->name;
1228         }
1229
1230         return NULL;
1231 }
1232
1233 /* return the current marker for this frame,
1234  * we can have more than 1 marker per frame, this just returns the first :/ */
1235 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
1236 {
1237         TimeMarker *marker, *best_marker = NULL;
1238         int best_frame = -MAXFRAME * 2;
1239         for (marker = scene->markers.first; marker; marker = marker->next) {
1240                 if (marker->frame == frame) {
1241                         return marker->name;
1242                 }
1243
1244                 if (marker->frame > best_frame && marker->frame < frame) {
1245                         best_marker = marker;
1246                         best_frame = marker->frame;
1247                 }
1248         }
1249
1250         return best_marker ? best_marker->name : NULL;
1251 }
1252
1253 int BKE_scene_frame_snap_by_seconds(Scene *scene, double interval_in_seconds, int cfra)
1254 {
1255         const int fps = round_db_to_int(FPS * interval_in_seconds);
1256         const int second_prev = cfra - mod_i(cfra, fps);
1257         const int second_next = second_prev + fps;
1258         const int delta_prev = cfra - second_prev;
1259         const int delta_next = second_next - cfra;
1260         return (delta_prev < delta_next) ? second_prev : second_next;
1261 }
1262
1263 void BKE_scene_remove_rigidbody_object(struct Main *bmain, Scene *scene, Object *ob)
1264 {
1265         /* remove rigid body constraint from world before removing object */
1266         if (ob->rigidbody_constraint)
1267                 BKE_rigidbody_remove_constraint(scene, ob);
1268         /* remove rigid body object from world before removing object */
1269         if (ob->rigidbody_object)
1270                 BKE_rigidbody_remove_object(bmain, scene, ob);
1271 }
1272
1273 /* checks for cycle, returns 1 if it's all OK */
1274 bool BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1275 {
1276         Scene *sce_iter;
1277         int a, totscene;
1278
1279         if (sce->set == NULL) return true;
1280         totscene = BLI_listbase_count(&bmain->scene);
1281
1282         for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) {
1283                 /* more iterations than scenes means we have a cycle */
1284                 if (a > totscene) {
1285                         /* the tested scene gets zero'ed, that's typically current scene */
1286                         sce->set = NULL;
1287                         return false;
1288                 }
1289         }
1290
1291         return true;
1292 }
1293
1294 /* This function is needed to cope with fractional frames - including two Blender rendering features
1295  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering.
1296  */
1297 float BKE_scene_frame_get(const Scene *scene)
1298 {
1299         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1300 }
1301
1302 /* This function is used to obtain arbitrary fractional frames */
1303 float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame)
1304 {
1305         float ctime = frame;
1306         ctime += scene->r.subframe;
1307         ctime *= scene->r.framelen;
1308
1309         return ctime;
1310 }
1311
1312 /**
1313  * Sets the frame int/float components.
1314  */
1315 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1316 {
1317         double intpart;
1318         scene->r.subframe = modf(cfra, &intpart);
1319         scene->r.cfra = (int)intpart;
1320 }
1321
1322 /* That's like really a bummer, because currently animation data for armatures
1323  * might want to use pose, and pose might be missing on the object.
1324  * This happens when changing visible layers, which leads to situations when
1325  * pose is missing or marked for recalc, animation will change it and then
1326  * object update will restore the pose.
1327  *
1328  * This could be solved by the new dependency graph, but for until then we'll
1329  * do an extra pass on the objects to ensure it's all fine.
1330  */
1331 #define POSE_ANIMATION_WORKAROUND
1332
1333 #ifdef POSE_ANIMATION_WORKAROUND
1334 static void scene_armature_depsgraph_workaround(Main *bmain, Depsgraph *depsgraph)
1335 {
1336         Object *ob;
1337         if (BLI_listbase_is_empty(&bmain->armature) || !DEG_id_type_updated(depsgraph, ID_OB)) {
1338                 return;
1339         }
1340         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1341                 if (ob->type == OB_ARMATURE && ob->adt && ob->adt->recalc & ADT_RECALC_ANIM) {
1342                         if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
1343                                 BKE_pose_rebuild(bmain, ob, ob->data, true);
1344                         }
1345                 }
1346         }
1347 }
1348 #endif
1349
1350 static bool check_rendered_viewport_visible(Main *bmain)
1351 {
1352         wmWindowManager *wm = bmain->wm.first;
1353         wmWindow *window;
1354         for (window = wm->windows.first; window != NULL; window = window->next) {
1355                 const bScreen *screen = BKE_workspace_active_screen_get(window->workspace_hook);
1356                 Scene *scene = window->scene;
1357                 RenderEngineType *type = RE_engines_find(scene->r.engine);
1358
1359                 if (type->draw_engine || !type->render) {
1360                         continue;
1361                 }
1362
1363                 for (ScrArea *area = screen->areabase.first; area != NULL; area = area->next) {
1364                         View3D *v3d = area->spacedata.first;
1365                         if (area->spacetype != SPACE_VIEW3D) {
1366                                 continue;
1367                         }
1368                         if (v3d->shading.type == OB_RENDER) {
1369                                 return true;
1370                         }
1371                 }
1372         }
1373         return false;
1374 }
1375
1376 /* TODO(campbell): shouldn't we be able to use 'DEG_get_view_layer' here?
1377  * Currently this is NULL on load, so don't. */
1378 static void prepare_mesh_for_viewport_render(
1379         Main *bmain, const ViewLayer *view_layer)
1380 {
1381         /* This is needed to prepare mesh to be used by the render
1382          * engine from the viewport rendering. We do loading here
1383          * so all the objects which shares the same mesh datablock
1384          * are nicely tagged for update and updated.
1385          *
1386          * This makes it so viewport render engine doesn't need to
1387          * call loading of the edit data for the mesh objects.
1388          */
1389
1390         Object *obedit = OBEDIT_FROM_VIEW_LAYER(view_layer);
1391         if (obedit) {
1392                 Mesh *mesh = obedit->data;
1393                 if ((obedit->type == OB_MESH) &&
1394                     ((obedit->id.recalc & ID_RECALC_ALL) ||
1395                      (mesh->id.recalc & ID_RECALC_ALL)))
1396                 {
1397                         if (check_rendered_viewport_visible(bmain)) {
1398                                 BMesh *bm = mesh->edit_btmesh->bm;
1399                                 BM_mesh_bm_to_me(
1400                                         bmain, bm, mesh,
1401                                         (&(struct BMeshToMeshParams){
1402                                             .calc_object_remap = true,
1403                                         }));
1404                                 DEG_id_tag_update(&mesh->id, 0);
1405                         }
1406                 }
1407         }
1408 }
1409
1410 /* TODO(sergey): This actually should become view_layer_graph or so.
1411  * Same applies to update_for_newframe.
1412  */
1413 void BKE_scene_graph_update_tagged(Depsgraph *depsgraph,
1414                                    Main *bmain)
1415 {
1416         Scene *scene = DEG_get_input_scene(depsgraph);
1417         ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1418
1419         bool run_callbacks = DEG_id_type_any_updated(depsgraph);
1420         if (run_callbacks) {
1421                 BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_DEPSGRAPH_UPDATE_PRE);
1422         }
1423
1424         /* TODO(sergey): Some functions here are changing global state,
1425          * for example, clearing update tags from bmain.
1426          */
1427         /* (Re-)build dependency graph if needed. */
1428         DEG_graph_relations_update(depsgraph, bmain, scene, view_layer);
1429         /* Uncomment this to check if graph was properly tagged for update. */
1430         // DEG_debug_graph_relations_validate(depsgraph, bmain, scene);
1431         /* Flush editing data if needed. */
1432         prepare_mesh_for_viewport_render(bmain, view_layer);
1433         /* Flush recalc flags to dependencies. */
1434         DEG_graph_flush_update(bmain, depsgraph);
1435         /* Update all objects: drivers, matrices, displists, etc. flags set
1436          * by depgraph or manual, no layer check here, gets correct flushed.
1437          */
1438         DEG_evaluate_on_refresh(depsgraph);
1439         /* Update sound system animation (TODO, move to depsgraph). */
1440         BKE_sound_update_scene(bmain, scene);
1441
1442         /* Notify python about depsgraph update */
1443         if (run_callbacks) {
1444                 BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_DEPSGRAPH_UPDATE_POST);
1445         }
1446         /* Inform editors about possible changes. */
1447         DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, false);
1448         /* Clear recalc flags. */
1449         DEG_ids_clear_recalc(bmain, depsgraph);
1450 }
1451
1452 /* applies changes right away, does all sets too */
1453 void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph,
1454                                          Main *bmain)
1455 {
1456         Scene *scene = DEG_get_input_scene(depsgraph);
1457         ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1458
1459         /* TODO(sergey): Some functions here are changing global state,
1460          * for example, clearing update tags from bmain.
1461          */
1462         const float ctime = BKE_scene_frame_get(scene);
1463         /* Keep this first. */
1464         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1465         /* Update animated image textures for particles, modifiers, gpu, etc,
1466          * call this at the start so modifiers with textures don't lag 1 frame.
1467          */
1468         BKE_image_update_frame(bmain, scene->r.cfra);
1469         BKE_sound_set_cfra(scene->r.cfra);
1470         DEG_graph_relations_update(depsgraph, bmain, scene, view_layer);
1471         /* Update animated cache files for modifiers.
1472          *
1473          * TODO(sergey): Make this a depsgraph node?
1474          */
1475         BKE_cachefile_update_frame(bmain, depsgraph, scene, ctime,
1476                                    (((double)scene->r.frs_sec) / (double)scene->r.frs_sec_base));
1477 #ifdef POSE_ANIMATION_WORKAROUND
1478         scene_armature_depsgraph_workaround(bmain, depsgraph);
1479 #endif
1480         /* Update all objects: drivers, matrices, displists, etc. flags set
1481          * by depgraph or manual, no layer check here, gets correct flushed.
1482          */
1483         DEG_evaluate_on_framechange(bmain, depsgraph, ctime);
1484         /* Update sound system animation (TODO, move to depsgraph). */
1485         BKE_sound_update_scene(bmain, scene);
1486         /* Notify editors and python about recalc. */
1487         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1488         /* Inform editors about possible changes. */
1489         DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, true);
1490         /* clear recalc flags */
1491         DEG_ids_clear_recalc(bmain, depsgraph);
1492 }
1493
1494 /** Ensures given scene/view_layer pair has a valid, up-to-date depsgraph.
1495  *
1496  * \warning Sets matching depsgraph as active, so should only be called from the active editing context
1497  *          (usually, from operators).
1498  */
1499 void BKE_scene_view_layer_graph_evaluated_ensure(Main *bmain, Scene *scene, ViewLayer *view_layer)
1500 {
1501         Depsgraph *depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true);
1502         DEG_make_active(depsgraph);
1503         BKE_scene_graph_update_tagged(depsgraph, bmain);
1504 }
1505
1506 /* return default view */
1507 SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name)
1508 {
1509         SceneRenderView *srv;
1510
1511         if (!name)
1512                 name = DATA_("RenderView");
1513
1514         srv = MEM_callocN(sizeof(SceneRenderView), "new render view");
1515         BLI_strncpy(srv->name, name, sizeof(srv->name));
1516         BLI_uniquename(&sce->r.views, srv, DATA_("RenderView"), '.', offsetof(SceneRenderView, name), sizeof(srv->name));
1517         BLI_addtail(&sce->r.views, srv);
1518
1519         return srv;
1520 }
1521
1522 bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
1523 {
1524         const int act = BLI_findindex(&scene->r.views, srv);
1525
1526         if (act == -1) {
1527                 return false;
1528         }
1529         else if (scene->r.views.first == scene->r.views.last) {
1530                 /* ensure 1 view is kept */
1531                 return false;
1532         }
1533
1534         BLI_remlink(&scene->r.views, srv);
1535         MEM_freeN(srv);
1536
1537         scene->r.actview = 0;
1538
1539         return true;
1540 }
1541
1542 /* render simplification */
1543
1544 int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
1545 {
1546         if (r->mode & R_SIMPLIFY) {
1547                 if (for_render)
1548                         return min_ii(r->simplify_subsurf_render, lvl);
1549                 else
1550                         return min_ii(r->simplify_subsurf, lvl);
1551         }
1552         else {
1553                 return lvl;
1554         }
1555 }
1556
1557 int get_render_child_particle_number(const RenderData *r, int num, bool for_render)
1558 {
1559         if (r->mode & R_SIMPLIFY) {
1560                 if (for_render)
1561                         return (int)(r->simplify_particles_render * num);
1562                 else
1563                         return (int)(r->simplify_particles * num);
1564         }
1565         else {
1566                 return num;
1567         }
1568 }
1569
1570 /**
1571   * Helper function for the SETLOOPER and SETLOOPER_VIEW_LAYER macros
1572   *
1573   * It iterates over the bases of the active layer and then the bases
1574   * of the active layer of the background (set) scenes recursively.
1575   */
1576 Base *_setlooper_base_step(Scene **sce_iter, ViewLayer *view_layer, Base *base)
1577 {
1578         if (base && base->next) {
1579                 /* Common case, step to the next. */
1580                 return base->next;
1581         }
1582         else if ((base == NULL) && (view_layer != NULL)) {
1583                 /* First time looping, return the scenes first base. */
1584                 /* For the first loop we should get the layer from workspace when available. */
1585                 if (view_layer->object_bases.first) {
1586                         return (Base *)view_layer->object_bases.first;
1587                 }
1588                 /* No base on this scene layer. */
1589                 goto next_set;
1590         }
1591         else {
1592 next_set:
1593                 /* Reached the end, get the next base in the set. */
1594                 while ((*sce_iter = (*sce_iter)->set)) {
1595                         ViewLayer *view_layer_set = BKE_view_layer_default_render((*sce_iter));
1596                         base = (Base *)view_layer_set->object_bases.first;
1597
1598                         if (base) {
1599                                 return base;
1600                         }
1601                 }
1602         }
1603
1604         return NULL;
1605 }
1606
1607 bool BKE_scene_use_shading_nodes_custom(Scene *scene)
1608 {
1609         RenderEngineType *type = RE_engines_find(scene->r.engine);
1610         return (type && type->flag & RE_USE_SHADING_NODES_CUSTOM);
1611 }
1612
1613 bool BKE_scene_use_spherical_stereo(Scene *scene)
1614 {
1615         RenderEngineType *type = RE_engines_find(scene->r.engine);
1616         return (type && type->flag & RE_USE_SPHERICAL_STEREO);
1617 }
1618
1619 bool BKE_scene_uses_blender_eevee(const Scene *scene)
1620 {
1621         return STREQ(scene->r.engine, RE_engine_id_BLENDER_EEVEE);
1622 }
1623
1624 bool BKE_scene_uses_blender_workbench(const Scene *scene)
1625 {
1626         return STREQ(scene->r.engine, RE_engine_id_BLENDER_WORKBENCH);
1627 }
1628
1629 bool BKE_scene_uses_cycles(const Scene *scene)
1630 {
1631         return STREQ(scene->r.engine, RE_engine_id_CYCLES);
1632 }
1633
1634 void BKE_scene_base_flag_to_objects(ViewLayer *view_layer)
1635 {
1636         Base *base = view_layer->object_bases.first;
1637
1638         while (base) {
1639                 BKE_scene_object_base_flag_sync_from_base(base);
1640                 base = base->next;
1641         }
1642 }
1643
1644 void BKE_scene_object_base_flag_sync_from_base(Base *base)
1645 {
1646         Object *ob = base->object;
1647
1648         ob->flag = base->flag;
1649
1650         if ((base->flag & BASE_SELECTED) != 0) {
1651                 ob->flag |= SELECT;
1652         }
1653         else {
1654                 ob->flag &= ~SELECT;
1655         }
1656 }
1657
1658 void BKE_scene_object_base_flag_sync_from_object(Base *base)
1659 {
1660         Object *ob = base->object;
1661         base->flag = ob->flag;
1662
1663         if ((ob->flag & SELECT) != 0) {
1664                 base->flag |= BASE_SELECTED;
1665                 BLI_assert((base->flag & BASE_SELECTABLE) != 0);
1666         }
1667         else {
1668                 base->flag &= ~BASE_SELECTED;
1669         }
1670 }
1671
1672 void BKE_scene_disable_color_management(Scene *scene)
1673 {
1674         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1675         ColorManagedViewSettings *view_settings = &scene->view_settings;
1676         const char *view;
1677         const char *none_display_name;
1678
1679         none_display_name = IMB_colormanagement_display_get_none_name();
1680
1681         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
1682
1683         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1684
1685         if (view) {
1686                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1687         }
1688 }
1689
1690 bool BKE_scene_check_color_management_enabled(const Scene *scene)
1691 {
1692         return !STREQ(scene->display_settings.display_device, "None");
1693 }
1694
1695 bool BKE_scene_check_rigidbody_active(const Scene *scene)
1696 {
1697         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1698 }
1699
1700 int BKE_render_num_threads(const RenderData *rd)
1701 {
1702         int threads;
1703
1704         /* override set from command line? */
1705         threads = BLI_system_num_threads_override_get();
1706
1707         if (threads > 0)
1708                 return threads;
1709
1710         /* fixed number of threads specified in scene? */
1711         if (rd->mode & R_FIXED_THREADS)
1712                 threads = rd->threads;
1713         else
1714                 threads = BLI_system_thread_count();
1715
1716         return max_ii(threads, 1);
1717 }
1718
1719 int BKE_scene_num_threads(const Scene *scene)
1720 {
1721         return BKE_render_num_threads(&scene->r);
1722 }
1723
1724 int BKE_render_preview_pixel_size(const RenderData *r)
1725 {
1726         if (r->preview_pixel_size == 0) {
1727                 return (U.pixelsize > 1.5f) ? 2 : 1;
1728         }
1729         return r->preview_pixel_size;
1730 }
1731
1732 /* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently)
1733  * and unit->scale_length.
1734  */
1735 double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value)
1736 {
1737         if (unit->system == USER_UNIT_NONE) {
1738                 /* Never apply scale_length when not using a unit setting! */
1739                 return value;
1740         }
1741
1742         switch (unit_type) {
1743                 case B_UNIT_LENGTH:
1744                         return value * (double)unit->scale_length;
1745                 case B_UNIT_AREA:
1746                         return value * pow(unit->scale_length, 2);
1747                 case B_UNIT_VOLUME:
1748                         return value * pow(unit->scale_length, 3);
1749                 case B_UNIT_MASS:
1750                         return value * pow(unit->scale_length, 3);
1751                 case B_UNIT_CAMERA:  /* *Do not* use scene's unit scale for camera focal lens! See T42026. */
1752                 default:
1753                         return value;
1754         }
1755 }
1756
1757 /******************** multiview *************************/
1758
1759 int BKE_scene_multiview_num_views_get(const RenderData *rd)
1760 {
1761         SceneRenderView *srv;
1762         int totviews = 0;
1763
1764         if ((rd->scemode & R_MULTIVIEW) == 0)
1765                 return 1;
1766
1767         if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
1768                 srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1769                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1770                         totviews++;
1771                 }
1772
1773                 srv = BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1774                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1775                         totviews++;
1776                 }
1777         }
1778         else {
1779                 for (srv = rd->views.first; srv; srv = srv->next) {
1780                         if ((srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1781                                 totviews++;
1782                         }
1783                 }
1784         }
1785         return totviews;
1786 }
1787
1788 bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
1789 {
1790         SceneRenderView *srv[2];
1791
1792         if ((rd->scemode & R_MULTIVIEW) == 0)
1793                 return false;
1794
1795         srv[0] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1796         srv[1] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1797
1798         return (srv[0] && ((srv[0]->viewflag & SCE_VIEW_DISABLE) == 0) &&
1799                 srv[1] && ((srv[1]->viewflag & SCE_VIEW_DISABLE) == 0));
1800 }
1801
1802 /* return whether to render this SceneRenderView */
1803 bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
1804 {
1805         if (srv == NULL)
1806                 return false;
1807
1808         if ((rd->scemode & R_MULTIVIEW) == 0)
1809                 return false;
1810
1811         if ((srv->viewflag & SCE_VIEW_DISABLE))
1812                 return false;
1813
1814         if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW)
1815                 return true;
1816
1817         /* SCE_VIEWS_SETUP_BASIC */
1818         if (STREQ(srv->name, STEREO_LEFT_NAME) ||
1819             STREQ(srv->name, STEREO_RIGHT_NAME))
1820         {
1821                 return true;
1822         }
1823
1824         return false;
1825 }
1826
1827 /* return true if viewname is the first or if the name is NULL or not found */
1828 bool BKE_scene_multiview_is_render_view_first(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.first; srv; srv = srv->next) {
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 /* return true if viewname is the last or if the name is NULL or not found */
1848 bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *viewname)
1849 {
1850         SceneRenderView *srv;
1851
1852         if ((rd->scemode & R_MULTIVIEW) == 0)
1853                 return true;
1854
1855         if ((!viewname) || (!viewname[0]))
1856                 return true;
1857
1858         for (srv = rd->views.last; srv; srv = srv->prev) {
1859                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1860                         return STREQ(viewname, srv->name);
1861                 }
1862         }
1863
1864         return true;
1865 }
1866
1867 SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, const int view_id)
1868 {
1869         SceneRenderView *srv;
1870         size_t nr;
1871
1872         if ((rd->scemode & R_MULTIVIEW) == 0)
1873                 return NULL;
1874
1875         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
1876                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1877                         if (nr++ == view_id)
1878                                 return srv;
1879                 }
1880         }
1881         return srv;
1882 }
1883
1884 const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const int view_id)
1885 {
1886         SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id);
1887
1888         if (srv)
1889                 return srv->name;
1890         else
1891                 return "";
1892 }
1893
1894 int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
1895 {
1896         SceneRenderView *srv;
1897         size_t nr;
1898
1899         if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0))
1900                 return 0;
1901
1902         if ((!viewname) || (!viewname[0]))
1903                 return 0;
1904
1905         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
1906                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1907                         if (STREQ(viewname, srv->name)) {
1908                                 return nr;
1909                         }
1910                         else {
1911                                 nr += 1;
1912                         }
1913                 }
1914         }
1915
1916         return 0;
1917 }
1918
1919 void BKE_scene_multiview_filepath_get(
1920         SceneRenderView *srv, const char *filepath,
1921         char *r_filepath)
1922 {
1923         BLI_strncpy(r_filepath, filepath, FILE_MAX);
1924         BLI_path_suffix(r_filepath, FILE_MAX, srv->suffix, "");
1925 }
1926
1927 /**
1928  * When multiview is not used the filepath is as usual (e.g., ``Image.jpg``).
1929  * When multiview is on, even if only one view is enabled the view is incorporated
1930  * into the file name (e.g., ``Image_L.jpg``). That allows for the user to re-render
1931  * individual views.
1932  */
1933 void BKE_scene_multiview_view_filepath_get(
1934         const RenderData *rd, const char *filepath, const char *viewname,
1935         char *r_filepath)
1936 {
1937         SceneRenderView *srv;
1938         char suffix[FILE_MAX];
1939
1940         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
1941         if (srv)
1942                 BLI_strncpy(suffix, srv->suffix, sizeof(suffix));
1943         else
1944                 BLI_strncpy(suffix, viewname, sizeof(suffix));
1945
1946         BLI_strncpy(r_filepath, filepath, FILE_MAX);
1947         BLI_path_suffix(r_filepath, FILE_MAX, suffix, "");
1948 }
1949
1950 const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char *viewname)
1951 {
1952         SceneRenderView *srv;
1953
1954         if ((viewname == NULL) || (viewname[0] == '\0'))
1955                 return viewname;
1956
1957         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
1958         if (srv)
1959                 return srv->suffix;
1960         else
1961                 return viewname;
1962 }
1963
1964 const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id)
1965 {
1966         if ((rd->scemode & R_MULTIVIEW) == 0) {
1967                 return "";
1968         }
1969         else {
1970                 const char *viewname = BKE_scene_multiview_render_view_name_get(rd, view_id);
1971                 return BKE_scene_multiview_view_suffix_get(rd, viewname);
1972         }
1973 }
1974
1975 void BKE_scene_multiview_view_prefix_get(Scene *scene, const char *name, char *rprefix, const char **rext)
1976 {
1977         SceneRenderView *srv;
1978         size_t index_act;
1979         const char *suf_act;
1980         const char delims[] = {'.', '\0'};
1981
1982         rprefix[0] = '\0';
1983
1984         /* begin of extension */
1985         index_act = BLI_str_rpartition(name, delims, rext, &suf_act);
1986         if (*rext == NULL)
1987                 return;
1988         BLI_assert(index_act > 0);
1989         UNUSED_VARS_NDEBUG(index_act);
1990
1991         for (srv = scene->r.views.first; srv; srv = srv->next) {
1992                 if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
1993                         size_t len = strlen(srv->suffix);
1994                         if (strlen(*rext) >= len && STREQLEN(*rext - len, srv->suffix, len)) {
1995                                 BLI_strncpy(rprefix, name, strlen(name) - strlen(*rext) - len + 1);
1996                                 break;
1997                         }
1998                 }
1999         }
2000 }
2001
2002 void BKE_scene_multiview_videos_dimensions_get(
2003         const RenderData *rd, const size_t width, const size_t height,
2004         size_t *r_width, size_t *r_height)
2005 {
2006         if ((rd->scemode & R_MULTIVIEW) &&
2007             rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D)
2008         {
2009                 IMB_stereo3d_write_dimensions(
2010                         rd->im_format.stereo3d_format.display_mode,
2011                         (rd->im_format.stereo3d_format.flag & S3D_SQUEEZED_FRAME) != 0,
2012                         width, height,
2013                         r_width, r_height);
2014         }
2015         else {
2016                 *r_width = width;
2017                 *r_height = height;
2018         }
2019 }
2020
2021 int BKE_scene_multiview_num_videos_get(const RenderData *rd)
2022 {
2023         if (BKE_imtype_is_movie(rd->im_format.imtype) == false)
2024                 return 0;
2025
2026         if ((rd->scemode & R_MULTIVIEW) == 0)
2027                 return 1;
2028
2029         if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2030                 return 1;
2031         }
2032         else {
2033                 /* R_IMF_VIEWS_INDIVIDUAL */
2034                 return BKE_scene_multiview_num_views_get(rd);
2035         }
2036 }
2037
2038 /* Manipulation of depsgraph storage. */
2039
2040 /* This is a key which identifies depsgraph. */
2041 typedef struct DepsgraphKey {
2042         ViewLayer *view_layer;
2043         /* TODO(sergey): Need to include window somehow (same layer might be in a
2044          * different states in different windows).
2045          */
2046 } DepsgraphKey;
2047
2048 static unsigned int depsgraph_key_hash(const void *key_v)
2049 {
2050         const DepsgraphKey *key = key_v;
2051         unsigned int hash = BLI_ghashutil_ptrhash(key->view_layer);
2052         /* TODO(sergey): Include hash from other fields in the key. */
2053         return hash;
2054 }
2055
2056 static bool depsgraph_key_compare(const void *key_a_v, const void *key_b_v)
2057 {
2058         const DepsgraphKey *key_a = key_a_v;
2059         const DepsgraphKey *key_b = key_b_v;
2060         /* TODO(sergey): Compare rest of  */
2061         return !(key_a->view_layer == key_b->view_layer);
2062 }
2063
2064 static void depsgraph_key_free(void *key_v)
2065 {
2066         DepsgraphKey *key = key_v;
2067         MEM_freeN(key);
2068 }
2069
2070 static void depsgraph_key_value_free(void *value)
2071 {
2072         Depsgraph *depsgraph = value;
2073         DEG_graph_free(depsgraph);
2074 }
2075
2076 void BKE_scene_allocate_depsgraph_hash(Scene *scene)
2077 {
2078         scene->depsgraph_hash = BLI_ghash_new(depsgraph_key_hash,
2079                                               depsgraph_key_compare,
2080                                               "Scene Depsgraph Hash");
2081 }
2082
2083 void BKE_scene_ensure_depsgraph_hash(Scene *scene)
2084 {
2085         if (scene->depsgraph_hash == NULL) {
2086                 BKE_scene_allocate_depsgraph_hash(scene);
2087         }
2088 }
2089
2090 void BKE_scene_free_depsgraph_hash(Scene *scene)
2091 {
2092         if (scene->depsgraph_hash == NULL) {
2093                 return;
2094         }
2095         BLI_ghash_free(scene->depsgraph_hash,
2096                        depsgraph_key_free,
2097                        depsgraph_key_value_free);
2098 }
2099
2100 /* Query depsgraph for a specific contexts. */
2101
2102 Depsgraph *BKE_scene_get_depsgraph(Scene *scene,
2103                                    ViewLayer *view_layer,
2104                                    bool allocate)
2105 {
2106         BLI_assert(scene != NULL);
2107         BLI_assert(view_layer != NULL);
2108         /* Make sure hash itself exists. */
2109         if (allocate) {
2110                 BKE_scene_ensure_depsgraph_hash(scene);
2111         }
2112         if (scene->depsgraph_hash == NULL) {
2113                 return NULL;
2114         }
2115         /* Either ensure item is in the hash or simply return NULL if it's not,
2116          * depending on whether caller wants us to create depsgraph or not.
2117          */
2118         DepsgraphKey key;
2119         key.view_layer = view_layer;
2120         Depsgraph *depsgraph;
2121         if (allocate) {
2122                 DepsgraphKey **key_ptr;
2123                 Depsgraph **depsgraph_ptr;
2124                 if (!BLI_ghash_ensure_p_ex(scene->depsgraph_hash,
2125                                            &key,
2126                                            (void ***)&key_ptr,
2127                                            (void ***)&depsgraph_ptr))
2128                 {
2129                         *key_ptr = MEM_mallocN(sizeof(DepsgraphKey), __func__);
2130                         **key_ptr = key;
2131                         *depsgraph_ptr = DEG_graph_new(scene, view_layer, DAG_EVAL_VIEWPORT);
2132                         /* TODO(sergey): Would be cool to avoid string format print,
2133                          * but is a bit tricky because we can't know in advance  whether
2134                          * we will ever enable debug messages for this depsgraph.
2135                          */
2136                         char name[1024];
2137                         BLI_snprintf(name, sizeof(name), "%s :: %s", scene->id.name, view_layer->name);
2138                         DEG_debug_name_set(*depsgraph_ptr, name);
2139                 }
2140                 depsgraph = *depsgraph_ptr;
2141         }
2142         else {
2143                 depsgraph = BLI_ghash_lookup(scene->depsgraph_hash, &key);
2144         }
2145         return depsgraph;
2146 }
2147
2148 /* -------------------------------------------------------------------- */
2149 /** \name Scene Orientation
2150  * \{ */
2151
2152 void BKE_scene_transform_orientation_remove(
2153         Scene *scene, TransformOrientation *orientation)
2154 {
2155         const int orientation_index = BKE_scene_transform_orientation_get_index(scene, orientation);
2156         if (scene->orientation_index_custom == orientation_index) {
2157                 /* could also use orientation_index-- */
2158                 scene->orientation_type = V3D_MANIP_GLOBAL;
2159                 scene->orientation_index_custom = -1;
2160         }
2161         BLI_freelinkN(&scene->transform_spaces, orientation);
2162 }
2163
2164 TransformOrientation *BKE_scene_transform_orientation_find(
2165         const Scene *scene, const int index)
2166 {
2167         return BLI_findlink(&scene->transform_spaces, index);
2168 }
2169
2170 /**
2171  * \return the index that \a orientation has within \a scene's transform-orientation list or -1 if not found.
2172  */
2173 int BKE_scene_transform_orientation_get_index(
2174         const Scene *scene, const TransformOrientation *orientation)
2175 {
2176         return BLI_findindex(&scene->transform_spaces, orientation);
2177 }
2178
2179 /** \} */