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