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