1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup bke
22  */
23 
24 #include <stddef.h>
25 #include <stdio.h>
26 #include <string.h>
27 
28 #include "MEM_guardedalloc.h"
29 
30 #include "DNA_anim_types.h"
31 #include "DNA_collection_types.h"
32 #include "DNA_curveprofile_types.h"
33 #include "DNA_defaults.h"
34 #include "DNA_gpencil_types.h"
35 #include "DNA_linestyle_types.h"
36 #include "DNA_mask_types.h"
37 #include "DNA_mesh_types.h"
38 #include "DNA_node_types.h"
39 #include "DNA_object_types.h"
40 #include "DNA_rigidbody_types.h"
41 #include "DNA_scene_types.h"
42 #include "DNA_screen_types.h"
43 #include "DNA_sequence_types.h"
44 #include "DNA_sound_types.h"
45 #include "DNA_space_types.h"
46 #include "DNA_text_types.h"
47 #include "DNA_view3d_types.h"
48 #include "DNA_windowmanager_types.h"
49 #include "DNA_workspace_types.h"
50 #include "DNA_world_types.h"
51 
52 #include "BKE_callbacks.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_math.h"
55 #include "BLI_string.h"
56 #include "BLI_string_utils.h"
57 #include "BLI_task.h"
58 #include "BLI_threads.h"
59 #include "BLI_utildefines.h"
60 
61 #include "BLT_translation.h"
62 
63 #include "BKE_action.h"
64 #include "BKE_anim_data.h"
65 #include "BKE_animsys.h"
66 #include "BKE_armature.h"
67 #include "BKE_cachefile.h"
68 #include "BKE_collection.h"
69 #include "BKE_colortools.h"
70 #include "BKE_curveprofile.h"
71 #include "BKE_duplilist.h"
72 #include "BKE_editmesh.h"
73 #include "BKE_fcurve.h"
74 #include "BKE_freestyle.h"
75 #include "BKE_gpencil.h"
76 #include "BKE_icons.h"
77 #include "BKE_idprop.h"
78 #include "BKE_idtype.h"
79 #include "BKE_image.h"
80 #include "BKE_layer.h"
81 #include "BKE_lib_id.h"
82 #include "BKE_lib_query.h"
83 #include "BKE_lib_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 
scene_init_data(ID * id)115 static void scene_init_data(ID *id)
116 {
117   Scene *scene = (Scene *)id;
118   const char *colorspace_name;
119   SceneRenderView *srv;
120   CurveMapping *mblur_shutter_curve;
121 
122   BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(scene, id));
123 
124   MEMCPY_STRUCT_AFTER(scene, DNA_struct_default_get(Scene), id);
125 
126   BLI_strncpy(scene->r.bake.filepath, U.renderdir, sizeof(scene->r.bake.filepath));
127 
128   mblur_shutter_curve = &scene->r.mblur_shutter_curve;
129   BKE_curvemapping_set_defaults(mblur_shutter_curve, 1, 0.0f, 0.0f, 1.0f, 1.0f);
130   BKE_curvemapping_init(mblur_shutter_curve);
131   BKE_curvemap_reset(mblur_shutter_curve->cm,
132                      &mblur_shutter_curve->clipr,
133                      CURVE_PRESET_MAX,
134                      CURVEMAP_SLOPE_POS_NEG);
135 
136   scene->toolsettings = DNA_struct_default_alloc(ToolSettings);
137 
138   scene->toolsettings->autokey_mode = (uchar)U.autokey_mode;
139 
140   /* grease pencil multiframe falloff curve */
141   scene->toolsettings->gp_sculpt.cur_falloff = BKE_curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
142   CurveMapping *gp_falloff_curve = scene->toolsettings->gp_sculpt.cur_falloff;
143   BKE_curvemapping_init(gp_falloff_curve);
144   BKE_curvemap_reset(
145       gp_falloff_curve->cm, &gp_falloff_curve->clipr, CURVE_PRESET_GAUSS, CURVEMAP_SLOPE_POSITIVE);
146 
147   scene->toolsettings->gp_sculpt.cur_primitive = BKE_curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
148   CurveMapping *gp_primitive_curve = scene->toolsettings->gp_sculpt.cur_primitive;
149   BKE_curvemapping_init(gp_primitive_curve);
150   BKE_curvemap_reset(gp_primitive_curve->cm,
151                      &gp_primitive_curve->clipr,
152                      CURVE_PRESET_BELL,
153                      CURVEMAP_SLOPE_POSITIVE);
154 
155   scene->unit.system = USER_UNIT_METRIC;
156   scene->unit.scale_length = 1.0f;
157   scene->unit.length_unit = (uchar)BKE_unit_base_of_type_get(USER_UNIT_METRIC, B_UNIT_LENGTH);
158   scene->unit.mass_unit = (uchar)BKE_unit_base_of_type_get(USER_UNIT_METRIC, B_UNIT_MASS);
159   scene->unit.time_unit = (uchar)BKE_unit_base_of_type_get(USER_UNIT_METRIC, B_UNIT_TIME);
160   scene->unit.temperature_unit = (uchar)BKE_unit_base_of_type_get(USER_UNIT_METRIC,
161                                                                   B_UNIT_TEMPERATURE);
162 
163   /* Anti-Aliasing threshold. */
164   scene->grease_pencil_settings.smaa_threshold = 1.0f;
165 
166   {
167     ParticleEditSettings *pset;
168     pset = &scene->toolsettings->particle;
169     for (size_t i = 1; i < ARRAY_SIZE(pset->brush); i++) {
170       pset->brush[i] = pset->brush[0];
171     }
172     pset->brush[PE_BRUSH_CUT].strength = 1.0f;
173   }
174 
175   BLI_strncpy(scene->r.engine, RE_engine_id_BLENDER_EEVEE, sizeof(scene->r.engine));
176 
177   BLI_strncpy(scene->r.pic, U.renderdir, sizeof(scene->r.pic));
178 
179   /* Note; in header_info.c the scene copy happens...,
180    * if you add more to renderdata it has to be checked there. */
181 
182   /* multiview - stereo */
183   BKE_scene_add_render_view(scene, STEREO_LEFT_NAME);
184   srv = scene->r.views.first;
185   BLI_strncpy(srv->suffix, STEREO_LEFT_SUFFIX, sizeof(srv->suffix));
186 
187   BKE_scene_add_render_view(scene, STEREO_RIGHT_NAME);
188   srv = scene->r.views.last;
189   BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix));
190 
191   BKE_sound_reset_scene_runtime(scene);
192 
193   /* color management */
194   colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
195 
196   BKE_color_managed_display_settings_init(&scene->display_settings);
197   BKE_color_managed_view_settings_init_render(
198       &scene->view_settings, &scene->display_settings, "Filmic");
199   BLI_strncpy(scene->sequencer_colorspace_settings.name,
200               colorspace_name,
201               sizeof(scene->sequencer_colorspace_settings.name));
202 
203   /* Those next two sets (render and baking settings) are not currently in use,
204    * but are exposed to RNA API and hence must have valid data. */
205   BKE_color_managed_display_settings_init(&scene->r.im_format.display_settings);
206   BKE_color_managed_view_settings_init_render(
207       &scene->r.im_format.view_settings, &scene->r.im_format.display_settings, "Filmic");
208 
209   BKE_color_managed_display_settings_init(&scene->r.bake.im_format.display_settings);
210   BKE_color_managed_view_settings_init_render(
211       &scene->r.bake.im_format.view_settings, &scene->r.bake.im_format.display_settings, "Filmic");
212 
213   /* Curve Profile */
214   scene->toolsettings->custom_bevel_profile_preset = BKE_curveprofile_add(PROF_PRESET_LINE);
215 
216   for (size_t i = 0; i < ARRAY_SIZE(scene->orientation_slots); i++) {
217     scene->orientation_slots[i].index_custom = -1;
218   }
219 
220   /* Master Collection */
221   scene->master_collection = BKE_collection_master_add();
222 
223   BKE_view_layer_add(scene, "View Layer", NULL, VIEWLAYER_ADD_NEW);
224 }
225 
scene_copy_markers(Scene * scene_dst,const Scene * scene_src,const int flag)226 static void scene_copy_markers(Scene *scene_dst, const Scene *scene_src, const int flag)
227 {
228   BLI_duplicatelist(&scene_dst->markers, &scene_src->markers);
229   LISTBASE_FOREACH (TimeMarker *, marker, &scene_dst->markers) {
230     if (marker->prop != NULL) {
231       marker->prop = IDP_CopyProperty_ex(marker->prop, flag);
232     }
233   }
234 }
235 
scene_copy_data(Main * bmain,ID * id_dst,const ID * id_src,const int flag)236 static void scene_copy_data(Main *bmain, ID *id_dst, const ID *id_src, const int flag)
237 {
238   Scene *scene_dst = (Scene *)id_dst;
239   const Scene *scene_src = (const Scene *)id_src;
240   /* We never handle usercount here for own data. */
241   const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
242   /* We always need allocation of our private ID data. */
243   const int flag_private_id_data = flag & ~LIB_ID_CREATE_NO_ALLOCATE;
244 
245   scene_dst->ed = NULL;
246   scene_dst->depsgraph_hash = NULL;
247   scene_dst->fps_info = NULL;
248 
249   /* Master Collection */
250   if (scene_src->master_collection) {
251     BKE_id_copy_ex(bmain,
252                    (ID *)scene_src->master_collection,
253                    (ID **)&scene_dst->master_collection,
254                    flag_private_id_data);
255   }
256 
257   /* View Layers */
258   BLI_duplicatelist(&scene_dst->view_layers, &scene_src->view_layers);
259   for (ViewLayer *view_layer_src = scene_src->view_layers.first,
260                  *view_layer_dst = scene_dst->view_layers.first;
261        view_layer_src;
262        view_layer_src = view_layer_src->next, view_layer_dst = view_layer_dst->next) {
263     BKE_view_layer_copy_data(scene_dst, scene_src, view_layer_dst, view_layer_src, flag_subdata);
264   }
265 
266   scene_copy_markers(scene_dst, scene_src, flag);
267 
268   BLI_duplicatelist(&(scene_dst->transform_spaces), &(scene_src->transform_spaces));
269   BLI_duplicatelist(&(scene_dst->r.views), &(scene_src->r.views));
270   BKE_keyingsets_copy(&(scene_dst->keyingsets), &(scene_src->keyingsets));
271 
272   if (scene_src->nodetree) {
273     BKE_id_copy_ex(
274         bmain, (ID *)scene_src->nodetree, (ID **)&scene_dst->nodetree, flag_private_id_data);
275     BKE_libblock_relink_ex(bmain,
276                            scene_dst->nodetree,
277                            (void *)(&scene_src->id),
278                            &scene_dst->id,
279                            ID_REMAP_SKIP_NEVER_NULL_USAGE);
280   }
281 
282   if (scene_src->rigidbody_world) {
283     scene_dst->rigidbody_world = BKE_rigidbody_world_copy(scene_src->rigidbody_world,
284                                                           flag_subdata);
285   }
286 
287   /* copy color management settings */
288   BKE_color_managed_display_settings_copy(&scene_dst->display_settings,
289                                           &scene_src->display_settings);
290   BKE_color_managed_view_settings_copy(&scene_dst->view_settings, &scene_src->view_settings);
291   BKE_color_managed_colorspace_settings_copy(&scene_dst->sequencer_colorspace_settings,
292                                              &scene_src->sequencer_colorspace_settings);
293 
294   BKE_color_managed_display_settings_copy(&scene_dst->r.im_format.display_settings,
295                                           &scene_src->r.im_format.display_settings);
296   BKE_color_managed_view_settings_copy(&scene_dst->r.im_format.view_settings,
297                                        &scene_src->r.im_format.view_settings);
298 
299   BKE_color_managed_display_settings_copy(&scene_dst->r.bake.im_format.display_settings,
300                                           &scene_src->r.bake.im_format.display_settings);
301   BKE_color_managed_view_settings_copy(&scene_dst->r.bake.im_format.view_settings,
302                                        &scene_src->r.bake.im_format.view_settings);
303 
304   BKE_curvemapping_copy_data(&scene_dst->r.mblur_shutter_curve, &scene_src->r.mblur_shutter_curve);
305 
306   /* tool settings */
307   scene_dst->toolsettings = BKE_toolsettings_copy(scene_dst->toolsettings, flag_subdata);
308 
309   /* make a private copy of the avicodecdata */
310   if (scene_src->r.avicodecdata) {
311     scene_dst->r.avicodecdata = MEM_dupallocN(scene_src->r.avicodecdata);
312     scene_dst->r.avicodecdata->lpFormat = MEM_dupallocN(scene_dst->r.avicodecdata->lpFormat);
313     scene_dst->r.avicodecdata->lpParms = MEM_dupallocN(scene_dst->r.avicodecdata->lpParms);
314   }
315 
316   if (scene_src->r.ffcodecdata.properties) {
317     /* intentionally check sce_dst not sce_src. */ /* XXX ??? comment outdated... */
318     scene_dst->r.ffcodecdata.properties = IDP_CopyProperty_ex(scene_src->r.ffcodecdata.properties,
319                                                               flag_subdata);
320   }
321 
322   if (scene_src->display.shading.prop) {
323     scene_dst->display.shading.prop = IDP_CopyProperty(scene_src->display.shading.prop);
324   }
325 
326   BKE_sound_reset_scene_runtime(scene_dst);
327 
328   /* Copy sequencer, this is local data! */
329   if (scene_src->ed) {
330     scene_dst->ed = MEM_callocN(sizeof(*scene_dst->ed), __func__);
331     scene_dst->ed->seqbasep = &scene_dst->ed->seqbase;
332     BKE_sequence_base_dupli_recursive(scene_src,
333                                       scene_dst,
334                                       &scene_dst->ed->seqbase,
335                                       &scene_src->ed->seqbase,
336                                       SEQ_DUPE_ALL,
337                                       flag_subdata);
338   }
339 
340   if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
341     BKE_previewimg_id_copy(&scene_dst->id, &scene_src->id);
342   }
343   else {
344     scene_dst->preview = NULL;
345   }
346 
347   BKE_scene_copy_data_eevee(scene_dst, scene_src);
348 }
349 
scene_free_markers(Scene * scene,bool do_id_user)350 static void scene_free_markers(Scene *scene, bool do_id_user)
351 {
352   LISTBASE_FOREACH_MUTABLE (TimeMarker *, marker, &scene->markers) {
353     if (marker->prop != NULL) {
354       IDP_FreePropertyContent_ex(marker->prop, do_id_user);
355       MEM_freeN(marker->prop);
356     }
357     MEM_freeN(marker);
358   }
359 }
360 
scene_free_data(ID * id)361 static void scene_free_data(ID *id)
362 {
363 
364   Scene *scene = (Scene *)id;
365   const bool do_id_user = false;
366 
367   BKE_sequencer_editing_free(scene, do_id_user);
368 
369   BKE_keyingsets_free(&scene->keyingsets);
370 
371   /* is no lib link block, but scene extension */
372   if (scene->nodetree) {
373     ntreeFreeEmbeddedTree(scene->nodetree);
374     MEM_freeN(scene->nodetree);
375     scene->nodetree = NULL;
376   }
377 
378   if (scene->rigidbody_world) {
379     /* Prevent rigidbody freeing code to follow other IDs pointers, this should never be allowed
380      * nor necessary from here, and with new undo code, those pointers may be fully invalid or
381      * worse, pointing to data actually belonging to new BMain! */
382     scene->rigidbody_world->constraints = NULL;
383     scene->rigidbody_world->group = NULL;
384     BKE_rigidbody_free_world(scene);
385   }
386 
387   if (scene->r.avicodecdata) {
388     free_avicodecdata(scene->r.avicodecdata);
389     MEM_freeN(scene->r.avicodecdata);
390     scene->r.avicodecdata = NULL;
391   }
392   if (scene->r.ffcodecdata.properties) {
393     IDP_FreeProperty(scene->r.ffcodecdata.properties);
394     scene->r.ffcodecdata.properties = NULL;
395   }
396 
397   scene_free_markers(scene, do_id_user);
398   BLI_freelistN(&scene->transform_spaces);
399   BLI_freelistN(&scene->r.views);
400 
401   BKE_toolsettings_free(scene->toolsettings);
402   scene->toolsettings = NULL;
403 
404   BKE_scene_free_depsgraph_hash(scene);
405 
406   MEM_SAFE_FREE(scene->fps_info);
407 
408   BKE_sound_destroy_scene(scene);
409 
410   BKE_color_managed_view_settings_free(&scene->view_settings);
411 
412   BKE_previewimg_free(&scene->preview);
413   BKE_curvemapping_free_data(&scene->r.mblur_shutter_curve);
414 
415   for (ViewLayer *view_layer = scene->view_layers.first, *view_layer_next; view_layer;
416        view_layer = view_layer_next) {
417     view_layer_next = view_layer->next;
418 
419     BLI_remlink(&scene->view_layers, view_layer);
420     BKE_view_layer_free_ex(view_layer, do_id_user);
421   }
422 
423   /* Master Collection */
424   /* TODO: what to do with do_id_user? it's also true when just
425    * closing the file which seems wrong? should decrement users
426    * for objects directly in the master collection? then other
427    * collections in the scene need to do it too? */
428   if (scene->master_collection) {
429     BKE_collection_free(scene->master_collection);
430     MEM_freeN(scene->master_collection);
431     scene->master_collection = NULL;
432   }
433 
434   if (scene->eevee.light_cache_data) {
435     EEVEE_lightcache_free(scene->eevee.light_cache_data);
436     scene->eevee.light_cache_data = NULL;
437   }
438 
439   if (scene->display.shading.prop) {
440     IDP_FreeProperty(scene->display.shading.prop);
441     scene->display.shading.prop = NULL;
442   }
443 
444   /* These are freed on doversion. */
445   BLI_assert(scene->layer_properties == NULL);
446 }
447 
scene_foreach_rigidbodyworldSceneLooper(struct RigidBodyWorld * UNUSED (rbw),ID ** id_pointer,void * user_data,int cb_flag)448 static void scene_foreach_rigidbodyworldSceneLooper(struct RigidBodyWorld *UNUSED(rbw),
449                                                     ID **id_pointer,
450                                                     void *user_data,
451                                                     int cb_flag)
452 {
453   LibraryForeachIDData *data = (LibraryForeachIDData *)user_data;
454   BKE_lib_query_foreachid_process(data, id_pointer, cb_flag);
455 }
456 
scene_foreach_paint(LibraryForeachIDData * data,Paint * paint)457 static void scene_foreach_paint(LibraryForeachIDData *data, Paint *paint)
458 {
459   BKE_LIB_FOREACHID_PROCESS(data, paint->brush, IDWALK_CB_USER);
460   for (int i = 0; i < paint->tool_slots_len; i++) {
461     BKE_LIB_FOREACHID_PROCESS(data, paint->tool_slots[i].brush, IDWALK_CB_USER);
462   }
463   BKE_LIB_FOREACHID_PROCESS(data, paint->palette, IDWALK_CB_USER);
464 }
465 
scene_foreach_toolsettings(LibraryForeachIDData * data,ToolSettings * toolsett)466 static void scene_foreach_toolsettings(LibraryForeachIDData *data, ToolSettings *toolsett)
467 {
468   BKE_LIB_FOREACHID_PROCESS(data, toolsett->particle.scene, IDWALK_CB_NOP);
469   BKE_LIB_FOREACHID_PROCESS(data, toolsett->particle.object, IDWALK_CB_NOP);
470   BKE_LIB_FOREACHID_PROCESS(data, toolsett->particle.shape_object, IDWALK_CB_NOP);
471 
472   scene_foreach_paint(data, &toolsett->imapaint.paint);
473   BKE_LIB_FOREACHID_PROCESS(data, toolsett->imapaint.stencil, IDWALK_CB_USER);
474   BKE_LIB_FOREACHID_PROCESS(data, toolsett->imapaint.clone, IDWALK_CB_USER);
475   BKE_LIB_FOREACHID_PROCESS(data, toolsett->imapaint.canvas, IDWALK_CB_USER);
476 
477   if (toolsett->vpaint) {
478     scene_foreach_paint(data, &toolsett->vpaint->paint);
479   }
480   if (toolsett->wpaint) {
481     scene_foreach_paint(data, &toolsett->wpaint->paint);
482   }
483   if (toolsett->sculpt) {
484     scene_foreach_paint(data, &toolsett->sculpt->paint);
485     BKE_LIB_FOREACHID_PROCESS(data, toolsett->sculpt->gravity_object, IDWALK_CB_NOP);
486   }
487   if (toolsett->uvsculpt) {
488     scene_foreach_paint(data, &toolsett->uvsculpt->paint);
489   }
490   if (toolsett->gp_paint) {
491     scene_foreach_paint(data, &toolsett->gp_paint->paint);
492   }
493   if (toolsett->gp_vertexpaint) {
494     scene_foreach_paint(data, &toolsett->gp_vertexpaint->paint);
495   }
496   if (toolsett->gp_sculptpaint) {
497     scene_foreach_paint(data, &toolsett->gp_sculptpaint->paint);
498   }
499   if (toolsett->gp_weightpaint) {
500     scene_foreach_paint(data, &toolsett->gp_weightpaint->paint);
501   }
502 
503   BKE_LIB_FOREACHID_PROCESS(data, toolsett->gp_sculpt.guide.reference_object, IDWALK_CB_NOP);
504 }
505 
scene_foreach_layer_collection(LibraryForeachIDData * data,ListBase * lb)506 static void scene_foreach_layer_collection(LibraryForeachIDData *data, ListBase *lb)
507 {
508   LISTBASE_FOREACH (LayerCollection *, lc, lb) {
509     /* XXX This is very weak. The whole idea of keeping pointers to private IDs is very bad
510      * anyway... */
511     const int cb_flag = (lc->collection != NULL &&
512                          (lc->collection->id.flag & LIB_EMBEDDED_DATA) != 0) ?
513                             IDWALK_CB_EMBEDDED :
514                             IDWALK_CB_NOP;
515     BKE_LIB_FOREACHID_PROCESS(data, lc->collection, cb_flag);
516     scene_foreach_layer_collection(data, &lc->layer_collections);
517   }
518 }
519 
scene_foreach_id(ID * id,LibraryForeachIDData * data)520 static void scene_foreach_id(ID *id, LibraryForeachIDData *data)
521 {
522   Scene *scene = (Scene *)id;
523 
524   BKE_LIB_FOREACHID_PROCESS(data, scene->camera, IDWALK_CB_NOP);
525   BKE_LIB_FOREACHID_PROCESS(data, scene->world, IDWALK_CB_USER);
526   BKE_LIB_FOREACHID_PROCESS(data, scene->set, IDWALK_CB_NEVER_SELF);
527   BKE_LIB_FOREACHID_PROCESS(data, scene->clip, IDWALK_CB_USER);
528   BKE_LIB_FOREACHID_PROCESS(data, scene->gpd, IDWALK_CB_USER);
529   BKE_LIB_FOREACHID_PROCESS(data, scene->r.bake.cage_object, IDWALK_CB_NOP);
530   if (scene->nodetree) {
531     /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
532     BKE_library_foreach_ID_embedded(data, (ID **)&scene->nodetree);
533   }
534   if (scene->ed) {
535     Sequence *seq;
536     SEQ_ALL_BEGIN (scene->ed, seq) {
537       BKE_LIB_FOREACHID_PROCESS(data, seq->scene, IDWALK_CB_NEVER_SELF);
538       BKE_LIB_FOREACHID_PROCESS(data, seq->scene_camera, IDWALK_CB_NOP);
539       BKE_LIB_FOREACHID_PROCESS(data, seq->clip, IDWALK_CB_USER);
540       BKE_LIB_FOREACHID_PROCESS(data, seq->mask, IDWALK_CB_USER);
541       BKE_LIB_FOREACHID_PROCESS(data, seq->sound, IDWALK_CB_USER);
542       IDP_foreach_property(
543           seq->prop, IDP_TYPE_FILTER_ID, BKE_lib_query_idpropertiesForeachIDLink_callback, data);
544       LISTBASE_FOREACH (SequenceModifierData *, smd, &seq->modifiers) {
545         BKE_LIB_FOREACHID_PROCESS(data, smd->mask_id, IDWALK_CB_USER);
546       }
547 
548       if (seq->type == SEQ_TYPE_TEXT && seq->effectdata) {
549         TextVars *text_data = seq->effectdata;
550         BKE_LIB_FOREACHID_PROCESS(data, text_data->text_font, IDWALK_CB_USER);
551       }
552     }
553     SEQ_ALL_END;
554   }
555 
556   /* This pointer can be NULL during old files reading, better be safe than sorry. */
557   if (scene->master_collection != NULL) {
558     BKE_library_foreach_ID_embedded(data, (ID **)&scene->master_collection);
559   }
560 
561   LISTBASE_FOREACH (ViewLayer *, view_layer, &scene->view_layers) {
562     BKE_LIB_FOREACHID_PROCESS(data, view_layer->mat_override, IDWALK_CB_USER);
563 
564     LISTBASE_FOREACH (Base *, base, &view_layer->object_bases) {
565       BKE_LIB_FOREACHID_PROCESS(data, base->object, IDWALK_CB_NOP);
566     }
567 
568     scene_foreach_layer_collection(data, &view_layer->layer_collections);
569 
570     LISTBASE_FOREACH (FreestyleModuleConfig *, fmc, &view_layer->freestyle_config.modules) {
571       if (fmc->script) {
572         BKE_LIB_FOREACHID_PROCESS(data, fmc->script, IDWALK_CB_NOP);
573       }
574     }
575 
576     LISTBASE_FOREACH (FreestyleLineSet *, fls, &view_layer->freestyle_config.linesets) {
577       if (fls->group) {
578         BKE_LIB_FOREACHID_PROCESS(data, fls->group, IDWALK_CB_USER);
579       }
580 
581       if (fls->linestyle) {
582         BKE_LIB_FOREACHID_PROCESS(data, fls->linestyle, IDWALK_CB_USER);
583       }
584     }
585   }
586 
587   LISTBASE_FOREACH (TimeMarker *, marker, &scene->markers) {
588     BKE_LIB_FOREACHID_PROCESS(data, marker->camera, IDWALK_CB_NOP);
589     IDP_foreach_property(
590         marker->prop, IDP_TYPE_FILTER_ID, BKE_lib_query_idpropertiesForeachIDLink_callback, data);
591   }
592 
593   ToolSettings *toolsett = scene->toolsettings;
594   if (toolsett) {
595     scene_foreach_toolsettings(data, toolsett);
596   }
597 
598   if (scene->rigidbody_world) {
599     BKE_rigidbody_world_id_loop(
600         scene->rigidbody_world, scene_foreach_rigidbodyworldSceneLooper, data);
601   }
602 }
603 
scene_foreach_cache(ID * id,IDTypeForeachCacheFunctionCallback function_callback,void * user_data)604 static void scene_foreach_cache(ID *id,
605                                 IDTypeForeachCacheFunctionCallback function_callback,
606                                 void *user_data)
607 {
608   Scene *scene = (Scene *)id;
609   IDCacheKey key = {
610       .id_session_uuid = id->session_uuid,
611       .offset_in_ID = offsetof(Scene, eevee.light_cache_data),
612       .cache_v = scene->eevee.light_cache_data,
613   };
614 
615   function_callback(id,
616                     &key,
617                     (void **)&scene->eevee.light_cache_data,
618                     IDTYPE_CACHE_CB_FLAGS_PERSISTENT,
619                     user_data);
620 }
621 
622 IDTypeInfo IDType_ID_SCE = {
623     .id_code = ID_SCE,
624     .id_filter = FILTER_ID_SCE,
625     .main_listbase_index = INDEX_ID_SCE,
626     .struct_size = sizeof(Scene),
627     .name = "Scene",
628     .name_plural = "scenes",
629     .translation_context = BLT_I18NCONTEXT_ID_SCENE,
630     .flags = 0,
631 
632     .init_data = scene_init_data,
633     .copy_data = scene_copy_data,
634     .free_data = scene_free_data,
635     /* For now default `BKE_lib_id_make_local_generic()` should work, may need more work though to
636      * support all possible corner cases. */
637     .make_local = NULL,
638     .foreach_id = scene_foreach_id,
639     .foreach_cache = scene_foreach_cache,
640 
641     .blend_write = NULL,
642     .blend_read_data = NULL,
643     .blend_read_lib = NULL,
644     .blend_read_expand = NULL,
645 };
646 
647 const char *RE_engine_id_BLENDER_EEVEE = "BLENDER_EEVEE";
648 const char *RE_engine_id_BLENDER_WORKBENCH = "BLENDER_WORKBENCH";
649 const char *RE_engine_id_CYCLES = "CYCLES";
650 
free_avicodecdata(AviCodecData * acd)651 void free_avicodecdata(AviCodecData *acd)
652 {
653   if (acd) {
654     if (acd->lpFormat) {
655       MEM_freeN(acd->lpFormat);
656       acd->lpFormat = NULL;
657       acd->cbFormat = 0;
658     }
659     if (acd->lpParms) {
660       MEM_freeN(acd->lpParms);
661       acd->lpParms = NULL;
662       acd->cbParms = 0;
663     }
664   }
665 }
666 
remove_sequencer_fcurves(Scene * sce)667 static void remove_sequencer_fcurves(Scene *sce)
668 {
669   AnimData *adt = BKE_animdata_from_id(&sce->id);
670 
671   if (adt && adt->action) {
672     FCurve *fcu, *nextfcu;
673 
674     for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
675       nextfcu = fcu->next;
676 
677       if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
678         action_groups_remove_channel(adt->action, fcu);
679         BKE_fcurve_free(fcu);
680       }
681     }
682   }
683 }
684 
685 /* flag -- copying options (see BKE_lib_id.h's LIB_ID_COPY_... flags for more). */
BKE_toolsettings_copy(ToolSettings * toolsettings,const int flag)686 ToolSettings *BKE_toolsettings_copy(ToolSettings *toolsettings, const int flag)
687 {
688   if (toolsettings == NULL) {
689     return NULL;
690   }
691   ToolSettings *ts = MEM_dupallocN(toolsettings);
692   if (ts->vpaint) {
693     ts->vpaint = MEM_dupallocN(ts->vpaint);
694     BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, flag);
695   }
696   if (ts->wpaint) {
697     ts->wpaint = MEM_dupallocN(ts->wpaint);
698     BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, flag);
699   }
700   if (ts->sculpt) {
701     ts->sculpt = MEM_dupallocN(ts->sculpt);
702     BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, flag);
703   }
704   if (ts->uvsculpt) {
705     ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
706     BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, flag);
707   }
708   if (ts->gp_paint) {
709     ts->gp_paint = MEM_dupallocN(ts->gp_paint);
710     BKE_paint_copy(&ts->gp_paint->paint, &ts->gp_paint->paint, flag);
711   }
712   if (ts->gp_vertexpaint) {
713     ts->gp_vertexpaint = MEM_dupallocN(ts->gp_vertexpaint);
714     BKE_paint_copy(&ts->gp_vertexpaint->paint, &ts->gp_vertexpaint->paint, flag);
715   }
716   if (ts->gp_sculptpaint) {
717     ts->gp_sculptpaint = MEM_dupallocN(ts->gp_sculptpaint);
718     BKE_paint_copy(&ts->gp_sculptpaint->paint, &ts->gp_sculptpaint->paint, flag);
719   }
720   if (ts->gp_weightpaint) {
721     ts->gp_weightpaint = MEM_dupallocN(ts->gp_weightpaint);
722     BKE_paint_copy(&ts->gp_weightpaint->paint, &ts->gp_weightpaint->paint, flag);
723   }
724 
725   BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, flag);
726   ts->particle.paintcursor = NULL;
727   ts->particle.scene = NULL;
728   ts->particle.object = NULL;
729 
730   /* duplicate Grease Pencil interpolation curve */
731   ts->gp_interpolate.custom_ipo = BKE_curvemapping_copy(ts->gp_interpolate.custom_ipo);
732   /* Duplicate Grease Pencil multiframe falloff. */
733   ts->gp_sculpt.cur_falloff = BKE_curvemapping_copy(ts->gp_sculpt.cur_falloff);
734   ts->gp_sculpt.cur_primitive = BKE_curvemapping_copy(ts->gp_sculpt.cur_primitive);
735 
736   ts->custom_bevel_profile_preset = BKE_curveprofile_copy(ts->custom_bevel_profile_preset);
737   return ts;
738 }
739 
BKE_toolsettings_free(ToolSettings * toolsettings)740 void BKE_toolsettings_free(ToolSettings *toolsettings)
741 {
742   if (toolsettings == NULL) {
743     return;
744   }
745   if (toolsettings->vpaint) {
746     BKE_paint_free(&toolsettings->vpaint->paint);
747     MEM_freeN(toolsettings->vpaint);
748   }
749   if (toolsettings->wpaint) {
750     BKE_paint_free(&toolsettings->wpaint->paint);
751     MEM_freeN(toolsettings->wpaint);
752   }
753   if (toolsettings->sculpt) {
754     BKE_paint_free(&toolsettings->sculpt->paint);
755     MEM_freeN(toolsettings->sculpt);
756   }
757   if (toolsettings->uvsculpt) {
758     BKE_paint_free(&toolsettings->uvsculpt->paint);
759     MEM_freeN(toolsettings->uvsculpt);
760   }
761   if (toolsettings->gp_paint) {
762     BKE_paint_free(&toolsettings->gp_paint->paint);
763     MEM_freeN(toolsettings->gp_paint);
764   }
765   if (toolsettings->gp_vertexpaint) {
766     BKE_paint_free(&toolsettings->gp_vertexpaint->paint);
767     MEM_freeN(toolsettings->gp_vertexpaint);
768   }
769   if (toolsettings->gp_sculptpaint) {
770     BKE_paint_free(&toolsettings->gp_sculptpaint->paint);
771     MEM_freeN(toolsettings->gp_sculptpaint);
772   }
773   if (toolsettings->gp_weightpaint) {
774     BKE_paint_free(&toolsettings->gp_weightpaint->paint);
775     MEM_freeN(toolsettings->gp_weightpaint);
776   }
777   BKE_paint_free(&toolsettings->imapaint.paint);
778 
779   /* free Grease Pencil interpolation curve */
780   if (toolsettings->gp_interpolate.custom_ipo) {
781     BKE_curvemapping_free(toolsettings->gp_interpolate.custom_ipo);
782   }
783   /* free Grease Pencil multiframe falloff curve */
784   if (toolsettings->gp_sculpt.cur_falloff) {
785     BKE_curvemapping_free(toolsettings->gp_sculpt.cur_falloff);
786   }
787   if (toolsettings->gp_sculpt.cur_primitive) {
788     BKE_curvemapping_free(toolsettings->gp_sculpt.cur_primitive);
789   }
790 
791   if (toolsettings->custom_bevel_profile_preset) {
792     BKE_curveprofile_free(toolsettings->custom_bevel_profile_preset);
793   }
794 
795   MEM_freeN(toolsettings);
796 }
797 
BKE_scene_copy_data_eevee(Scene * sce_dst,const Scene * sce_src)798 void BKE_scene_copy_data_eevee(Scene *sce_dst, const Scene *sce_src)
799 {
800   /* Copy eevee data between scenes. */
801   sce_dst->eevee = sce_src->eevee;
802   sce_dst->eevee.light_cache_data = NULL;
803   sce_dst->eevee.light_cache_info[0] = '\0';
804   /* TODO Copy the cache. */
805 }
806 
BKE_scene_duplicate(Main * bmain,Scene * sce,eSceneCopyMethod type)807 Scene *BKE_scene_duplicate(Main *bmain, Scene *sce, eSceneCopyMethod type)
808 {
809   Scene *sce_copy;
810 
811   /* TODO this should/could most likely be replaced by call to more generic code at some point...
812    * But for now, let's keep it well isolated here. */
813   if (type == SCE_COPY_EMPTY) {
814     ListBase rv;
815 
816     sce_copy = BKE_scene_add(bmain, sce->id.name + 2);
817 
818     rv = sce_copy->r.views;
819     BKE_curvemapping_free_data(&sce_copy->r.mblur_shutter_curve);
820     sce_copy->r = sce->r;
821     sce_copy->r.views = rv;
822     sce_copy->unit = sce->unit;
823     sce_copy->physics_settings = sce->physics_settings;
824     sce_copy->audio = sce->audio;
825     BKE_scene_copy_data_eevee(sce_copy, sce);
826 
827     if (sce->id.properties) {
828       sce_copy->id.properties = IDP_CopyProperty(sce->id.properties);
829     }
830 
831     MEM_freeN(sce_copy->toolsettings);
832     BKE_sound_destroy_scene(sce_copy);
833 
834     /* copy color management settings */
835     BKE_color_managed_display_settings_copy(&sce_copy->display_settings, &sce->display_settings);
836     BKE_color_managed_view_settings_copy(&sce_copy->view_settings, &sce->view_settings);
837     BKE_color_managed_colorspace_settings_copy(&sce_copy->sequencer_colorspace_settings,
838                                                &sce->sequencer_colorspace_settings);
839 
840     BKE_color_managed_display_settings_copy(&sce_copy->r.im_format.display_settings,
841                                             &sce->r.im_format.display_settings);
842     BKE_color_managed_view_settings_copy(&sce_copy->r.im_format.view_settings,
843                                          &sce->r.im_format.view_settings);
844 
845     BKE_color_managed_display_settings_copy(&sce_copy->r.bake.im_format.display_settings,
846                                             &sce->r.bake.im_format.display_settings);
847     BKE_color_managed_view_settings_copy(&sce_copy->r.bake.im_format.view_settings,
848                                          &sce->r.bake.im_format.view_settings);
849 
850     BKE_curvemapping_copy_data(&sce_copy->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
851 
852     /* viewport display settings */
853     sce_copy->display = sce->display;
854 
855     /* tool settings */
856     sce_copy->toolsettings = BKE_toolsettings_copy(sce->toolsettings, 0);
857 
858     /* make a private copy of the avicodecdata */
859     if (sce->r.avicodecdata) {
860       sce_copy->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
861       sce_copy->r.avicodecdata->lpFormat = MEM_dupallocN(sce_copy->r.avicodecdata->lpFormat);
862       sce_copy->r.avicodecdata->lpParms = MEM_dupallocN(sce_copy->r.avicodecdata->lpParms);
863     }
864 
865     if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
866       sce_copy->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
867     }
868 
869     BKE_sound_reset_scene_runtime(sce_copy);
870 
871     /* grease pencil */
872     sce_copy->gpd = NULL;
873 
874     sce_copy->preview = NULL;
875 
876     return sce_copy;
877   }
878 
879   eDupli_ID_Flags duplicate_flags = U.dupflag | USER_DUP_OBJECT;
880 
881   sce_copy = (Scene *)BKE_id_copy(bmain, (ID *)sce);
882   id_us_min(&sce_copy->id);
883   id_us_ensure_real(&sce_copy->id);
884 
885   BKE_animdata_duplicate_id_action(bmain, &sce_copy->id, duplicate_flags);
886 
887   /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks. */
888 
889   if (type == SCE_COPY_FULL) {
890     /* Scene duplication is always root of duplication currently. */
891     const bool is_subprocess = false;
892 
893     if (!is_subprocess) {
894       BKE_main_id_tag_all(bmain, LIB_TAG_NEW, false);
895       BKE_main_id_clear_newpoins(bmain);
896       /* In case root duplicated ID is linked, assume we want to get a local copy of it and
897        * duplicate all expected linked data. */
898       if (ID_IS_LINKED(sce)) {
899         duplicate_flags |= USER_DUP_LINKED_ID;
900       }
901     }
902 
903     /* Copy Freestyle LineStyle datablocks. */
904     LISTBASE_FOREACH (ViewLayer *, view_layer_dst, &sce_copy->view_layers) {
905       LISTBASE_FOREACH (FreestyleLineSet *, lineset, &view_layer_dst->freestyle_config.linesets) {
906         BKE_id_copy_for_duplicate(bmain, (ID *)lineset->linestyle, duplicate_flags);
907       }
908     }
909 
910     /* Full copy of world (included animations) */
911     BKE_id_copy_for_duplicate(bmain, (ID *)sce->world, duplicate_flags);
912 
913     /* Full copy of GreasePencil. */
914     BKE_id_copy_for_duplicate(bmain, (ID *)sce->gpd, duplicate_flags);
915 
916     /* Deep-duplicate collections and objects (using preferences' settings for which sub-data to
917      * duplicate along the object itself). */
918     BKE_collection_duplicate(
919         bmain, NULL, sce_copy->master_collection, duplicate_flags, LIB_ID_DUPLICATE_IS_SUBPROCESS);
920 
921     if (!is_subprocess) {
922       /* This code will follow into all ID links using an ID tagged with LIB_TAG_NEW.*/
923       BKE_libblock_relink_to_newid(&sce_copy->id);
924 
925 #ifndef NDEBUG
926       /* Call to `BKE_libblock_relink_to_newid` above is supposed to have cleared all those
927        * flags. */
928       ID *id_iter;
929       FOREACH_MAIN_ID_BEGIN (bmain, id_iter) {
930         BLI_assert((id_iter->tag & LIB_TAG_NEW) == 0);
931       }
932       FOREACH_MAIN_ID_END;
933 #endif
934 
935       /* Cleanup. */
936       BKE_main_id_tag_all(bmain, LIB_TAG_NEW, false);
937       BKE_main_id_clear_newpoins(bmain);
938 
939       BKE_main_collection_sync(bmain);
940     }
941   }
942   else {
943     /* Remove sequencer if not full copy */
944     /* XXX Why in Hell? :/ */
945     remove_sequencer_fcurves(sce_copy);
946     BKE_sequencer_editing_free(sce_copy, true);
947   }
948 
949   return sce_copy;
950 }
951 
BKE_scene_groups_relink(Scene * sce)952 void BKE_scene_groups_relink(Scene *sce)
953 {
954   if (sce->rigidbody_world) {
955     BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
956   }
957 }
958 
BKE_scene_add(Main * bmain,const char * name)959 Scene *BKE_scene_add(Main *bmain, const char *name)
960 {
961   Scene *sce;
962 
963   sce = BKE_id_new(bmain, ID_SCE, name);
964   id_us_min(&sce->id);
965   id_us_ensure_real(&sce->id);
966 
967   return sce;
968 }
969 
970 /**
971  * Check if there is any instance of the object in the scene
972  */
BKE_scene_object_find(Scene * scene,Object * ob)973 bool BKE_scene_object_find(Scene *scene, Object *ob)
974 {
975   LISTBASE_FOREACH (ViewLayer *, view_layer, &scene->view_layers) {
976     if (BLI_findptr(&view_layer->object_bases, ob, offsetof(Base, object))) {
977       return true;
978     }
979   }
980   return false;
981 }
982 
BKE_scene_object_find_by_name(const Scene * scene,const char * name)983 Object *BKE_scene_object_find_by_name(const Scene *scene, const char *name)
984 {
985   LISTBASE_FOREACH (ViewLayer *, view_layer, &scene->view_layers) {
986     LISTBASE_FOREACH (Base *, base, &view_layer->object_bases) {
987       if (STREQ(base->object->id.name + 2, name)) {
988         return base->object;
989       }
990     }
991   }
992   return NULL;
993 }
994 
995 /**
996  * Sets the active scene, mainly used when running in background mode
997  * (``--scene`` command line argument).
998  * This is also called to set the scene directly, bypassing windowing code.
999  * Otherwise #WM_window_set_active_scene is used when changing scenes by the user.
1000  */
BKE_scene_set_background(Main * bmain,Scene * scene)1001 void BKE_scene_set_background(Main *bmain, Scene *scene)
1002 {
1003   Object *ob;
1004 
1005   /* check for cyclic sets, for reading old files but also for definite security (py?) */
1006   BKE_scene_validate_setscene(bmain, scene);
1007 
1008   /* deselect objects (for dataselect) */
1009   for (ob = bmain->objects.first; ob; ob = ob->id.next) {
1010     ob->flag &= ~SELECT;
1011   }
1012 
1013   /* copy layers and flags from bases to objects */
1014   LISTBASE_FOREACH (ViewLayer *, view_layer, &scene->view_layers) {
1015     LISTBASE_FOREACH (Base *, base, &view_layer->object_bases) {
1016       ob = base->object;
1017       /* collection patch... */
1018       BKE_scene_object_base_flag_sync_from_base(base);
1019     }
1020   }
1021   /* No full animation update, this to enable render code to work
1022    * (render code calls own animation updates). */
1023 }
1024 
1025 /* called from creator_args.c */
BKE_scene_set_name(Main * bmain,const char * name)1026 Scene *BKE_scene_set_name(Main *bmain, const char *name)
1027 {
1028   Scene *sce = (Scene *)BKE_libblock_find_name(bmain, ID_SCE, name);
1029   if (sce) {
1030     BKE_scene_set_background(bmain, sce);
1031     printf("Scene switch for render: '%s' in file: '%s'\n", name, BKE_main_blendfile_path(bmain));
1032     return sce;
1033   }
1034 
1035   printf("Can't find scene: '%s' in file: '%s'\n", name, BKE_main_blendfile_path(bmain));
1036   return NULL;
1037 }
1038 
1039 /* Used by meta-balls, return *all* objects (including duplis)
1040  * existing in the scene (including scene's sets). */
BKE_scene_base_iter_next(Depsgraph * depsgraph,SceneBaseIter * iter,Scene ** scene,int val,Base ** base,Object ** ob)1041 int BKE_scene_base_iter_next(
1042     Depsgraph *depsgraph, SceneBaseIter *iter, Scene **scene, int val, Base **base, Object **ob)
1043 {
1044   bool run_again = true;
1045 
1046   /* init */
1047   if (val == 0) {
1048     iter->phase = F_START;
1049     iter->dupob = NULL;
1050     iter->duplilist = NULL;
1051     iter->dupli_refob = NULL;
1052   }
1053   else {
1054     /* run_again is set when a duplilist has been ended */
1055     while (run_again) {
1056       run_again = false;
1057 
1058       /* the first base */
1059       if (iter->phase == F_START) {
1060         ViewLayer *view_layer = (depsgraph) ? DEG_get_evaluated_view_layer(depsgraph) :
1061                                               BKE_view_layer_context_active_PLACEHOLDER(*scene);
1062         *base = view_layer->object_bases.first;
1063         if (*base) {
1064           *ob = (*base)->object;
1065           iter->phase = F_SCENE;
1066         }
1067         else {
1068           /* exception: empty scene layer */
1069           while ((*scene)->set) {
1070             (*scene) = (*scene)->set;
1071             ViewLayer *view_layer_set = BKE_view_layer_default_render((*scene));
1072             if (view_layer_set->object_bases.first) {
1073               *base = view_layer_set->object_bases.first;
1074               *ob = (*base)->object;
1075               iter->phase = F_SCENE;
1076               break;
1077             }
1078           }
1079         }
1080       }
1081       else {
1082         if (*base && iter->phase != F_DUPLI) {
1083           *base = (*base)->next;
1084           if (*base) {
1085             *ob = (*base)->object;
1086           }
1087           else {
1088             if (iter->phase == F_SCENE) {
1089               /* (*scene) is finished, now do the set */
1090               while ((*scene)->set) {
1091                 (*scene) = (*scene)->set;
1092                 ViewLayer *view_layer_set = BKE_view_layer_default_render((*scene));
1093                 if (view_layer_set->object_bases.first) {
1094                   *base = view_layer_set->object_bases.first;
1095                   *ob = (*base)->object;
1096                   break;
1097                 }
1098               }
1099             }
1100           }
1101         }
1102       }
1103 
1104       if (*base == NULL) {
1105         iter->phase = F_START;
1106       }
1107       else {
1108         if (iter->phase != F_DUPLI) {
1109           if (depsgraph && (*base)->object->transflag & OB_DUPLI) {
1110             /* Collections cannot be duplicated for meta-balls yet,
1111              * this enters eternal loop because of
1112              * makeDispListMBall getting called inside of collection_duplilist */
1113             if ((*base)->object->instance_collection == NULL) {
1114               iter->duplilist = object_duplilist(depsgraph, (*scene), (*base)->object);
1115 
1116               iter->dupob = iter->duplilist->first;
1117 
1118               if (!iter->dupob) {
1119                 free_object_duplilist(iter->duplilist);
1120                 iter->duplilist = NULL;
1121               }
1122               iter->dupli_refob = NULL;
1123             }
1124           }
1125         }
1126         /* handle dupli's */
1127         if (iter->dupob) {
1128           (*base)->flag_legacy |= OB_FROMDUPLI;
1129           *ob = iter->dupob->ob;
1130           iter->phase = F_DUPLI;
1131 
1132           if (iter->dupli_refob != *ob) {
1133             if (iter->dupli_refob) {
1134               /* Restore previous object's real matrix. */
1135               copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1136             }
1137             /* Backup new object's real matrix. */
1138             iter->dupli_refob = *ob;
1139             copy_m4_m4(iter->omat, iter->dupli_refob->obmat);
1140           }
1141           copy_m4_m4((*ob)->obmat, iter->dupob->mat);
1142 
1143           iter->dupob = iter->dupob->next;
1144         }
1145         else if (iter->phase == F_DUPLI) {
1146           iter->phase = F_SCENE;
1147           (*base)->flag_legacy &= ~OB_FROMDUPLI;
1148 
1149           if (iter->dupli_refob) {
1150             /* Restore last object's real matrix. */
1151             copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1152             iter->dupli_refob = NULL;
1153           }
1154 
1155           free_object_duplilist(iter->duplilist);
1156           iter->duplilist = NULL;
1157           run_again = true;
1158         }
1159       }
1160     }
1161   }
1162 
1163   return iter->phase;
1164 }
1165 
BKE_scene_has_view_layer(const Scene * scene,const ViewLayer * layer)1166 bool BKE_scene_has_view_layer(const Scene *scene, const ViewLayer *layer)
1167 {
1168   return BLI_findindex(&scene->view_layers, layer) != -1;
1169 }
1170 
BKE_scene_find_from_collection(const Main * bmain,const Collection * collection)1171 Scene *BKE_scene_find_from_collection(const Main *bmain, const Collection *collection)
1172 {
1173   for (Scene *scene = bmain->scenes.first; scene; scene = scene->id.next) {
1174     LISTBASE_FOREACH (ViewLayer *, layer, &scene->view_layers) {
1175       if (BKE_view_layer_has_collection(layer, collection)) {
1176         return scene;
1177       }
1178     }
1179   }
1180 
1181   return NULL;
1182 }
1183 
1184 #ifdef DURIAN_CAMERA_SWITCH
BKE_scene_camera_switch_find(Scene * scene)1185 Object *BKE_scene_camera_switch_find(Scene *scene)
1186 {
1187   if (scene->r.mode & R_NO_CAMERA_SWITCH) {
1188     return NULL;
1189   }
1190 
1191   const int cfra = ((scene->r.images == scene->r.framapto) ?
1192                         scene->r.cfra :
1193                         (int)(scene->r.cfra *
1194                               ((float)scene->r.framapto / (float)scene->r.images)));
1195   int frame = -(MAXFRAME + 1);
1196   int min_frame = MAXFRAME + 1;
1197   Object *camera = NULL;
1198   Object *first_camera = NULL;
1199 
1200   LISTBASE_FOREACH (TimeMarker *, m, &scene->markers) {
1201     if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
1202       if ((m->frame <= cfra) && (m->frame > frame)) {
1203         camera = m->camera;
1204         frame = m->frame;
1205 
1206         if (frame == cfra) {
1207           break;
1208         }
1209       }
1210 
1211       if (m->frame < min_frame) {
1212         first_camera = m->camera;
1213         min_frame = m->frame;
1214       }
1215     }
1216   }
1217 
1218   if (camera == NULL) {
1219     /* If there's no marker to the left of current frame,
1220      * use camera from left-most marker to solve all sort
1221      * of Schrodinger uncertainties.
1222      */
1223     return first_camera;
1224   }
1225 
1226   return camera;
1227 }
1228 #endif
1229 
BKE_scene_camera_switch_update(Scene * scene)1230 bool BKE_scene_camera_switch_update(Scene *scene)
1231 {
1232 #ifdef DURIAN_CAMERA_SWITCH
1233   Object *camera = BKE_scene_camera_switch_find(scene);
1234   if (camera && (camera != scene->camera)) {
1235     scene->camera = camera;
1236     DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE);
1237     return true;
1238   }
1239 #else
1240   (void)scene;
1241 #endif
1242   return false;
1243 }
1244 
BKE_scene_find_marker_name(const Scene * scene,int frame)1245 const char *BKE_scene_find_marker_name(const Scene *scene, int frame)
1246 {
1247   const ListBase *markers = &scene->markers;
1248   const TimeMarker *m1, *m2;
1249 
1250   /* search through markers for match */
1251   for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
1252     if (m1->frame == frame) {
1253       return m1->name;
1254     }
1255 
1256     if (m1 == m2) {
1257       break;
1258     }
1259 
1260     if (m2->frame == frame) {
1261       return m2->name;
1262     }
1263   }
1264 
1265   return NULL;
1266 }
1267 
1268 /* return the current marker for this frame,
1269  * we can have more than 1 marker per frame, this just returns the first :/ */
BKE_scene_find_last_marker_name(const Scene * scene,int frame)1270 const char *BKE_scene_find_last_marker_name(const Scene *scene, int frame)
1271 {
1272   const TimeMarker *marker, *best_marker = NULL;
1273   int best_frame = -MAXFRAME * 2;
1274   for (marker = scene->markers.first; marker; marker = marker->next) {
1275     if (marker->frame == frame) {
1276       return marker->name;
1277     }
1278 
1279     if (marker->frame > best_frame && marker->frame < frame) {
1280       best_marker = marker;
1281       best_frame = marker->frame;
1282     }
1283   }
1284 
1285   return best_marker ? best_marker->name : NULL;
1286 }
1287 
BKE_scene_frame_snap_by_seconds(Scene * scene,double interval_in_seconds,int cfra)1288 int BKE_scene_frame_snap_by_seconds(Scene *scene, double interval_in_seconds, int cfra)
1289 {
1290   const int fps = round_db_to_int(FPS * interval_in_seconds);
1291   const int second_prev = cfra - mod_i(cfra, fps);
1292   const int second_next = second_prev + fps;
1293   const int delta_prev = cfra - second_prev;
1294   const int delta_next = second_next - cfra;
1295   return (delta_prev < delta_next) ? second_prev : second_next;
1296 }
1297 
BKE_scene_remove_rigidbody_object(struct Main * bmain,Scene * scene,Object * ob,const bool free_us)1298 void BKE_scene_remove_rigidbody_object(struct Main *bmain,
1299                                        Scene *scene,
1300                                        Object *ob,
1301                                        const bool free_us)
1302 {
1303   /* remove rigid body constraint from world before removing object */
1304   if (ob->rigidbody_constraint) {
1305     BKE_rigidbody_remove_constraint(bmain, scene, ob, free_us);
1306   }
1307   /* remove rigid body object from world before removing object */
1308   if (ob->rigidbody_object) {
1309     BKE_rigidbody_remove_object(bmain, scene, ob, free_us);
1310   }
1311 }
1312 
1313 /* checks for cycle, returns 1 if it's all OK */
BKE_scene_validate_setscene(Main * bmain,Scene * sce)1314 bool BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1315 {
1316   Scene *sce_iter;
1317   int a, totscene;
1318 
1319   if (sce->set == NULL) {
1320     return true;
1321   }
1322   totscene = BLI_listbase_count(&bmain->scenes);
1323 
1324   for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) {
1325     /* more iterations than scenes means we have a cycle */
1326     if (a > totscene) {
1327       /* the tested scene gets zero'ed, that's typically current scene */
1328       sce->set = NULL;
1329       return false;
1330     }
1331   }
1332 
1333   return true;
1334 }
1335 
1336 /**
1337  * This function is needed to cope with fractional frames, needed for motion blur & physics.
1338  */
BKE_scene_frame_get(const Scene * scene)1339 float BKE_scene_frame_get(const Scene *scene)
1340 {
1341   return BKE_scene_frame_to_ctime(scene, scene->r.cfra);
1342 }
1343 
1344 /* This function is used to obtain arbitrary fractional frames */
BKE_scene_frame_to_ctime(const Scene * scene,const float frame)1345 float BKE_scene_frame_to_ctime(const Scene *scene, const float frame)
1346 {
1347   float ctime = frame;
1348   ctime += scene->r.subframe;
1349   ctime *= scene->r.framelen;
1350 
1351   return ctime;
1352 }
1353 /**
1354  * Sets the frame int/float components.
1355  */
BKE_scene_frame_set(struct Scene * scene,double cfra)1356 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1357 {
1358   double intpart;
1359   scene->r.subframe = modf(cfra, &intpart);
1360   scene->r.cfra = (int)intpart;
1361 }
1362 
1363 /* -------------------------------------------------------------------- */
1364 /** \name Scene Orientation Slots
1365  * \{ */
1366 
BKE_scene_orientation_slot_get(Scene * scene,int slot_index)1367 TransformOrientationSlot *BKE_scene_orientation_slot_get(Scene *scene, int slot_index)
1368 {
1369   if ((scene->orientation_slots[slot_index].flag & SELECT) == 0) {
1370     slot_index = SCE_ORIENT_DEFAULT;
1371   }
1372   return &scene->orientation_slots[slot_index];
1373 }
1374 
BKE_scene_orientation_slot_get_from_flag(Scene * scene,int flag)1375 TransformOrientationSlot *BKE_scene_orientation_slot_get_from_flag(Scene *scene, int flag)
1376 {
1377   BLI_assert(flag && !(flag & ~(V3D_GIZMO_SHOW_OBJECT_TRANSLATE | V3D_GIZMO_SHOW_OBJECT_ROTATE |
1378                                 V3D_GIZMO_SHOW_OBJECT_SCALE)));
1379   int slot_index = SCE_ORIENT_DEFAULT;
1380   if (flag & V3D_GIZMO_SHOW_OBJECT_TRANSLATE) {
1381     slot_index = SCE_ORIENT_TRANSLATE;
1382   }
1383   else if (flag & V3D_GIZMO_SHOW_OBJECT_ROTATE) {
1384     slot_index = SCE_ORIENT_ROTATE;
1385   }
1386   else if (flag & V3D_GIZMO_SHOW_OBJECT_SCALE) {
1387     slot_index = SCE_ORIENT_SCALE;
1388   }
1389   return BKE_scene_orientation_slot_get(scene, slot_index);
1390 }
1391 
1392 /**
1393  * Activate a transform orientation in a 3D view based on an enum value.
1394  *
1395  * \param orientation: If this is #V3D_ORIENT_CUSTOM or greater, the custom transform orientation
1396  * with index \a orientation - #V3D_ORIENT_CUSTOM gets activated.
1397  */
BKE_scene_orientation_slot_set_index(TransformOrientationSlot * orient_slot,int orientation)1398 void BKE_scene_orientation_slot_set_index(TransformOrientationSlot *orient_slot, int orientation)
1399 {
1400   const bool is_custom = orientation >= V3D_ORIENT_CUSTOM;
1401   orient_slot->type = is_custom ? V3D_ORIENT_CUSTOM : orientation;
1402   orient_slot->index_custom = is_custom ? (orientation - V3D_ORIENT_CUSTOM) : -1;
1403 }
1404 
BKE_scene_orientation_slot_get_index(const TransformOrientationSlot * orient_slot)1405 int BKE_scene_orientation_slot_get_index(const TransformOrientationSlot *orient_slot)
1406 {
1407   return (orient_slot->type == V3D_ORIENT_CUSTOM) ?
1408              (orient_slot->type + orient_slot->index_custom) :
1409              orient_slot->type;
1410 }
1411 
1412 /** \} */
1413 
check_rendered_viewport_visible(Main * bmain)1414 static bool check_rendered_viewport_visible(Main *bmain)
1415 {
1416   wmWindowManager *wm = bmain->wm.first;
1417   wmWindow *window;
1418   for (window = wm->windows.first; window != NULL; window = window->next) {
1419     const bScreen *screen = BKE_workspace_active_screen_get(window->workspace_hook);
1420     Scene *scene = window->scene;
1421     RenderEngineType *type = RE_engines_find(scene->r.engine);
1422 
1423     if (type->draw_engine || !type->render) {
1424       continue;
1425     }
1426 
1427     for (ScrArea *area = screen->areabase.first; area != NULL; area = area->next) {
1428       View3D *v3d = area->spacedata.first;
1429       if (area->spacetype != SPACE_VIEW3D) {
1430         continue;
1431       }
1432       if (v3d->shading.type == OB_RENDER) {
1433         return true;
1434       }
1435     }
1436   }
1437   return false;
1438 }
1439 
1440 /* TODO(campbell): shouldn't we be able to use 'DEG_get_view_layer' here?
1441  * Currently this is NULL on load, so don't. */
prepare_mesh_for_viewport_render(Main * bmain,const ViewLayer * view_layer)1442 static void prepare_mesh_for_viewport_render(Main *bmain, const ViewLayer *view_layer)
1443 {
1444   /* This is needed to prepare mesh to be used by the render
1445    * engine from the viewport rendering. We do loading here
1446    * so all the objects which shares the same mesh datablock
1447    * are nicely tagged for update and updated.
1448    *
1449    * This makes it so viewport render engine doesn't need to
1450    * call loading of the edit data for the mesh objects.
1451    */
1452 
1453   Object *obedit = OBEDIT_FROM_VIEW_LAYER(view_layer);
1454   if (obedit) {
1455     Mesh *mesh = obedit->data;
1456     if ((obedit->type == OB_MESH) &&
1457         ((obedit->id.recalc & ID_RECALC_ALL) || (mesh->id.recalc & ID_RECALC_ALL))) {
1458       if (check_rendered_viewport_visible(bmain)) {
1459         BMesh *bm = mesh->edit_mesh->bm;
1460         BM_mesh_bm_to_me(bmain,
1461                          bm,
1462                          mesh,
1463                          (&(struct BMeshToMeshParams){
1464                              .calc_object_remap = true,
1465                              .update_shapekey_indices = true,
1466                          }));
1467         DEG_id_tag_update(&mesh->id, 0);
1468       }
1469     }
1470   }
1471 }
1472 
BKE_scene_update_sound(Depsgraph * depsgraph,Main * bmain)1473 void BKE_scene_update_sound(Depsgraph *depsgraph, Main *bmain)
1474 {
1475   Scene *scene = DEG_get_evaluated_scene(depsgraph);
1476   const int recalc = scene->id.recalc;
1477   BKE_sound_ensure_scene(scene);
1478   if (recalc & ID_RECALC_AUDIO_SEEK) {
1479     BKE_sound_seek_scene(bmain, scene);
1480   }
1481   if (recalc & ID_RECALC_AUDIO_FPS) {
1482     BKE_sound_update_fps(bmain, scene);
1483   }
1484   if (recalc & ID_RECALC_AUDIO_VOLUME) {
1485     BKE_sound_set_scene_volume(scene, scene->audio.volume);
1486   }
1487   if (recalc & ID_RECALC_AUDIO_MUTE) {
1488     const bool is_mute = (scene->audio.flag & AUDIO_MUTE);
1489     BKE_sound_mute_scene(scene, is_mute);
1490   }
1491   if (recalc & ID_RECALC_AUDIO_LISTENER) {
1492     BKE_sound_update_scene_listener(scene);
1493   }
1494   BKE_sound_update_scene(depsgraph, scene);
1495 }
1496 
BKE_scene_update_tag_audio_volume(Depsgraph * UNUSED (depsgraph),Scene * scene)1497 void BKE_scene_update_tag_audio_volume(Depsgraph *UNUSED(depsgraph), Scene *scene)
1498 {
1499   BLI_assert(DEG_is_evaluated_id(&scene->id));
1500   /* The volume is actually updated in BKE_scene_update_sound(), from either
1501    * scene_graph_update_tagged() or from BKE_scene_graph_update_for_newframe(). */
1502   scene->id.recalc |= ID_RECALC_AUDIO_VOLUME;
1503 }
1504 
1505 /* TODO(sergey): This actually should become view_layer_graph or so.
1506  * Same applies to update_for_newframe.
1507  *
1508  * If only_if_tagged is truth then the function will do nothing if the dependency graph is up
1509  * to date already.
1510  */
scene_graph_update_tagged(Depsgraph * depsgraph,Main * bmain,bool only_if_tagged)1511 static void scene_graph_update_tagged(Depsgraph *depsgraph, Main *bmain, bool only_if_tagged)
1512 {
1513   if (only_if_tagged && DEG_is_fully_evaluated(depsgraph)) {
1514     return;
1515   }
1516 
1517   Scene *scene = DEG_get_input_scene(depsgraph);
1518   ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1519 
1520   bool run_callbacks = DEG_id_type_any_updated(depsgraph);
1521   if (run_callbacks) {
1522     BKE_callback_exec_id(bmain, &scene->id, BKE_CB_EVT_DEPSGRAPH_UPDATE_PRE);
1523   }
1524 
1525   for (int pass = 0; pass < 2; pass++) {
1526     /* (Re-)build dependency graph if needed. */
1527     DEG_graph_relations_update(depsgraph);
1528     /* Uncomment this to check if graph was properly tagged for update. */
1529     // DEG_debug_graph_relations_validate(depsgraph, bmain, scene);
1530     /* Flush editing data if needed. */
1531     prepare_mesh_for_viewport_render(bmain, view_layer);
1532     /* Update all objects: drivers, matrices, displists, etc. flags set
1533      * by depsgraph or manual, no layer check here, gets correct flushed. */
1534     DEG_evaluate_on_refresh(depsgraph);
1535     /* Update sound system. */
1536     BKE_scene_update_sound(depsgraph, bmain);
1537     /* Notify python about depsgraph update. */
1538     if (run_callbacks) {
1539       BKE_callback_exec_id_depsgraph(
1540           bmain, &scene->id, depsgraph, BKE_CB_EVT_DEPSGRAPH_UPDATE_POST);
1541 
1542       /* It is possible that the custom callback modified scene and removed some IDs from the main
1543        * database. In this case DEG_ids_clear_recalc() will crash because it iterates over all IDs
1544        * which depsgraph was built for.
1545        *
1546        * The solution is to update relations prior to this call, avoiding access to freed IDs.
1547        * Should be safe because relations update is supposed to preserve flags of all IDs which are
1548        * still a part of the dependency graph. If an ID is kicked out of the dependency graph it
1549        * should also be fine because when/if it's added to another dependency graph it will need to
1550        * be tagged for an update anyway.
1551        *
1552        * If there are no relations changed by the callback this call will do nothing. */
1553       DEG_graph_relations_update(depsgraph);
1554     }
1555     /* Inform editors about possible changes. */
1556     DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, false);
1557     /* Clear recalc flags. */
1558     DEG_ids_clear_recalc(bmain, depsgraph);
1559 
1560     /* If user callback did not tag anything for update we can skip second iteration.
1561      * Otherwise we update scene once again, but without running callbacks to bring
1562      * scene to a fully evaluated state with user modifications taken into account. */
1563     if (DEG_is_fully_evaluated(depsgraph)) {
1564       break;
1565     }
1566 
1567     run_callbacks = false;
1568   }
1569 }
1570 
BKE_scene_graph_update_tagged(Depsgraph * depsgraph,Main * bmain)1571 void BKE_scene_graph_update_tagged(Depsgraph *depsgraph, Main *bmain)
1572 {
1573   scene_graph_update_tagged(depsgraph, bmain, false);
1574 }
1575 
BKE_scene_graph_evaluated_ensure(Depsgraph * depsgraph,Main * bmain)1576 void BKE_scene_graph_evaluated_ensure(Depsgraph *depsgraph, Main *bmain)
1577 {
1578   scene_graph_update_tagged(depsgraph, bmain, true);
1579 }
1580 
1581 /* applies changes right away, does all sets too */
BKE_scene_graph_update_for_newframe(Depsgraph * depsgraph)1582 void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph)
1583 {
1584   Scene *scene = DEG_get_input_scene(depsgraph);
1585   ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
1586   Main *bmain = DEG_get_bmain(depsgraph);
1587 
1588   /* Keep this first. */
1589   BKE_callback_exec_id(bmain, &scene->id, BKE_CB_EVT_FRAME_CHANGE_PRE);
1590 
1591   for (int pass = 0; pass < 2; pass++) {
1592     /* Update animated image textures for particles, modifiers, gpu, etc,
1593      * call this at the start so modifiers with textures don't lag 1 frame.
1594      */
1595     BKE_image_editors_update_frame(bmain, scene->r.cfra);
1596     BKE_sound_set_cfra(scene->r.cfra);
1597     DEG_graph_relations_update(depsgraph);
1598     /* Update all objects: drivers, matrices, displists, etc. flags set
1599      * by depgraph or manual, no layer check here, gets correct flushed.
1600      *
1601      * NOTE: Only update for new frame on first iteration. Second iteration is for ensuring user
1602      * edits from callback are properly taken into account. Doing a time update on those would
1603      * lose any possible unkeyed changes made by the handler. */
1604     if (pass == 0) {
1605       const float ctime = BKE_scene_frame_get(scene);
1606       DEG_evaluate_on_framechange(depsgraph, ctime);
1607     }
1608     else {
1609       DEG_evaluate_on_refresh(depsgraph);
1610     }
1611     /* Update sound system animation. */
1612     BKE_scene_update_sound(depsgraph, bmain);
1613 
1614     /* Notify editors and python about recalc. */
1615     if (pass == 0) {
1616       BKE_callback_exec_id_depsgraph(bmain, &scene->id, depsgraph, BKE_CB_EVT_FRAME_CHANGE_POST);
1617 
1618       /* NOTE: Similar to this case in scene_graph_update_tagged(). Need to ensure that
1619        * DEG_ids_clear_recalc() doesn't access freed memory of possibly removed ID. */
1620       DEG_graph_relations_update(depsgraph);
1621     }
1622 
1623     /* Inform editors about possible changes. */
1624     DEG_ids_check_recalc(bmain, depsgraph, scene, view_layer, true);
1625     /* clear recalc flags */
1626     DEG_ids_clear_recalc(bmain, depsgraph);
1627 
1628     /* If user callback did not tag anything for update we can skip second iteration.
1629      * Otherwise we update scene once again, but without running callbacks to bring
1630      * scene to a fully evaluated state with user modifications taken into account. */
1631     if (DEG_is_fully_evaluated(depsgraph)) {
1632       break;
1633     }
1634   }
1635 }
1636 
1637 /**
1638  * Ensures given scene/view_layer pair has a valid, up-to-date depsgraph.
1639  *
1640  * \warning Sets matching depsgraph as active,
1641  * so should only be called from the active editing context (usually, from operators).
1642  */
BKE_scene_view_layer_graph_evaluated_ensure(Main * bmain,Scene * scene,ViewLayer * view_layer)1643 void BKE_scene_view_layer_graph_evaluated_ensure(Main *bmain, Scene *scene, ViewLayer *view_layer)
1644 {
1645   Depsgraph *depsgraph = BKE_scene_ensure_depsgraph(bmain, scene, view_layer);
1646   DEG_make_active(depsgraph);
1647   BKE_scene_graph_update_tagged(depsgraph, bmain);
1648 }
1649 
1650 /* return default view */
BKE_scene_add_render_view(Scene * sce,const char * name)1651 SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name)
1652 {
1653   SceneRenderView *srv;
1654 
1655   if (!name) {
1656     name = DATA_("RenderView");
1657   }
1658 
1659   srv = MEM_callocN(sizeof(SceneRenderView), "new render view");
1660   BLI_strncpy(srv->name, name, sizeof(srv->name));
1661   BLI_uniquename(&sce->r.views,
1662                  srv,
1663                  DATA_("RenderView"),
1664                  '.',
1665                  offsetof(SceneRenderView, name),
1666                  sizeof(srv->name));
1667   BLI_addtail(&sce->r.views, srv);
1668 
1669   return srv;
1670 }
1671 
BKE_scene_remove_render_view(Scene * scene,SceneRenderView * srv)1672 bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
1673 {
1674   const int act = BLI_findindex(&scene->r.views, srv);
1675 
1676   if (act == -1) {
1677     return false;
1678   }
1679   if (scene->r.views.first == scene->r.views.last) {
1680     /* ensure 1 view is kept */
1681     return false;
1682   }
1683 
1684   BLI_remlink(&scene->r.views, srv);
1685   MEM_freeN(srv);
1686 
1687   scene->r.actview = 0;
1688 
1689   return true;
1690 }
1691 
1692 /* render simplification */
1693 
get_render_subsurf_level(const RenderData * r,int lvl,bool for_render)1694 int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
1695 {
1696   if (r->mode & R_SIMPLIFY) {
1697     if (for_render) {
1698       return min_ii(r->simplify_subsurf_render, lvl);
1699     }
1700 
1701     return min_ii(r->simplify_subsurf, lvl);
1702   }
1703 
1704   return lvl;
1705 }
1706 
get_render_child_particle_number(const RenderData * r,int num,bool for_render)1707 int get_render_child_particle_number(const RenderData *r, int num, bool for_render)
1708 {
1709   if (r->mode & R_SIMPLIFY) {
1710     if (for_render) {
1711       return (int)(r->simplify_particles_render * num);
1712     }
1713 
1714     return (int)(r->simplify_particles * num);
1715   }
1716 
1717   return num;
1718 }
1719 
1720 /**
1721  * Helper function for the SETLOOPER and SETLOOPER_VIEW_LAYER macros
1722  *
1723  * It iterates over the bases of the active layer and then the bases
1724  * of the active layer of the background (set) scenes recursively.
1725  */
_setlooper_base_step(Scene ** sce_iter,ViewLayer * view_layer,Base * base)1726 Base *_setlooper_base_step(Scene **sce_iter, ViewLayer *view_layer, Base *base)
1727 {
1728   if (base && base->next) {
1729     /* Common case, step to the next. */
1730     return base->next;
1731   }
1732   if ((base == NULL) && (view_layer != NULL)) {
1733     /* First time looping, return the scenes first base. */
1734     /* For the first loop we should get the layer from workspace when available. */
1735     if (view_layer->object_bases.first) {
1736       return (Base *)view_layer->object_bases.first;
1737     }
1738     /* No base on this scene layer. */
1739     goto next_set;
1740   }
1741   else {
1742   next_set:
1743     /* Reached the end, get the next base in the set. */
1744     while ((*sce_iter = (*sce_iter)->set)) {
1745       ViewLayer *view_layer_set = BKE_view_layer_default_render((*sce_iter));
1746       base = (Base *)view_layer_set->object_bases.first;
1747 
1748       if (base) {
1749         return base;
1750       }
1751     }
1752   }
1753 
1754   return NULL;
1755 }
1756 
BKE_scene_use_shading_nodes_custom(Scene * scene)1757 bool BKE_scene_use_shading_nodes_custom(Scene *scene)
1758 {
1759   RenderEngineType *type = RE_engines_find(scene->r.engine);
1760   return (type && type->flag & RE_USE_SHADING_NODES_CUSTOM);
1761 }
1762 
BKE_scene_use_spherical_stereo(Scene * scene)1763 bool BKE_scene_use_spherical_stereo(Scene *scene)
1764 {
1765   RenderEngineType *type = RE_engines_find(scene->r.engine);
1766   return (type && type->flag & RE_USE_SPHERICAL_STEREO);
1767 }
1768 
BKE_scene_uses_blender_eevee(const Scene * scene)1769 bool BKE_scene_uses_blender_eevee(const Scene *scene)
1770 {
1771   return STREQ(scene->r.engine, RE_engine_id_BLENDER_EEVEE);
1772 }
1773 
BKE_scene_uses_blender_workbench(const Scene * scene)1774 bool BKE_scene_uses_blender_workbench(const Scene *scene)
1775 {
1776   return STREQ(scene->r.engine, RE_engine_id_BLENDER_WORKBENCH);
1777 }
1778 
BKE_scene_uses_cycles(const Scene * scene)1779 bool BKE_scene_uses_cycles(const Scene *scene)
1780 {
1781   return STREQ(scene->r.engine, RE_engine_id_CYCLES);
1782 }
1783 
BKE_scene_base_flag_to_objects(ViewLayer * view_layer)1784 void BKE_scene_base_flag_to_objects(ViewLayer *view_layer)
1785 {
1786   Base *base = view_layer->object_bases.first;
1787 
1788   while (base) {
1789     BKE_scene_object_base_flag_sync_from_base(base);
1790     base = base->next;
1791   }
1792 }
1793 
1794 /**
1795  * Synchronize object base flags
1796  *
1797  * This is usually handled by the depsgraph.
1798  * However, in rare occasions we need to use the latest object flags
1799  * before depsgraph is fully updated.
1800  *
1801  * It should (ideally) only run for copy-on-written objects since this is
1802  * runtime data generated per-viewlayer.
1803  */
BKE_scene_object_base_flag_sync_from_base(Base * base)1804 void BKE_scene_object_base_flag_sync_from_base(Base *base)
1805 {
1806   Object *ob = base->object;
1807   ob->base_flag = base->flag;
1808 }
1809 
BKE_scene_disable_color_management(Scene * scene)1810 void BKE_scene_disable_color_management(Scene *scene)
1811 {
1812   ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1813   ColorManagedViewSettings *view_settings = &scene->view_settings;
1814   const char *view;
1815   const char *none_display_name;
1816 
1817   none_display_name = IMB_colormanagement_display_get_none_name();
1818 
1819   BLI_strncpy(display_settings->display_device,
1820               none_display_name,
1821               sizeof(display_settings->display_device));
1822 
1823   view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1824 
1825   if (view) {
1826     BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1827   }
1828 }
1829 
BKE_scene_check_color_management_enabled(const Scene * scene)1830 bool BKE_scene_check_color_management_enabled(const Scene *scene)
1831 {
1832   return !STREQ(scene->display_settings.display_device, "None");
1833 }
1834 
BKE_scene_check_rigidbody_active(const Scene * scene)1835 bool BKE_scene_check_rigidbody_active(const Scene *scene)
1836 {
1837   return scene && scene->rigidbody_world && scene->rigidbody_world->group &&
1838          !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1839 }
1840 
BKE_render_num_threads(const RenderData * rd)1841 int BKE_render_num_threads(const RenderData *rd)
1842 {
1843   int threads;
1844 
1845   /* override set from command line? */
1846   threads = BLI_system_num_threads_override_get();
1847 
1848   if (threads > 0) {
1849     return threads;
1850   }
1851 
1852   /* fixed number of threads specified in scene? */
1853   if (rd->mode & R_FIXED_THREADS) {
1854     threads = rd->threads;
1855   }
1856   else {
1857     threads = BLI_system_thread_count();
1858   }
1859 
1860   return max_ii(threads, 1);
1861 }
1862 
BKE_scene_num_threads(const Scene * scene)1863 int BKE_scene_num_threads(const Scene *scene)
1864 {
1865   return BKE_render_num_threads(&scene->r);
1866 }
1867 
BKE_render_preview_pixel_size(const RenderData * r)1868 int BKE_render_preview_pixel_size(const RenderData *r)
1869 {
1870   if (r->preview_pixel_size == 0) {
1871     return (U.pixelsize > 1.5f) ? 2 : 1;
1872   }
1873   return r->preview_pixel_size;
1874 }
1875 
1876 /**
1877  * Apply the needed correction factor to value, based on unit_type
1878  * (only length-related are affected currently) and unit->scale_length.
1879  */
BKE_scene_unit_scale(const UnitSettings * unit,const int unit_type,double value)1880 double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value)
1881 {
1882   if (unit->system == USER_UNIT_NONE) {
1883     /* Never apply scale_length when not using a unit setting! */
1884     return value;
1885   }
1886 
1887   switch (unit_type) {
1888     case B_UNIT_LENGTH:
1889     case B_UNIT_VELOCITY:
1890     case B_UNIT_ACCELERATION:
1891       return value * (double)unit->scale_length;
1892     case B_UNIT_AREA:
1893     case B_UNIT_POWER:
1894       return value * pow(unit->scale_length, 2);
1895     case B_UNIT_VOLUME:
1896       return value * pow(unit->scale_length, 3);
1897     case B_UNIT_MASS:
1898       return value * pow(unit->scale_length, 3);
1899     case B_UNIT_CAMERA: /* *Do not* use scene's unit scale for camera focal lens! See T42026. */
1900     default:
1901       return value;
1902   }
1903 }
1904 
1905 /******************** multiview *************************/
1906 
BKE_scene_multiview_num_views_get(const RenderData * rd)1907 int BKE_scene_multiview_num_views_get(const RenderData *rd)
1908 {
1909   SceneRenderView *srv;
1910   int totviews = 0;
1911 
1912   if ((rd->scemode & R_MULTIVIEW) == 0) {
1913     return 1;
1914   }
1915 
1916   if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
1917     srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1918     if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1919       totviews++;
1920     }
1921 
1922     srv = BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1923     if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1924       totviews++;
1925     }
1926   }
1927   else {
1928     for (srv = rd->views.first; srv; srv = srv->next) {
1929       if ((srv->viewflag & SCE_VIEW_DISABLE) == 0) {
1930         totviews++;
1931       }
1932     }
1933   }
1934   return totviews;
1935 }
1936 
BKE_scene_multiview_is_stereo3d(const RenderData * rd)1937 bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
1938 {
1939   SceneRenderView *srv[2];
1940 
1941   if ((rd->scemode & R_MULTIVIEW) == 0) {
1942     return false;
1943   }
1944 
1945   srv[0] = (SceneRenderView *)BLI_findstring(
1946       &rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
1947   srv[1] = (SceneRenderView *)BLI_findstring(
1948       &rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
1949 
1950   return (srv[0] && ((srv[0]->viewflag & SCE_VIEW_DISABLE) == 0) && srv[1] &&
1951           ((srv[1]->viewflag & SCE_VIEW_DISABLE) == 0));
1952 }
1953 
1954 /* return whether to render this SceneRenderView */
BKE_scene_multiview_is_render_view_active(const RenderData * rd,const SceneRenderView * srv)1955 bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
1956 {
1957   if (srv == NULL) {
1958     return false;
1959   }
1960 
1961   if ((rd->scemode & R_MULTIVIEW) == 0) {
1962     return false;
1963   }
1964 
1965   if ((srv->viewflag & SCE_VIEW_DISABLE)) {
1966     return false;
1967   }
1968 
1969   if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
1970     return true;
1971   }
1972 
1973   /* SCE_VIEWS_SETUP_BASIC */
1974   if (STREQ(srv->name, STEREO_LEFT_NAME) || STREQ(srv->name, STEREO_RIGHT_NAME)) {
1975     return true;
1976   }
1977 
1978   return false;
1979 }
1980 
1981 /* return true if viewname is the first or if the name is NULL or not found */
BKE_scene_multiview_is_render_view_first(const RenderData * rd,const char * viewname)1982 bool BKE_scene_multiview_is_render_view_first(const RenderData *rd, const char *viewname)
1983 {
1984   SceneRenderView *srv;
1985 
1986   if ((rd->scemode & R_MULTIVIEW) == 0) {
1987     return true;
1988   }
1989 
1990   if ((!viewname) || (!viewname[0])) {
1991     return true;
1992   }
1993 
1994   for (srv = rd->views.first; srv; srv = srv->next) {
1995     if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
1996       return STREQ(viewname, srv->name);
1997     }
1998   }
1999 
2000   return true;
2001 }
2002 
2003 /* return true if viewname is the last or if the name is NULL or not found */
BKE_scene_multiview_is_render_view_last(const RenderData * rd,const char * viewname)2004 bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *viewname)
2005 {
2006   SceneRenderView *srv;
2007 
2008   if ((rd->scemode & R_MULTIVIEW) == 0) {
2009     return true;
2010   }
2011 
2012   if ((!viewname) || (!viewname[0])) {
2013     return true;
2014   }
2015 
2016   for (srv = rd->views.last; srv; srv = srv->prev) {
2017     if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2018       return STREQ(viewname, srv->name);
2019     }
2020   }
2021 
2022   return true;
2023 }
2024 
BKE_scene_multiview_render_view_findindex(const RenderData * rd,const int view_id)2025 SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, const int view_id)
2026 {
2027   SceneRenderView *srv;
2028   size_t nr;
2029 
2030   if ((rd->scemode & R_MULTIVIEW) == 0) {
2031     return NULL;
2032   }
2033 
2034   for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2035     if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2036       if (nr++ == view_id) {
2037         return srv;
2038       }
2039     }
2040   }
2041   return srv;
2042 }
2043 
BKE_scene_multiview_render_view_name_get(const RenderData * rd,const int view_id)2044 const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const int view_id)
2045 {
2046   SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id);
2047 
2048   if (srv) {
2049     return srv->name;
2050   }
2051 
2052   return "";
2053 }
2054 
BKE_scene_multiview_view_id_get(const RenderData * rd,const char * viewname)2055 int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
2056 {
2057   SceneRenderView *srv;
2058   size_t nr;
2059 
2060   if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0)) {
2061     return 0;
2062   }
2063 
2064   if ((!viewname) || (!viewname[0])) {
2065     return 0;
2066   }
2067 
2068   for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2069     if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2070       if (STREQ(viewname, srv->name)) {
2071         return nr;
2072       }
2073 
2074       nr += 1;
2075     }
2076   }
2077 
2078   return 0;
2079 }
2080 
BKE_scene_multiview_filepath_get(SceneRenderView * srv,const char * filepath,char * r_filepath)2081 void BKE_scene_multiview_filepath_get(SceneRenderView *srv, const char *filepath, char *r_filepath)
2082 {
2083   BLI_strncpy(r_filepath, filepath, FILE_MAX);
2084   BLI_path_suffix(r_filepath, FILE_MAX, srv->suffix, "");
2085 }
2086 
2087 /**
2088  * When multiview is not used the filepath is as usual (e.g., ``Image.jpg``).
2089  * When multiview is on, even if only one view is enabled the view is incorporated
2090  * into the file name (e.g., ``Image_L.jpg``). That allows for the user to re-render
2091  * individual views.
2092  */
BKE_scene_multiview_view_filepath_get(const RenderData * rd,const char * filepath,const char * viewname,char * r_filepath)2093 void BKE_scene_multiview_view_filepath_get(const RenderData *rd,
2094                                            const char *filepath,
2095                                            const char *viewname,
2096                                            char *r_filepath)
2097 {
2098   SceneRenderView *srv;
2099   char suffix[FILE_MAX];
2100 
2101   srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2102   if (srv) {
2103     BLI_strncpy(suffix, srv->suffix, sizeof(suffix));
2104   }
2105   else {
2106     BLI_strncpy(suffix, viewname, sizeof(suffix));
2107   }
2108 
2109   BLI_strncpy(r_filepath, filepath, FILE_MAX);
2110   BLI_path_suffix(r_filepath, FILE_MAX, suffix, "");
2111 }
2112 
BKE_scene_multiview_view_suffix_get(const RenderData * rd,const char * viewname)2113 const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char *viewname)
2114 {
2115   SceneRenderView *srv;
2116 
2117   if ((viewname == NULL) || (viewname[0] == '\0')) {
2118     return viewname;
2119   }
2120 
2121   srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2122   if (srv) {
2123     return srv->suffix;
2124   }
2125 
2126   return viewname;
2127 }
2128 
BKE_scene_multiview_view_id_suffix_get(const RenderData * rd,const int view_id)2129 const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id)
2130 {
2131   if ((rd->scemode & R_MULTIVIEW) == 0) {
2132     return "";
2133   }
2134 
2135   const char *viewname = BKE_scene_multiview_render_view_name_get(rd, view_id);
2136   return BKE_scene_multiview_view_suffix_get(rd, viewname);
2137 }
2138 
BKE_scene_multiview_view_prefix_get(Scene * scene,const char * name,char * r_prefix,const char ** r_ext)2139 void BKE_scene_multiview_view_prefix_get(Scene *scene,
2140                                          const char *name,
2141                                          char *r_prefix,
2142                                          const char **r_ext)
2143 {
2144   SceneRenderView *srv;
2145   size_t index_act;
2146   const char *suf_act;
2147   const char delims[] = {'.', '\0'};
2148 
2149   r_prefix[0] = '\0';
2150 
2151   /* begin of extension */
2152   index_act = BLI_str_rpartition(name, delims, r_ext, &suf_act);
2153   if (*r_ext == NULL) {
2154     return;
2155   }
2156   BLI_assert(index_act > 0);
2157   UNUSED_VARS_NDEBUG(index_act);
2158 
2159   for (srv = scene->r.views.first; srv; srv = srv->next) {
2160     if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
2161       const size_t len = strlen(srv->suffix);
2162       const size_t ext_len = strlen(*r_ext);
2163       if (ext_len >= len && STREQLEN(*r_ext - len, srv->suffix, len)) {
2164         BLI_strncpy(r_prefix, name, strlen(name) - ext_len - len + 1);
2165         break;
2166       }
2167     }
2168   }
2169 }
2170 
BKE_scene_multiview_videos_dimensions_get(const RenderData * rd,const size_t width,const size_t height,size_t * r_width,size_t * r_height)2171 void BKE_scene_multiview_videos_dimensions_get(const RenderData *rd,
2172                                                const size_t width,
2173                                                const size_t height,
2174                                                size_t *r_width,
2175                                                size_t *r_height)
2176 {
2177   if ((rd->scemode & R_MULTIVIEW) && rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2178     IMB_stereo3d_write_dimensions(rd->im_format.stereo3d_format.display_mode,
2179                                   (rd->im_format.stereo3d_format.flag & S3D_SQUEEZED_FRAME) != 0,
2180                                   width,
2181                                   height,
2182                                   r_width,
2183                                   r_height);
2184   }
2185   else {
2186     *r_width = width;
2187     *r_height = height;
2188   }
2189 }
2190 
BKE_scene_multiview_num_videos_get(const RenderData * rd)2191 int BKE_scene_multiview_num_videos_get(const RenderData *rd)
2192 {
2193   if (BKE_imtype_is_movie(rd->im_format.imtype) == false) {
2194     return 0;
2195   }
2196 
2197   if ((rd->scemode & R_MULTIVIEW) == 0) {
2198     return 1;
2199   }
2200 
2201   if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2202     return 1;
2203   }
2204 
2205   /* R_IMF_VIEWS_INDIVIDUAL */
2206   return BKE_scene_multiview_num_views_get(rd);
2207 }
2208 
2209 /* Manipulation of depsgraph storage. */
2210 
2211 /* This is a key which identifies depsgraph. */
2212 typedef struct DepsgraphKey {
2213   ViewLayer *view_layer;
2214   /* TODO(sergey): Need to include window somehow (same layer might be in a
2215    * different states in different windows).
2216    */
2217 } DepsgraphKey;
2218 
depsgraph_key_hash(const void * key_v)2219 static unsigned int depsgraph_key_hash(const void *key_v)
2220 {
2221   const DepsgraphKey *key = key_v;
2222   unsigned int hash = BLI_ghashutil_ptrhash(key->view_layer);
2223   /* TODO(sergey): Include hash from other fields in the key. */
2224   return hash;
2225 }
2226 
depsgraph_key_compare(const void * key_a_v,const void * key_b_v)2227 static bool depsgraph_key_compare(const void *key_a_v, const void *key_b_v)
2228 {
2229   const DepsgraphKey *key_a = key_a_v;
2230   const DepsgraphKey *key_b = key_b_v;
2231   /* TODO(sergey): Compare rest of  */
2232   return !(key_a->view_layer == key_b->view_layer);
2233 }
2234 
depsgraph_key_free(void * key_v)2235 static void depsgraph_key_free(void *key_v)
2236 {
2237   DepsgraphKey *key = key_v;
2238   MEM_freeN(key);
2239 }
2240 
depsgraph_key_value_free(void * value)2241 static void depsgraph_key_value_free(void *value)
2242 {
2243   Depsgraph *depsgraph = value;
2244   DEG_graph_free(depsgraph);
2245 }
2246 
BKE_scene_allocate_depsgraph_hash(Scene * scene)2247 void BKE_scene_allocate_depsgraph_hash(Scene *scene)
2248 {
2249   scene->depsgraph_hash = BLI_ghash_new(
2250       depsgraph_key_hash, depsgraph_key_compare, "Scene Depsgraph Hash");
2251 }
2252 
BKE_scene_ensure_depsgraph_hash(Scene * scene)2253 void BKE_scene_ensure_depsgraph_hash(Scene *scene)
2254 {
2255   if (scene->depsgraph_hash == NULL) {
2256     BKE_scene_allocate_depsgraph_hash(scene);
2257   }
2258 }
2259 
BKE_scene_free_depsgraph_hash(Scene * scene)2260 void BKE_scene_free_depsgraph_hash(Scene *scene)
2261 {
2262   if (scene->depsgraph_hash == NULL) {
2263     return;
2264   }
2265   BLI_ghash_free(scene->depsgraph_hash, depsgraph_key_free, depsgraph_key_value_free);
2266   scene->depsgraph_hash = NULL;
2267 }
2268 
BKE_scene_free_view_layer_depsgraph(Scene * scene,ViewLayer * view_layer)2269 void BKE_scene_free_view_layer_depsgraph(Scene *scene, ViewLayer *view_layer)
2270 {
2271   if (scene->depsgraph_hash != NULL) {
2272     DepsgraphKey key = {view_layer};
2273     BLI_ghash_remove(scene->depsgraph_hash, &key, depsgraph_key_free, depsgraph_key_value_free);
2274   }
2275 }
2276 
2277 /* Query depsgraph for a specific contexts. */
2278 
scene_get_depsgraph_p(Scene * scene,ViewLayer * view_layer,const bool allocate_ghash_entry)2279 static Depsgraph **scene_get_depsgraph_p(Scene *scene,
2280                                          ViewLayer *view_layer,
2281                                          const bool allocate_ghash_entry)
2282 {
2283   /* bmain may be NULL here! */
2284   BLI_assert(scene != NULL);
2285   BLI_assert(view_layer != NULL);
2286   BLI_assert(BKE_scene_has_view_layer(scene, view_layer));
2287 
2288   /* Make sure hash itself exists. */
2289   if (allocate_ghash_entry) {
2290     BKE_scene_ensure_depsgraph_hash(scene);
2291   }
2292   if (scene->depsgraph_hash == NULL) {
2293     return NULL;
2294   }
2295 
2296   DepsgraphKey key;
2297   key.view_layer = view_layer;
2298 
2299   Depsgraph **depsgraph_ptr;
2300   if (!allocate_ghash_entry) {
2301     depsgraph_ptr = (Depsgraph **)BLI_ghash_lookup_p(scene->depsgraph_hash, &key);
2302     return depsgraph_ptr;
2303   }
2304 
2305   DepsgraphKey **key_ptr;
2306   if (BLI_ghash_ensure_p_ex(
2307           scene->depsgraph_hash, &key, (void ***)&key_ptr, (void ***)&depsgraph_ptr)) {
2308     return depsgraph_ptr;
2309   }
2310 
2311   /* Depsgraph was not found in the ghash, but the key still needs allocating. */
2312   *key_ptr = MEM_mallocN(sizeof(DepsgraphKey), __func__);
2313   **key_ptr = key;
2314 
2315   *depsgraph_ptr = NULL;
2316   return depsgraph_ptr;
2317 }
2318 
scene_ensure_depsgraph_p(Main * bmain,Scene * scene,ViewLayer * view_layer)2319 static Depsgraph **scene_ensure_depsgraph_p(Main *bmain, Scene *scene, ViewLayer *view_layer)
2320 {
2321   BLI_assert(bmain != NULL);
2322 
2323   Depsgraph **depsgraph_ptr = scene_get_depsgraph_p(scene, view_layer, true);
2324   if (depsgraph_ptr == NULL) {
2325     /* The scene has no depsgraph hash. */
2326     return NULL;
2327   }
2328   if (*depsgraph_ptr != NULL) {
2329     /* The depsgraph was found, no need to allocate. */
2330     return depsgraph_ptr;
2331   }
2332 
2333   /* Allocate a new depsgraph. scene_get_depsgraph_p() already ensured that the pointer is stored
2334    * in the scene's depsgraph hash. */
2335   *depsgraph_ptr = DEG_graph_new(bmain, scene, view_layer, DAG_EVAL_VIEWPORT);
2336 
2337   /* TODO(sergey): Would be cool to avoid string format print,
2338    * but is a bit tricky because we can't know in advance whether
2339    * we will ever enable debug messages for this depsgraph.
2340    */
2341   char name[1024];
2342   BLI_snprintf(name, sizeof(name), "%s :: %s", scene->id.name, view_layer->name);
2343   DEG_debug_name_set(*depsgraph_ptr, name);
2344 
2345   return depsgraph_ptr;
2346 }
2347 
BKE_scene_get_depsgraph(Scene * scene,ViewLayer * view_layer)2348 Depsgraph *BKE_scene_get_depsgraph(Scene *scene, ViewLayer *view_layer)
2349 {
2350   Depsgraph **depsgraph_ptr = scene_get_depsgraph_p(scene, view_layer, false);
2351   return (depsgraph_ptr != NULL) ? *depsgraph_ptr : NULL;
2352 }
2353 
BKE_scene_ensure_depsgraph(Main * bmain,Scene * scene,ViewLayer * view_layer)2354 Depsgraph *BKE_scene_ensure_depsgraph(Main *bmain, Scene *scene, ViewLayer *view_layer)
2355 {
2356   Depsgraph **depsgraph_ptr = scene_ensure_depsgraph_p(bmain, scene, view_layer);
2357   return (depsgraph_ptr != NULL) ? *depsgraph_ptr : NULL;
2358 }
2359 
scene_undo_depsgraph_gen_key(Scene * scene,ViewLayer * view_layer,char * key_full)2360 static char *scene_undo_depsgraph_gen_key(Scene *scene, ViewLayer *view_layer, char *key_full)
2361 {
2362   if (key_full == NULL) {
2363     key_full = MEM_callocN(MAX_ID_NAME + FILE_MAX + MAX_NAME, __func__);
2364   }
2365 
2366   size_t key_full_offset = BLI_strncpy_rlen(key_full, scene->id.name, MAX_ID_NAME);
2367   if (scene->id.lib != NULL) {
2368     key_full_offset += BLI_strncpy_rlen(
2369         key_full + key_full_offset, scene->id.lib->filepath, FILE_MAX);
2370   }
2371   key_full_offset += BLI_strncpy_rlen(key_full + key_full_offset, view_layer->name, MAX_NAME);
2372   BLI_assert(key_full_offset < MAX_ID_NAME + FILE_MAX + MAX_NAME);
2373 
2374   return key_full;
2375 }
2376 
BKE_scene_undo_depsgraphs_extract(Main * bmain)2377 GHash *BKE_scene_undo_depsgraphs_extract(Main *bmain)
2378 {
2379   GHash *depsgraph_extract = BLI_ghash_new(
2380       BLI_ghashutil_strhash_p, BLI_ghashutil_strcmp, __func__);
2381 
2382   for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) {
2383     if (scene->depsgraph_hash == NULL) {
2384       /* In some cases, e.g. when undo has to perform multiple steps at once, no depsgraph will be
2385        * built so this pointer may be NULL. */
2386       continue;
2387     }
2388     for (ViewLayer *view_layer = scene->view_layers.first; view_layer != NULL;
2389          view_layer = view_layer->next) {
2390       DepsgraphKey key;
2391       key.view_layer = view_layer;
2392       Depsgraph **depsgraph = (Depsgraph **)BLI_ghash_lookup_p(scene->depsgraph_hash, &key);
2393 
2394       if (depsgraph != NULL && *depsgraph != NULL) {
2395         char *key_full = scene_undo_depsgraph_gen_key(scene, view_layer, NULL);
2396 
2397         /* We steal the depsgraph from the scene. */
2398         BLI_ghash_insert(depsgraph_extract, key_full, *depsgraph);
2399         *depsgraph = NULL;
2400       }
2401     }
2402   }
2403 
2404   return depsgraph_extract;
2405 }
2406 
BKE_scene_undo_depsgraphs_restore(Main * bmain,GHash * depsgraph_extract)2407 void BKE_scene_undo_depsgraphs_restore(Main *bmain, GHash *depsgraph_extract)
2408 {
2409   for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) {
2410     for (ViewLayer *view_layer = scene->view_layers.first; view_layer != NULL;
2411          view_layer = view_layer->next) {
2412       char key_full[MAX_ID_NAME + FILE_MAX + MAX_NAME] = {0};
2413       scene_undo_depsgraph_gen_key(scene, view_layer, key_full);
2414 
2415       Depsgraph **depsgraph_extract_ptr = (Depsgraph **)BLI_ghash_lookup_p(depsgraph_extract,
2416                                                                            key_full);
2417       if (depsgraph_extract_ptr == NULL) {
2418         continue;
2419       }
2420       BLI_assert(*depsgraph_extract_ptr != NULL);
2421 
2422       Depsgraph **depsgraph_scene_ptr = scene_get_depsgraph_p(scene, view_layer, true);
2423       BLI_assert(depsgraph_scene_ptr != NULL);
2424       BLI_assert(*depsgraph_scene_ptr == NULL);
2425 
2426       /* We steal the depsgraph back from our 'extract' storage to the scene. */
2427       Depsgraph *depsgraph = *depsgraph_extract_ptr;
2428 
2429       DEG_graph_replace_owners(depsgraph, bmain, scene, view_layer);
2430 
2431       DEG_graph_tag_relations_update(depsgraph);
2432 
2433       *depsgraph_scene_ptr = depsgraph;
2434       *depsgraph_extract_ptr = NULL;
2435     }
2436   }
2437 
2438   BLI_ghash_free(depsgraph_extract, MEM_freeN, depsgraph_key_value_free);
2439 }
2440 
2441 /* -------------------------------------------------------------------- */
2442 /** \name Scene Orientation
2443  * \{ */
2444 
BKE_scene_transform_orientation_remove(Scene * scene,TransformOrientation * orientation)2445 void BKE_scene_transform_orientation_remove(Scene *scene, TransformOrientation *orientation)
2446 {
2447   const int orientation_index = BKE_scene_transform_orientation_get_index(scene, orientation);
2448 
2449   for (int i = 0; i < ARRAY_SIZE(scene->orientation_slots); i++) {
2450     TransformOrientationSlot *orient_slot = &scene->orientation_slots[i];
2451     if (orient_slot->index_custom == orientation_index) {
2452       /* could also use orientation_index-- */
2453       orient_slot->type = V3D_ORIENT_GLOBAL;
2454       orient_slot->index_custom = -1;
2455     }
2456     else if (orient_slot->index_custom > orientation_index) {
2457       BLI_assert(orient_slot->type == V3D_ORIENT_CUSTOM);
2458       orient_slot->index_custom--;
2459     }
2460   }
2461 
2462   BLI_freelinkN(&scene->transform_spaces, orientation);
2463 }
2464 
BKE_scene_transform_orientation_find(const Scene * scene,const int index)2465 TransformOrientation *BKE_scene_transform_orientation_find(const Scene *scene, const int index)
2466 {
2467   return BLI_findlink(&scene->transform_spaces, index);
2468 }
2469 
2470 /**
2471  * \return the index that \a orientation has within \a scene's transform-orientation list
2472  * or -1 if not found.
2473  */
BKE_scene_transform_orientation_get_index(const Scene * scene,const TransformOrientation * orientation)2474 int BKE_scene_transform_orientation_get_index(const Scene *scene,
2475                                               const TransformOrientation *orientation)
2476 {
2477   return BLI_findindex(&scene->transform_spaces, orientation);
2478 }
2479 
2480 /** \} */
2481 
2482 /* -------------------------------------------------------------------- */
2483 /** \name Scene Cursor Rotation
2484  *
2485  * Matches #BKE_object_rot_to_mat3 and #BKE_object_mat3_to_rot.
2486  * \{ */
2487 
BKE_scene_cursor_rot_to_mat3(const View3DCursor * cursor,float mat[3][3])2488 void BKE_scene_cursor_rot_to_mat3(const View3DCursor *cursor, float mat[3][3])
2489 {
2490   if (cursor->rotation_mode > 0) {
2491     eulO_to_mat3(mat, cursor->rotation_euler, cursor->rotation_mode);
2492   }
2493   else if (cursor->rotation_mode == ROT_MODE_AXISANGLE) {
2494     axis_angle_to_mat3(mat, cursor->rotation_axis, cursor->rotation_angle);
2495   }
2496   else {
2497     float tquat[4];
2498     normalize_qt_qt(tquat, cursor->rotation_quaternion);
2499     quat_to_mat3(mat, tquat);
2500   }
2501 }
2502 
BKE_scene_cursor_rot_to_quat(const View3DCursor * cursor,float quat[4])2503 void BKE_scene_cursor_rot_to_quat(const View3DCursor *cursor, float quat[4])
2504 {
2505   if (cursor->rotation_mode > 0) {
2506     eulO_to_quat(quat, cursor->rotation_euler, cursor->rotation_mode);
2507   }
2508   else if (cursor->rotation_mode == ROT_MODE_AXISANGLE) {
2509     axis_angle_to_quat(quat, cursor->rotation_axis, cursor->rotation_angle);
2510   }
2511   else {
2512     normalize_qt_qt(quat, cursor->rotation_quaternion);
2513   }
2514 }
2515 
BKE_scene_cursor_mat3_to_rot(View3DCursor * cursor,const float mat[3][3],bool use_compat)2516 void BKE_scene_cursor_mat3_to_rot(View3DCursor *cursor, const float mat[3][3], bool use_compat)
2517 {
2518   BLI_ASSERT_UNIT_M3(mat);
2519 
2520   switch (cursor->rotation_mode) {
2521     case ROT_MODE_QUAT: {
2522       float quat[4];
2523       mat3_normalized_to_quat(quat, mat);
2524       if (use_compat) {
2525         float quat_orig[4];
2526         copy_v4_v4(quat_orig, cursor->rotation_quaternion);
2527         quat_to_compatible_quat(cursor->rotation_quaternion, quat, quat_orig);
2528       }
2529       else {
2530         copy_v4_v4(cursor->rotation_quaternion, quat);
2531       }
2532       break;
2533     }
2534     case ROT_MODE_AXISANGLE: {
2535       mat3_to_axis_angle(cursor->rotation_axis, &cursor->rotation_angle, mat);
2536       break;
2537     }
2538     default: {
2539       if (use_compat) {
2540         mat3_to_compatible_eulO(
2541             cursor->rotation_euler, cursor->rotation_euler, cursor->rotation_mode, mat);
2542       }
2543       else {
2544         mat3_to_eulO(cursor->rotation_euler, cursor->rotation_mode, mat);
2545       }
2546       break;
2547     }
2548   }
2549 }
2550 
BKE_scene_cursor_quat_to_rot(View3DCursor * cursor,const float quat[4],bool use_compat)2551 void BKE_scene_cursor_quat_to_rot(View3DCursor *cursor, const float quat[4], bool use_compat)
2552 {
2553   BLI_ASSERT_UNIT_QUAT(quat);
2554 
2555   switch (cursor->rotation_mode) {
2556     case ROT_MODE_QUAT: {
2557       if (use_compat) {
2558         float quat_orig[4];
2559         copy_v4_v4(quat_orig, cursor->rotation_quaternion);
2560         quat_to_compatible_quat(cursor->rotation_quaternion, quat, quat_orig);
2561       }
2562       else {
2563         copy_qt_qt(cursor->rotation_quaternion, quat);
2564       }
2565       break;
2566     }
2567     case ROT_MODE_AXISANGLE: {
2568       quat_to_axis_angle(cursor->rotation_axis, &cursor->rotation_angle, quat);
2569       break;
2570     }
2571     default: {
2572       if (use_compat) {
2573         quat_to_compatible_eulO(
2574             cursor->rotation_euler, cursor->rotation_euler, cursor->rotation_mode, quat);
2575       }
2576       else {
2577         quat_to_eulO(cursor->rotation_euler, cursor->rotation_mode, quat);
2578       }
2579       break;
2580     }
2581   }
2582 }
2583 
BKE_scene_cursor_to_mat4(const View3DCursor * cursor,float mat[4][4])2584 void BKE_scene_cursor_to_mat4(const View3DCursor *cursor, float mat[4][4])
2585 {
2586   float mat3[3][3];
2587   BKE_scene_cursor_rot_to_mat3(cursor, mat3);
2588   copy_m4_m3(mat, mat3);
2589   copy_v3_v3(mat[3], cursor->location);
2590 }
2591 
BKE_scene_cursor_from_mat4(View3DCursor * cursor,const float mat[4][4],bool use_compat)2592 void BKE_scene_cursor_from_mat4(View3DCursor *cursor, const float mat[4][4], bool use_compat)
2593 {
2594   float mat3[3][3];
2595   copy_m3_m4(mat3, mat);
2596   BKE_scene_cursor_mat3_to_rot(cursor, mat3, use_compat);
2597   copy_v3_v3(cursor->location, mat[3]);
2598 }
2599 
2600 /** \} */
2601 
2602 /* Dependency graph evaluation. */
2603 
scene_sequencer_disable_sound_strips(Scene * scene)2604 static void scene_sequencer_disable_sound_strips(Scene *scene)
2605 {
2606   if (scene->sound_scene == NULL) {
2607     return;
2608   }
2609   Sequence *seq;
2610   SEQ_ALL_BEGIN (scene->ed, seq) {
2611     if (seq->scene_sound != NULL) {
2612       BKE_sound_remove_scene_sound(scene, seq->scene_sound);
2613       seq->scene_sound = NULL;
2614     }
2615   }
2616   SEQ_ALL_END;
2617 }
2618 
BKE_scene_eval_sequencer_sequences(Depsgraph * depsgraph,Scene * scene)2619 void BKE_scene_eval_sequencer_sequences(Depsgraph *depsgraph, Scene *scene)
2620 {
2621   DEG_debug_print_eval(depsgraph, __func__, scene->id.name, scene);
2622   if (scene->ed == NULL) {
2623     return;
2624   }
2625   BKE_sound_ensure_scene(scene);
2626   Sequence *seq;
2627   SEQ_ALL_BEGIN (scene->ed, seq) {
2628     if (seq->scene_sound == NULL) {
2629       if (seq->sound != NULL) {
2630         if (seq->scene_sound == NULL) {
2631           seq->scene_sound = BKE_sound_add_scene_sound_defaults(scene, seq);
2632         }
2633       }
2634       else if (seq->type == SEQ_TYPE_SCENE) {
2635         if (seq->scene != NULL) {
2636           BKE_sound_ensure_scene(seq->scene);
2637           seq->scene_sound = BKE_sound_scene_add_scene_sound_defaults(scene, seq);
2638         }
2639       }
2640     }
2641     if (seq->scene_sound != NULL) {
2642       /* Make sure changing volume via sequence's properties panel works correct.
2643        *
2644        * Ideally, the entire BKE_scene_update_sound() will happen from a dependency graph, so
2645        * then it is no longer needed to do such manual forced updates. */
2646       if (seq->type == SEQ_TYPE_SCENE && seq->scene != NULL) {
2647         BKE_sound_set_scene_volume(seq->scene, seq->scene->audio.volume);
2648         if ((seq->flag & SEQ_SCENE_STRIPS) == 0) {
2649           scene_sequencer_disable_sound_strips(seq->scene);
2650         }
2651       }
2652       if (seq->sound != NULL) {
2653         if (scene->id.recalc & ID_RECALC_AUDIO || seq->sound->id.recalc & ID_RECALC_AUDIO) {
2654           BKE_sound_update_scene_sound(seq->scene_sound, seq->sound);
2655         }
2656       }
2657       BKE_sound_set_scene_sound_volume(
2658           seq->scene_sound, seq->volume, (seq->flag & SEQ_AUDIO_VOLUME_ANIMATED) != 0);
2659       BKE_sound_set_scene_sound_pitch(
2660           seq->scene_sound, seq->pitch, (seq->flag & SEQ_AUDIO_PITCH_ANIMATED) != 0);
2661       BKE_sound_set_scene_sound_pan(
2662           seq->scene_sound, seq->pan, (seq->flag & SEQ_AUDIO_PAN_ANIMATED) != 0);
2663     }
2664   }
2665   SEQ_ALL_END;
2666   BKE_sequencer_update_muting(scene->ed);
2667   BKE_sequencer_update_sound_bounds_all(scene);
2668 }
2669