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