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