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