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