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