Depsgraph: Fix crash using --debug-depsgraph and --debug-depsgraph-no-threads
[blender.git] / source / blender / blenkernel / intern / scene.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/scene.c
29  *  \ingroup bke
30  */
31
32
33 #include <stddef.h>
34 #include <stdio.h>
35 #include <string.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_linestyle_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_node_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_rigidbody_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_sequence_types.h"
49 #include "DNA_space_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_windowmanager_types.h"
52 #include "DNA_gpencil_types.h"
53
54 #include "BLI_math.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_utildefines.h"
57 #include "BLI_callbacks.h"
58 #include "BLI_string.h"
59 #include "BLI_string_utils.h"
60 #include "BLI_threads.h"
61 #include "BLI_task.h"
62
63 #include "BLT_translation.h"
64
65 #include "BKE_anim.h"
66 #include "BKE_animsys.h"
67 #include "BKE_action.h"
68 #include "BKE_armature.h"
69 #include "BKE_cachefile.h"
70 #include "BKE_colortools.h"
71 #include "BKE_depsgraph.h"
72 #include "BKE_editmesh.h"
73 #include "BKE_fcurve.h"
74 #include "BKE_freestyle.h"
75 #include "BKE_global.h"
76 #include "BKE_gpencil.h"
77 #include "BKE_group.h"
78 #include "BKE_icons.h"
79 #include "BKE_idprop.h"
80 #include "BKE_image.h"
81 #include "BKE_library.h"
82 #include "BKE_library_remap.h"
83 #include "BKE_linestyle.h"
84 #include "BKE_main.h"
85 #include "BKE_mask.h"
86 #include "BKE_node.h"
87 #include "BKE_object.h"
88 #include "BKE_paint.h"
89 #include "BKE_rigidbody.h"
90 #include "BKE_scene.h"
91 #include "BKE_screen.h"
92 #include "BKE_sequencer.h"
93 #include "BKE_sound.h"
94 #include "BKE_unit.h"
95 #include "BKE_world.h"
96
97 #include "DEG_depsgraph.h"
98
99 #include "RE_engine.h"
100
101 #include "PIL_time.h"
102
103 #include "IMB_colormanagement.h"
104 #include "IMB_imbuf.h"
105
106 #include "bmesh.h"
107
108 const char *RE_engine_id_BLENDER_RENDER = "BLENDER_RENDER";
109 const char *RE_engine_id_BLENDER_GAME = "BLENDER_GAME";
110 const char *RE_engine_id_CYCLES = "CYCLES";
111
112 void free_avicodecdata(AviCodecData *acd)
113 {
114         if (acd) {
115                 if (acd->lpFormat) {
116                         MEM_freeN(acd->lpFormat);
117                         acd->lpFormat = NULL;
118                         acd->cbFormat = 0;
119                 }
120                 if (acd->lpParms) {
121                         MEM_freeN(acd->lpParms);
122                         acd->lpParms = NULL;
123                         acd->cbParms = 0;
124                 }
125         }
126 }
127
128 static void remove_sequencer_fcurves(Scene *sce)
129 {
130         AnimData *adt = BKE_animdata_from_id(&sce->id);
131
132         if (adt && adt->action) {
133                 FCurve *fcu, *nextfcu;
134                 
135                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
136                         nextfcu = fcu->next;
137                         
138                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
139                                 action_groups_remove_channel(adt->action, fcu);
140                                 free_fcurve(fcu);
141                         }
142                 }
143         }
144 }
145
146 /**
147  * Only copy internal data of Scene ID from source to already allocated/initialized destination.
148  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
149  *
150  * WARNING! This function will not handle ID user count!
151  *
152  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
153  */
154 void BKE_scene_copy_data(Main *bmain, Scene *sce_dst, const Scene *sce_src, const int flag)
155 {
156         /* We never handle usercount here for own data. */
157         const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
158
159         sce_dst->ed = NULL;
160         sce_dst->theDag = NULL;
161         sce_dst->depsgraph = NULL;
162         sce_dst->obedit = NULL;
163         sce_dst->stats = NULL;
164         sce_dst->fps_info = NULL;
165
166         BLI_duplicatelist(&(sce_dst->base), &(sce_src->base));
167         for (Base *base_dst = sce_dst->base.first, *base_src = sce_src->base.first;
168              base_dst;
169              base_dst = base_dst->next, base_src = base_src->next)
170         {
171                 if (base_src == sce_src->basact) {
172                         sce_dst->basact = base_dst;
173                 }
174         }
175
176         BLI_duplicatelist(&(sce_dst->markers), &(sce_src->markers));
177         BLI_duplicatelist(&(sce_dst->transform_spaces), &(sce_src->transform_spaces));
178         BLI_duplicatelist(&(sce_dst->r.layers), &(sce_src->r.layers));
179         BLI_duplicatelist(&(sce_dst->r.views), &(sce_src->r.views));
180         BKE_keyingsets_copy(&(sce_dst->keyingsets), &(sce_src->keyingsets));
181
182         if (sce_src->nodetree) {
183                 /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
184                  *       (see BKE_libblock_copy_ex()). */
185                 BKE_id_copy_ex(bmain, (ID *)sce_src->nodetree, (ID **)&sce_dst->nodetree, flag, false);
186                 BKE_libblock_relink_ex(bmain, sce_dst->nodetree, (void *)(&sce_src->id), &sce_dst->id, false);
187         }
188
189         if (sce_src->rigidbody_world) {
190                 sce_dst->rigidbody_world = BKE_rigidbody_world_copy(sce_src->rigidbody_world, flag_subdata);
191         }
192
193         /* copy Freestyle settings */
194         for (SceneRenderLayer *srl_dst = sce_dst->r.layers.first, *srl_src = sce_src->r.layers.first;
195              srl_src;
196              srl_dst = srl_dst->next, srl_src = srl_src->next)
197         {
198                 if (srl_dst->prop != NULL) {
199                         srl_dst->prop = IDP_CopyProperty_ex(srl_dst->prop, flag_subdata);
200                 }
201                 BKE_freestyle_config_copy(&srl_dst->freestyleConfig, &srl_src->freestyleConfig, flag_subdata);
202         }
203
204         /* copy color management settings */
205         BKE_color_managed_display_settings_copy(&sce_dst->display_settings, &sce_src->display_settings);
206         BKE_color_managed_view_settings_copy(&sce_dst->view_settings, &sce_src->view_settings);
207         BKE_color_managed_colorspace_settings_copy(&sce_dst->sequencer_colorspace_settings, &sce_src->sequencer_colorspace_settings);
208
209         BKE_color_managed_display_settings_copy(&sce_dst->r.im_format.display_settings, &sce_src->r.im_format.display_settings);
210         BKE_color_managed_view_settings_copy(&sce_dst->r.im_format.view_settings, &sce_src->r.im_format.view_settings);
211
212         BKE_color_managed_display_settings_copy(&sce_dst->r.bake.im_format.display_settings, &sce_src->r.bake.im_format.display_settings);
213         BKE_color_managed_view_settings_copy(&sce_dst->r.bake.im_format.view_settings, &sce_src->r.bake.im_format.view_settings);
214
215         curvemapping_copy_data(&sce_dst->r.mblur_shutter_curve, &sce_src->r.mblur_shutter_curve);
216
217         /* tool settings */
218         if (sce_dst->toolsettings != NULL) {
219                 ToolSettings *ts = sce_dst->toolsettings = MEM_dupallocN(sce_dst->toolsettings);
220                 if (ts->vpaint) {
221                         ts->vpaint = MEM_dupallocN(ts->vpaint);
222                         BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, flag_subdata);
223                 }
224                 if (ts->wpaint) {
225                         ts->wpaint = MEM_dupallocN(ts->wpaint);
226                         BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, flag_subdata);
227                 }
228                 if (ts->sculpt) {
229                         ts->sculpt = MEM_dupallocN(ts->sculpt);
230                         BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, flag_subdata);
231                 }
232                 if (ts->uvsculpt) {
233                         ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
234                         BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, flag_subdata);
235                 }
236
237                 BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, flag_subdata);
238                 ts->imapaint.paintcursor = NULL;
239                 ts->particle.paintcursor = NULL;
240                 ts->particle.scene = NULL;
241                 ts->particle.object = NULL;
242
243                 /* duplicate Grease Pencil Drawing Brushes */
244                 BLI_listbase_clear(&ts->gp_brushes);
245                 for (bGPDbrush *brush = sce_src->toolsettings->gp_brushes.first; brush; brush = brush->next) {
246                         bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
247                         BLI_addtail(&ts->gp_brushes, newbrush);
248                 }
249
250                 /* duplicate Grease Pencil interpolation curve */
251                 ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
252         }
253
254         /* make a private copy of the avicodecdata */
255         if (sce_src->r.avicodecdata) {
256                 sce_dst->r.avicodecdata = MEM_dupallocN(sce_src->r.avicodecdata);
257                 sce_dst->r.avicodecdata->lpFormat = MEM_dupallocN(sce_dst->r.avicodecdata->lpFormat);
258                 sce_dst->r.avicodecdata->lpParms = MEM_dupallocN(sce_dst->r.avicodecdata->lpParms);
259         }
260
261         if (sce_src->r.ffcodecdata.properties) { /* intentionally check sce_dst not sce_src. */  /* XXX ??? comment outdated... */
262                 sce_dst->r.ffcodecdata.properties = IDP_CopyProperty_ex(sce_src->r.ffcodecdata.properties, flag_subdata);
263         }
264
265         /* before scene copy */
266         BKE_sound_create_scene(sce_dst);
267
268         /* Copy sequencer, this is local data! */
269         if (sce_src->ed) {
270                 sce_dst->ed = MEM_callocN(sizeof(*sce_dst->ed), __func__);
271                 sce_dst->ed->seqbasep = &sce_dst->ed->seqbase;
272                 BKE_sequence_base_dupli_recursive(
273                             sce_src, sce_dst, &sce_dst->ed->seqbase, &sce_src->ed->seqbase, SEQ_DUPE_ALL, flag_subdata);
274         }
275
276         if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
277                 BKE_previewimg_id_copy(&sce_dst->id, &sce_src->id);
278         }
279         else {
280                 sce_dst->preview = NULL;
281         }
282 }
283
284 Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type)
285 {
286         Scene *sce_copy;
287
288         /* TODO this should/could most likely be replaced by call to more generic code at some point...
289          * But for now, let's keep it well isolated here. */
290         if (type == SCE_COPY_EMPTY) {
291                 ToolSettings *ts;
292                 ListBase rl, rv;
293
294                 sce_copy = BKE_scene_add(bmain, sce->id.name + 2);
295
296                 rl = sce_copy->r.layers;
297                 rv = sce_copy->r.views;
298                 curvemapping_free_data(&sce_copy->r.mblur_shutter_curve);
299                 sce_copy->r = sce->r;
300                 sce_copy->r.layers = rl;
301                 sce_copy->r.actlay = 0;
302                 sce_copy->r.views = rv;
303                 sce_copy->unit = sce->unit;
304                 sce_copy->physics_settings = sce->physics_settings;
305                 sce_copy->gm = sce->gm;
306                 sce_copy->audio = sce->audio;
307
308                 if (sce->id.properties)
309                         sce_copy->id.properties = IDP_CopyProperty(sce->id.properties);
310
311                 MEM_freeN(sce_copy->toolsettings);
312                 BKE_sound_destroy_scene(sce_copy);
313
314                 /* copy color management settings */
315                 BKE_color_managed_display_settings_copy(&sce_copy->display_settings, &sce->display_settings);
316                 BKE_color_managed_view_settings_copy(&sce_copy->view_settings, &sce->view_settings);
317                 BKE_color_managed_colorspace_settings_copy(&sce_copy->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings);
318
319                 BKE_color_managed_display_settings_copy(&sce_copy->r.im_format.display_settings, &sce->r.im_format.display_settings);
320                 BKE_color_managed_view_settings_copy(&sce_copy->r.im_format.view_settings, &sce->r.im_format.view_settings);
321
322                 BKE_color_managed_display_settings_copy(&sce_copy->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings);
323                 BKE_color_managed_view_settings_copy(&sce_copy->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings);
324
325                 curvemapping_copy_data(&sce_copy->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
326
327                 /* tool settings */
328                 sce_copy->toolsettings = MEM_dupallocN(sce->toolsettings);
329
330                 ts = sce_copy->toolsettings;
331                 if (ts) {
332                         if (ts->vpaint) {
333                                 ts->vpaint = MEM_dupallocN(ts->vpaint);
334                                 BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, 0);
335                         }
336                         if (ts->wpaint) {
337                                 ts->wpaint = MEM_dupallocN(ts->wpaint);
338                                 BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, 0);
339                         }
340                         if (ts->sculpt) {
341                                 ts->sculpt = MEM_dupallocN(ts->sculpt);
342                                 BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, 0);
343                         }
344                         if (ts->uvsculpt) {
345                                 ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
346                                 BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, 0);
347                         }
348
349                         BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, 0);
350                         ts->imapaint.paintcursor = NULL;
351                         id_us_plus((ID *)ts->imapaint.stencil);
352                         id_us_plus((ID *)ts->imapaint.clone);
353                         id_us_plus((ID *)ts->imapaint.canvas);
354                         ts->particle.paintcursor = NULL;
355                         ts->particle.scene = NULL;
356                         ts->particle.object = NULL;
357
358                         /* duplicate Grease Pencil Drawing Brushes */
359                         BLI_listbase_clear(&ts->gp_brushes);
360                         for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) {
361                                 bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
362                                 BLI_addtail(&ts->gp_brushes, newbrush);
363                         }
364
365                         /* duplicate Grease Pencil interpolation curve */
366                         ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
367                 }
368
369                 /* make a private copy of the avicodecdata */
370                 if (sce->r.avicodecdata) {
371                         sce_copy->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
372                         sce_copy->r.avicodecdata->lpFormat = MEM_dupallocN(sce_copy->r.avicodecdata->lpFormat);
373                         sce_copy->r.avicodecdata->lpParms = MEM_dupallocN(sce_copy->r.avicodecdata->lpParms);
374                 }
375
376                 if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
377                         sce_copy->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
378                 }
379
380                 /* before scene copy */
381                 BKE_sound_create_scene(sce_copy);
382
383                 /* grease pencil */
384                 sce_copy->gpd = NULL;
385
386                 sce_copy->preview = NULL;
387
388                 return sce_copy;
389         }
390         else {
391                 BKE_id_copy_ex(bmain, (ID *)sce, (ID **)&sce_copy, LIB_ID_COPY_ACTIONS, false);
392                 id_us_min(&sce_copy->id);
393                 id_us_ensure_real(&sce_copy->id);
394
395                 /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks... */
396
397                 if (type == SCE_COPY_FULL) {
398                         /* Copy Freestyle LineStyle datablocks. */
399                         for (SceneRenderLayer *srl_dst = sce_copy->r.layers.first; srl_dst; srl_dst = srl_dst->next) {
400                                 for (FreestyleLineSet *lineset = srl_dst->freestyleConfig.linesets.first; lineset; lineset = lineset->next) {
401                                         if (lineset->linestyle) {
402                                                 /* XXX Not copying anim/actions here? */
403                                                 BKE_id_copy_ex(bmain, (ID *)lineset->linestyle, (ID **)&lineset->linestyle, 0, false);
404                                         }
405                                 }
406                         }
407
408                         /* Full copy of world (included animations) */
409                         if (sce_copy->world) {
410                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->world, (ID **)&sce_copy->world, LIB_ID_COPY_ACTIONS, false);
411                         }
412
413                         /* Full copy of GreasePencil. */
414                         /* XXX Not copying anim/actions here? */
415                         if (sce_copy->gpd) {
416                                 BKE_id_copy_ex(bmain, (ID *)sce_copy->gpd, (ID **)&sce_copy->gpd, 0, false);
417                         }
418                 }
419                 else {
420                         /* Remove sequencer if not full copy */
421                         /* XXX Why in Hell? :/ */
422                         remove_sequencer_fcurves(sce_copy);
423                         BKE_sequencer_editing_free(sce_copy);
424                 }
425
426                 /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
427                  * are done outside of blenkernel with ED_objects_single_users! */
428
429                 /*  camera */
430                 if (ELEM(type, SCE_COPY_LINK_DATA, SCE_COPY_FULL)) {
431                         ID_NEW_REMAP(sce_copy->camera);
432                 }
433
434                 return sce_copy;
435         }
436 }
437
438 void BKE_scene_groups_relink(Scene *sce)
439 {
440         if (sce->rigidbody_world)
441                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
442 }
443
444 void BKE_scene_make_local(Main *bmain, Scene *sce, const bool lib_local)
445 {
446         /* For now should work, may need more work though to support all possible corner cases
447          * (also scene_copy probably needs some love). */
448         BKE_id_make_local_generic(bmain, &sce->id, true, lib_local);
449 }
450
451 /** Free (or release) any data used by this scene (does not free the scene itself). */
452 void BKE_scene_free(Scene *sce)
453 {
454         SceneRenderLayer *srl;
455
456         BKE_animdata_free((ID *)sce, false);
457
458         /* check all sequences */
459         BKE_sequencer_clear_scene_in_allseqs(G.main, sce);
460
461         sce->basact = NULL;
462         BLI_freelistN(&sce->base);
463         BKE_sequencer_editing_free(sce);
464
465         BKE_keyingsets_free(&sce->keyingsets);
466
467         /* is no lib link block, but scene extension */
468         if (sce->nodetree) {
469                 ntreeFreeTree(sce->nodetree);
470                 MEM_freeN(sce->nodetree);
471                 sce->nodetree = NULL;
472         }
473
474         if (sce->rigidbody_world) {
475                 BKE_rigidbody_free_world(sce->rigidbody_world);
476                 sce->rigidbody_world = NULL;
477         }
478
479         if (sce->r.avicodecdata) {
480                 free_avicodecdata(sce->r.avicodecdata);
481                 MEM_freeN(sce->r.avicodecdata);
482                 sce->r.avicodecdata = NULL;
483         }
484         if (sce->r.ffcodecdata.properties) {
485                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
486                 MEM_freeN(sce->r.ffcodecdata.properties);
487                 sce->r.ffcodecdata.properties = NULL;
488         }
489
490         for (srl = sce->r.layers.first; srl; srl = srl->next) {
491                 if (srl->prop != NULL) {
492                         IDP_FreeProperty(srl->prop);
493                         MEM_freeN(srl->prop);
494                 }
495                 BKE_freestyle_config_free(&srl->freestyleConfig);
496         }
497
498         BLI_freelistN(&sce->markers);
499         BLI_freelistN(&sce->transform_spaces);
500         BLI_freelistN(&sce->r.layers);
501         BLI_freelistN(&sce->r.views);
502         
503         if (sce->toolsettings) {
504                 if (sce->toolsettings->vpaint) {
505                         BKE_paint_free(&sce->toolsettings->vpaint->paint);
506                         MEM_freeN(sce->toolsettings->vpaint);
507                 }
508                 if (sce->toolsettings->wpaint) {
509                         BKE_paint_free(&sce->toolsettings->wpaint->paint);
510                         MEM_freeN(sce->toolsettings->wpaint);
511                 }
512                 if (sce->toolsettings->sculpt) {
513                         BKE_paint_free(&sce->toolsettings->sculpt->paint);
514                         MEM_freeN(sce->toolsettings->sculpt);
515                 }
516                 if (sce->toolsettings->uvsculpt) {
517                         BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
518                         MEM_freeN(sce->toolsettings->uvsculpt);
519                 }
520                 BKE_paint_free(&sce->toolsettings->imapaint.paint);
521                 
522                 /* free Grease Pencil Drawing Brushes */
523                 BKE_gpencil_free_brushes(&sce->toolsettings->gp_brushes);
524                 BLI_freelistN(&sce->toolsettings->gp_brushes);
525                 
526                 /* free Grease Pencil interpolation curve */
527                 if (sce->toolsettings->gp_interpolate.custom_ipo) {
528                         curvemapping_free(sce->toolsettings->gp_interpolate.custom_ipo);
529                 }
530                 
531                 MEM_freeN(sce->toolsettings);
532                 sce->toolsettings = NULL;
533         }
534         
535         DAG_scene_free(sce);
536         if (sce->depsgraph)
537                 DEG_graph_free(sce->depsgraph);
538         
539         MEM_SAFE_FREE(sce->stats);
540         MEM_SAFE_FREE(sce->fps_info);
541
542         BKE_sound_destroy_scene(sce);
543
544         BKE_color_managed_view_settings_free(&sce->view_settings);
545
546         BKE_previewimg_free(&sce->preview);
547         curvemapping_free_data(&sce->r.mblur_shutter_curve);
548 }
549
550 void BKE_scene_init(Scene *sce)
551 {
552         ParticleEditSettings *pset;
553         int a;
554         const char *colorspace_name;
555         SceneRenderView *srv;
556         CurveMapping *mblur_shutter_curve;
557
558         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(sce, id));
559
560         sce->lay = sce->layact = 1;
561         
562         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
563         sce->r.cfra = 1;
564         sce->r.sfra = 1;
565         sce->r.efra = 250;
566         sce->r.frame_step = 1;
567         sce->r.xsch = 1920;
568         sce->r.ysch = 1080;
569         sce->r.xasp = 1;
570         sce->r.yasp = 1;
571         sce->r.tilex = 256;
572         sce->r.tiley = 256;
573         sce->r.mblur_samples = 1;
574         sce->r.filtertype = R_FILTER_MITCH;
575         sce->r.size = 50;
576
577         sce->r.im_format.planes = R_IMF_PLANES_RGBA;
578         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
579         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
580         sce->r.im_format.quality = 90;
581         sce->r.im_format.compress = 15;
582
583         sce->r.displaymode = R_OUTPUT_AREA;
584         sce->r.framapto = 100;
585         sce->r.images = 100;
586         sce->r.framelen = 1.0;
587         sce->r.blurfac = 0.5;
588         sce->r.frs_sec = 24;
589         sce->r.frs_sec_base = 1;
590         sce->r.edgeint = 10;
591         sce->r.ocres = 128;
592
593         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
594          *            images would look in the same way as in current blender
595          *
596          *            perhaps at some point should be completely deprecated?
597          */
598         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
599
600         sce->r.gauss = 1.0;
601         
602         /* deprecated but keep for upwards compat */
603         sce->r.postgamma = 1.0;
604         sce->r.posthue = 0.0;
605         sce->r.postsat = 1.0;
606
607         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
608         sce->r.bake_filter = 16;
609         sce->r.bake_osa = 5;
610         sce->r.bake_flag = R_BAKE_CLEAR;
611         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
612         sce->r.bake_samples = 256;
613         sce->r.bake_biasdist = 0.001;
614
615         sce->r.bake.flag = R_BAKE_CLEAR;
616         sce->r.bake.pass_filter = R_BAKE_PASS_FILTER_ALL;
617         sce->r.bake.width = 512;
618         sce->r.bake.height = 512;
619         sce->r.bake.margin = 16;
620         sce->r.bake.normal_space = R_BAKE_SPACE_TANGENT;
621         sce->r.bake.normal_swizzle[0] = R_BAKE_POSX;
622         sce->r.bake.normal_swizzle[1] = R_BAKE_POSY;
623         sce->r.bake.normal_swizzle[2] = R_BAKE_POSZ;
624         BLI_strncpy(sce->r.bake.filepath, U.renderdir, sizeof(sce->r.bake.filepath));
625
626         sce->r.bake.im_format.planes = R_IMF_PLANES_RGBA;
627         sce->r.bake.im_format.imtype = R_IMF_IMTYPE_PNG;
628         sce->r.bake.im_format.depth = R_IMF_CHAN_DEPTH_8;
629         sce->r.bake.im_format.quality = 90;
630         sce->r.bake.im_format.compress = 15;
631
632         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
633         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME | R_STAMP_MEMORY;
634         sce->r.stamp_font_id = 12;
635         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
636         sce->r.fg_stamp[3] = 1.0f;
637         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
638         sce->r.bg_stamp[3] = 0.25f;
639         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
640
641         sce->r.seq_prev_type = OB_SOLID;
642         sce->r.seq_rend_type = OB_SOLID;
643         sce->r.seq_flag = 0;
644
645         sce->r.threads = 1;
646
647         sce->r.simplify_subsurf = 6;
648         sce->r.simplify_particles = 1.0f;
649         sce->r.simplify_shadowsamples = 16;
650         sce->r.simplify_aosss = 1.0f;
651
652         sce->r.border.xmin = 0.0f;
653         sce->r.border.ymin = 0.0f;
654         sce->r.border.xmax = 1.0f;
655         sce->r.border.ymax = 1.0f;
656
657         sce->r.preview_start_resolution = 64;
658         
659         sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE;
660         sce->r.unit_line_thickness = 1.0f;
661
662         mblur_shutter_curve = &sce->r.mblur_shutter_curve;
663         curvemapping_set_defaults(mblur_shutter_curve, 1, 0.0f, 0.0f, 1.0f, 1.0f);
664         curvemapping_initialize(mblur_shutter_curve);
665         curvemap_reset(mblur_shutter_curve->cm,
666                        &mblur_shutter_curve->clipr,
667                        CURVE_PRESET_MAX,
668                        CURVEMAP_SLOPE_POS_NEG);
669
670         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
671         sce->toolsettings->doublimit = 0.001;
672         sce->toolsettings->vgroup_weight = 1.0f;
673         sce->toolsettings->uvcalc_margin = 0.001f;
674         sce->toolsettings->unwrapper = 1;
675         sce->toolsettings->select_thresh = 0.01f;
676
677         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
678         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
679         sce->toolsettings->normalsize = 0.1;
680         sce->toolsettings->autokey_mode = U.autokey_mode;
681
682         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
683
684         sce->toolsettings->skgen_resolution = 100;
685         sce->toolsettings->skgen_threshold_internal     = 0.01f;
686         sce->toolsettings->skgen_threshold_external     = 0.01f;
687         sce->toolsettings->skgen_angle_limit            = 45.0f;
688         sce->toolsettings->skgen_length_ratio           = 1.3f;
689         sce->toolsettings->skgen_length_limit           = 1.5f;
690         sce->toolsettings->skgen_correlation_limit      = 0.98f;
691         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
692         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
693         sce->toolsettings->skgen_postpro_passes = 1;
694         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
695         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
696         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
697         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
698
699         sce->toolsettings->curve_paint_settings.curve_type = CU_BEZIER;
700         sce->toolsettings->curve_paint_settings.flag |= CURVE_PAINT_FLAG_CORNERS_DETECT;
701         sce->toolsettings->curve_paint_settings.error_threshold = 8;
702         sce->toolsettings->curve_paint_settings.radius_max = 1.0f;
703         sce->toolsettings->curve_paint_settings.corner_angle = DEG2RADF(70.0f);
704
705         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
706         sce->toolsettings->statvis.overhang_min = 0;
707         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
708         sce->toolsettings->statvis.thickness_max = 0.1f;
709         sce->toolsettings->statvis.thickness_samples = 1;
710         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
711         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
712
713         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
714         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
715
716         sce->toolsettings->proportional_size = 1.0f;
717
718         sce->toolsettings->imapaint.paint.flags |= PAINT_SHOW_BRUSH;
719         sce->toolsettings->imapaint.normal_angle = 80;
720         sce->toolsettings->imapaint.seam_bleed = 2;
721
722         sce->physics_settings.gravity[0] = 0.0f;
723         sce->physics_settings.gravity[1] = 0.0f;
724         sce->physics_settings.gravity[2] = -9.81f;
725         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
726
727         sce->unit.scale_length = 1.0f;
728
729         pset = &sce->toolsettings->particle;
730         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
731         pset->emitterdist = 0.25f;
732         pset->totrekey = 5;
733         pset->totaddkey = 5;
734         pset->brushtype = PE_BRUSH_NONE;
735         pset->draw_step = 2;
736         pset->fade_frames = 2;
737         pset->selectmode = SCE_SELECT_PATH;
738
739         for (a = 0; a < ARRAY_SIZE(pset->brush); a++) {
740                 pset->brush[a].strength = 0.5f;
741                 pset->brush[a].size = 50;
742                 pset->brush[a].step = 10;
743                 pset->brush[a].count = 10;
744         }
745         pset->brush[PE_BRUSH_CUT].strength = 1.0f;
746
747         sce->r.ffcodecdata.audio_mixrate = 48000;
748         sce->r.ffcodecdata.audio_volume = 1.0f;
749         sce->r.ffcodecdata.audio_bitrate = 192;
750         sce->r.ffcodecdata.audio_channels = 2;
751
752         BLI_strncpy(sce->r.engine, RE_engine_id_BLENDER_RENDER, sizeof(sce->r.engine));
753
754         sce->audio.distance_model = 2.0f;
755         sce->audio.doppler_factor = 1.0f;
756         sce->audio.speed_of_sound = 343.3f;
757         sce->audio.volume = 1.0f;
758
759         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
760
761         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
762         sce->r.osa = 8;
763
764         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
765         BKE_scene_add_render_layer(sce, NULL);
766
767         /* multiview - stereo */
768         BKE_scene_add_render_view(sce, STEREO_LEFT_NAME);
769         srv = sce->r.views.first;
770         BLI_strncpy(srv->suffix, STEREO_LEFT_SUFFIX, sizeof(srv->suffix));
771
772         BKE_scene_add_render_view(sce, STEREO_RIGHT_NAME);
773         srv = sce->r.views.last;
774         BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix));
775
776         /* game data */
777         sce->gm.stereoflag = STEREO_NOSTEREO;
778         sce->gm.stereomode = STEREO_ANAGLYPH;
779         sce->gm.eyeseparation = 0.10;
780
781         sce->gm.dome.angle = 180;
782         sce->gm.dome.mode = DOME_FISHEYE;
783         sce->gm.dome.res = 4;
784         sce->gm.dome.resbuf = 1.0f;
785         sce->gm.dome.tilt = 0;
786
787         sce->gm.xplay = 640;
788         sce->gm.yplay = 480;
789         sce->gm.freqplay = 60;
790         sce->gm.depth = 32;
791
792         sce->gm.gravity = 9.8f;
793         sce->gm.physicsEngine = WOPHY_BULLET;
794         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
795         sce->gm.occlusionRes = 128;
796         sce->gm.ticrate = 60;
797         sce->gm.maxlogicstep = 5;
798         sce->gm.physubstep = 1;
799         sce->gm.maxphystep = 5;
800         sce->gm.lineardeactthreshold = 0.8f;
801         sce->gm.angulardeactthreshold = 1.0f;
802         sce->gm.deactivationtime = 0.0f;
803
804         sce->gm.flag = GAME_DISPLAY_LISTS;
805         sce->gm.matmode = GAME_MAT_MULTITEX;
806
807         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
808         sce->gm.levelHeight = 2.f;
809
810         sce->gm.recastData.cellsize = 0.3f;
811         sce->gm.recastData.cellheight = 0.2f;
812         sce->gm.recastData.agentmaxslope = M_PI_4;
813         sce->gm.recastData.agentmaxclimb = 0.9f;
814         sce->gm.recastData.agentheight = 2.0f;
815         sce->gm.recastData.agentradius = 0.6f;
816         sce->gm.recastData.edgemaxlen = 12.0f;
817         sce->gm.recastData.edgemaxerror = 1.3f;
818         sce->gm.recastData.regionminsize = 8.f;
819         sce->gm.recastData.regionmergesize = 20.f;
820         sce->gm.recastData.vertsperpoly = 6;
821         sce->gm.recastData.detailsampledist = 6.0f;
822         sce->gm.recastData.detailsamplemaxerror = 1.0f;
823
824         sce->gm.lodflag = SCE_LOD_USE_HYST;
825         sce->gm.scehysteresis = 10;
826
827         sce->gm.exitkey = 218; // Blender key code for ESC
828
829         BKE_sound_create_scene(sce);
830
831         /* color management */
832         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
833
834         BKE_color_managed_display_settings_init(&sce->display_settings);
835         BKE_color_managed_view_settings_init(&sce->view_settings);
836         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
837                     sizeof(sce->sequencer_colorspace_settings.name));
838
839         /* Safe Areas */
840         copy_v2_fl2(sce->safe_areas.title, 3.5f / 100.0f, 3.5f / 100.0f);
841         copy_v2_fl2(sce->safe_areas.action, 10.0f / 100.0f, 5.0f / 100.0f);
842         copy_v2_fl2(sce->safe_areas.title_center, 17.5f / 100.0f, 5.0f / 100.0f);
843         copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f);
844
845         sce->preview = NULL;
846         
847         /* GP Sculpt brushes */
848         {
849                 GP_BrushEdit_Settings *gset = &sce->toolsettings->gp_sculpt;
850                 GP_EditBrush_Data *gp_brush;
851                 
852                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH];
853                 gp_brush->size = 25;
854                 gp_brush->strength = 0.3f;
855                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE;
856                 
857                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS];
858                 gp_brush->size = 25;
859                 gp_brush->strength = 0.5f;
860                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
861                 
862                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_STRENGTH];
863                 gp_brush->size = 25;
864                 gp_brush->strength = 0.5f;
865                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
866
867                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_GRAB];
868                 gp_brush->size = 50;
869                 gp_brush->strength = 0.3f;
870                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
871                 
872                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH];
873                 gp_brush->size = 25;
874                 gp_brush->strength = 0.3f;
875                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
876                 
877                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST];
878                 gp_brush->size = 50;
879                 gp_brush->strength = 0.3f; // XXX?
880                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
881                 
882                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH];
883                 gp_brush->size = 50;
884                 gp_brush->strength = 0.5f; // XXX?
885                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
886                 
887                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE];
888                 gp_brush->size = 25;
889                 gp_brush->strength = 0.5f;
890                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
891         }
892         
893         /* GP Stroke Placement */
894         sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE;
895         sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE;
896         sce->toolsettings->gpencil_seq_align = GP_PROJECT_VIEWSPACE;
897         sce->toolsettings->gpencil_ima_align = GP_PROJECT_VIEWSPACE;
898 }
899
900 Scene *BKE_scene_add(Main *bmain, const char *name)
901 {
902         Scene *sce;
903
904         sce = BKE_libblock_alloc(bmain, ID_SCE, name, 0);
905         id_us_min(&sce->id);
906         id_us_ensure_real(&sce->id);
907
908         BKE_scene_init(sce);
909
910         return sce;
911 }
912
913 Base *BKE_scene_base_find_by_name(struct Scene *scene, const char *name)
914 {
915         Base *base;
916
917         for (base = scene->base.first; base; base = base->next) {
918                 if (STREQ(base->object->id.name + 2, name)) {
919                         break;
920                 }
921         }
922
923         return base;
924 }
925
926 Base *BKE_scene_base_find(Scene *scene, Object *ob)
927 {
928         return BLI_findptr(&scene->base, ob, offsetof(Base, object));
929 }
930
931 /**
932  * Sets the active scene, mainly used when running in background mode (``--scene`` command line argument).
933  * This is also called to set the scene directly, bypassing windowing code.
934  * Otherwise #ED_screen_set_scene is used when changing scenes by the user.
935  */
936 void BKE_scene_set_background(Main *bmain, Scene *scene)
937 {
938         Scene *sce;
939         Base *base;
940         Object *ob;
941         Group *group;
942         GroupObject *go;
943         int flag;
944         
945         /* check for cyclic sets, for reading old files but also for definite security (py?) */
946         BKE_scene_validate_setscene(bmain, scene);
947         
948         /* can happen when switching modes in other scenes */
949         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
950                 scene->obedit = NULL;
951
952         /* deselect objects (for dataselect) */
953         for (ob = bmain->object.first; ob; ob = ob->id.next)
954                 ob->flag &= ~(SELECT | OB_FROMGROUP);
955
956         /* group flags again */
957         for (group = bmain->group.first; group; group = group->id.next) {
958                 for (go = group->gobject.first; go; go = go->next) {
959                         if (go->ob) {
960                                 go->ob->flag |= OB_FROMGROUP;
961                         }
962                 }
963         }
964
965         /* sort baselist for scene and sets */
966         for (sce = scene; sce; sce = sce->set)
967                 DAG_scene_relations_rebuild(bmain, sce);
968
969         /* copy layers and flags from bases to objects */
970         for (base = scene->base.first; base; base = base->next) {
971                 ob = base->object;
972                 ob->lay = base->lay;
973                 
974                 /* group patch... */
975                 base->flag &= ~(OB_FROMGROUP);
976                 flag = ob->flag & (OB_FROMGROUP);
977                 base->flag |= flag;
978                 
979                 /* not too nice... for recovering objects with lost data */
980                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
981                 ob->flag = base->flag;
982         }
983         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
984 }
985
986 /* called from creator_args.c */
987 Scene *BKE_scene_set_name(Main *bmain, const char *name)
988 {
989         Scene *sce = (Scene *)BKE_libblock_find_name_ex(bmain, ID_SCE, name);
990         if (sce) {
991                 BKE_scene_set_background(bmain, sce);
992                 printf("Scene switch for render: '%s' in file: '%s'\n", name, bmain->name);
993                 return sce;
994         }
995
996         printf("Can't find scene: '%s' in file: '%s'\n", name, bmain->name);
997         return NULL;
998 }
999
1000 /* Used by metaballs, return *all* objects (including duplis) existing in the scene (including scene's sets) */
1001 int BKE_scene_base_iter_next(EvaluationContext *eval_ctx, SceneBaseIter *iter,
1002                              Scene **scene, int val, Base **base, Object **ob)
1003 {
1004         bool run_again = true;
1005         
1006         /* init */
1007         if (val == 0) {
1008                 iter->phase = F_START;
1009                 iter->dupob = NULL;
1010                 iter->duplilist = NULL;
1011                 iter->dupli_refob = NULL;
1012         }
1013         else {
1014                 /* run_again is set when a duplilist has been ended */
1015                 while (run_again) {
1016                         run_again = false;
1017
1018                         /* the first base */
1019                         if (iter->phase == F_START) {
1020                                 *base = (*scene)->base.first;
1021                                 if (*base) {
1022                                         *ob = (*base)->object;
1023                                         iter->phase = F_SCENE;
1024                                 }
1025                                 else {
1026                                         /* exception: empty scene */
1027                                         while ((*scene)->set) {
1028                                                 (*scene) = (*scene)->set;
1029                                                 if ((*scene)->base.first) {
1030                                                         *base = (*scene)->base.first;
1031                                                         *ob = (*base)->object;
1032                                                         iter->phase = F_SCENE;
1033                                                         break;
1034                                                 }
1035                                         }
1036                                 }
1037                         }
1038                         else {
1039                                 if (*base && iter->phase != F_DUPLI) {
1040                                         *base = (*base)->next;
1041                                         if (*base) {
1042                                                 *ob = (*base)->object;
1043                                         }
1044                                         else {
1045                                                 if (iter->phase == F_SCENE) {
1046                                                         /* (*scene) is finished, now do the set */
1047                                                         while ((*scene)->set) {
1048                                                                 (*scene) = (*scene)->set;
1049                                                                 if ((*scene)->base.first) {
1050                                                                         *base = (*scene)->base.first;
1051                                                                         *ob = (*base)->object;
1052                                                                         break;
1053                                                                 }
1054                                                         }
1055                                                 }
1056                                         }
1057                                 }
1058                         }
1059                         
1060                         if (*base == NULL) {
1061                                 iter->phase = F_START;
1062                         }
1063                         else {
1064                                 if (iter->phase != F_DUPLI) {
1065                                         if ( (*base)->object->transflag & OB_DUPLI) {
1066                                                 /* groups cannot be duplicated for mballs yet, 
1067                                                  * this enters eternal loop because of 
1068                                                  * makeDispListMBall getting called inside of group_duplilist */
1069                                                 if ((*base)->object->dup_group == NULL) {
1070                                                         iter->duplilist = object_duplilist_ex(eval_ctx, (*scene), (*base)->object, false);
1071                                                         
1072                                                         iter->dupob = iter->duplilist->first;
1073
1074                                                         if (!iter->dupob) {
1075                                                                 free_object_duplilist(iter->duplilist);
1076                                                                 iter->duplilist = NULL;
1077                                                         }
1078                                                         iter->dupli_refob = NULL;
1079                                                 }
1080                                         }
1081                                 }
1082                                 /* handle dupli's */
1083                                 if (iter->dupob) {
1084                                         (*base)->flag |= OB_FROMDUPLI;
1085                                         *ob = iter->dupob->ob;
1086                                         iter->phase = F_DUPLI;
1087
1088                                         if (iter->dupli_refob != *ob) {
1089                                                 if (iter->dupli_refob) {
1090                                                         /* Restore previous object's real matrix. */
1091                                                         copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1092                                                 }
1093                                                 /* Backup new object's real matrix. */
1094                                                 iter->dupli_refob = *ob;
1095                                                 copy_m4_m4(iter->omat, iter->dupli_refob->obmat);
1096                                         }
1097                                         copy_m4_m4((*ob)->obmat, iter->dupob->mat);
1098
1099                                         iter->dupob = iter->dupob->next;
1100                                 }
1101                                 else if (iter->phase == F_DUPLI) {
1102                                         iter->phase = F_SCENE;
1103                                         (*base)->flag &= ~OB_FROMDUPLI;
1104                                         
1105                                         if (iter->dupli_refob) {
1106                                                 /* Restore last object's real matrix. */
1107                                                 copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1108                                                 iter->dupli_refob = NULL;
1109                                         }
1110                                         
1111                                         free_object_duplilist(iter->duplilist);
1112                                         iter->duplilist = NULL;
1113                                         run_again = true;
1114                                 }
1115                         }
1116                 }
1117         }
1118
1119 #if 0
1120         if (ob && *ob) {
1121                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
1122         }
1123 #endif
1124
1125         return iter->phase;
1126 }
1127
1128 Object *BKE_scene_camera_find(Scene *sc)
1129 {
1130         Base *base;
1131         
1132         for (base = sc->base.first; base; base = base->next)
1133                 if (base->object->type == OB_CAMERA)
1134                         return base->object;
1135
1136         return NULL;
1137 }
1138
1139 #ifdef DURIAN_CAMERA_SWITCH
1140 Object *BKE_scene_camera_switch_find(Scene *scene)
1141 {
1142         if (scene->r.mode & R_NO_CAMERA_SWITCH) {
1143                 return NULL;
1144         }
1145
1146         TimeMarker *m;
1147         int cfra = scene->r.cfra;
1148         int frame = -(MAXFRAME + 1);
1149         int min_frame = MAXFRAME + 1;
1150         Object *camera = NULL;
1151         Object *first_camera = NULL;
1152
1153         for (m = scene->markers.first; m; m = m->next) {
1154                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
1155                         if ((m->frame <= cfra) && (m->frame > frame)) {
1156                                 camera = m->camera;
1157                                 frame = m->frame;
1158
1159                                 if (frame == cfra)
1160                                         break;
1161                         }
1162
1163                         if (m->frame < min_frame) {
1164                                 first_camera = m->camera;
1165                                 min_frame = m->frame;
1166                         }
1167                 }
1168         }
1169
1170         if (camera == NULL) {
1171                 /* If there's no marker to the left of current frame,
1172                  * use camera from left-most marker to solve all sort
1173                  * of Schrodinger uncertainties.
1174                  */
1175                 return first_camera;
1176         }
1177
1178         return camera;
1179 }
1180 #endif
1181
1182 int BKE_scene_camera_switch_update(Scene *scene)
1183 {
1184 #ifdef DURIAN_CAMERA_SWITCH
1185         Object *camera = BKE_scene_camera_switch_find(scene);
1186         if (camera) {
1187                 scene->camera = camera;
1188                 return 1;
1189         }
1190 #else
1191         (void)scene;
1192 #endif
1193         return 0;
1194 }
1195
1196 char *BKE_scene_find_marker_name(Scene *scene, int frame)
1197 {
1198         ListBase *markers = &scene->markers;
1199         TimeMarker *m1, *m2;
1200
1201         /* search through markers for match */
1202         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
1203                 if (m1->frame == frame)
1204                         return m1->name;
1205
1206                 if (m1 == m2)
1207                         break;
1208
1209                 if (m2->frame == frame)
1210                         return m2->name;
1211         }
1212
1213         return NULL;
1214 }
1215
1216 /* return the current marker for this frame,
1217  * we can have more than 1 marker per frame, this just returns the first :/ */
1218 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
1219 {
1220         TimeMarker *marker, *best_marker = NULL;
1221         int best_frame = -MAXFRAME * 2;
1222         for (marker = scene->markers.first; marker; marker = marker->next) {
1223                 if (marker->frame == frame) {
1224                         return marker->name;
1225                 }
1226
1227                 if (marker->frame > best_frame && marker->frame < frame) {
1228                         best_marker = marker;
1229                         best_frame = marker->frame;
1230                 }
1231         }
1232
1233         return best_marker ? best_marker->name : NULL;
1234 }
1235
1236
1237 Base *BKE_scene_base_add(Scene *sce, Object *ob)
1238 {
1239         Base *b = MEM_callocN(sizeof(*b), __func__);
1240         BLI_addhead(&sce->base, b);
1241
1242         b->object = ob;
1243         b->flag = ob->flag;
1244         b->lay = ob->lay;
1245
1246         return b;
1247 }
1248
1249 void BKE_scene_base_unlink(Scene *sce, Base *base)
1250 {
1251         /* remove rigid body constraint from world before removing object */
1252         if (base->object->rigidbody_constraint)
1253                 BKE_rigidbody_remove_constraint(sce, base->object);
1254         /* remove rigid body object from world before removing object */
1255         if (base->object->rigidbody_object)
1256                 BKE_rigidbody_remove_object(sce, base->object);
1257         
1258         BLI_remlink(&sce->base, base);
1259         if (sce->basact == base)
1260                 sce->basact = NULL;
1261 }
1262
1263 void BKE_scene_base_deselect_all(Scene *sce)
1264 {
1265         Base *b;
1266
1267         for (b = sce->base.first; b; b = b->next) {
1268                 b->flag &= ~SELECT;
1269                 b->object->flag = b->flag;
1270         }
1271 }
1272
1273 void BKE_scene_base_select(Scene *sce, Base *selbase)
1274 {
1275         selbase->flag |= SELECT;
1276         selbase->object->flag = selbase->flag;
1277
1278         sce->basact = selbase;
1279 }
1280
1281 /* checks for cycle, returns 1 if it's all OK */
1282 bool BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1283 {
1284         Scene *sce_iter;
1285         int a, totscene;
1286
1287         if (sce->set == NULL) return true;
1288         totscene = BLI_listbase_count(&bmain->scene);
1289         
1290         for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) {
1291                 /* more iterations than scenes means we have a cycle */
1292                 if (a > totscene) {
1293                         /* the tested scene gets zero'ed, that's typically current scene */
1294                         sce->set = NULL;
1295                         return false;
1296                 }
1297         }
1298
1299         return true;
1300 }
1301
1302 /* This function is needed to cope with fractional frames - including two Blender rendering features
1303  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1304  */
1305 float BKE_scene_frame_get(const Scene *scene)
1306 {
1307         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1308 }
1309
1310 /* This function is used to obtain arbitrary fractional frames */
1311 float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame)
1312 {
1313         float ctime = frame;
1314         ctime += scene->r.subframe;
1315         ctime *= scene->r.framelen;
1316         
1317         return ctime;
1318 }
1319
1320 /**
1321  * Sets the frame int/float components.
1322  */
1323 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1324 {
1325         double intpart;
1326         scene->r.subframe = modf(cfra, &intpart);
1327         scene->r.cfra = (int)intpart;
1328 }
1329
1330 #ifdef WITH_LEGACY_DEPSGRAPH
1331 /* drivers support/hacks 
1332  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
1333  *      - these are always run since the depsgraph can't handle non-object data
1334  *      - these happen after objects are all done so that we can read in their final transform values,
1335  *        though this means that objects can't refer to scene info for guidance...
1336  */
1337 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
1338 {
1339         SceneRenderLayer *srl;
1340         float ctime = BKE_scene_frame_get(scene);
1341         
1342         /* scene itself */
1343         if (scene->adt && scene->adt->drivers.first) {
1344                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
1345         }
1346
1347         /* world */
1348         /* TODO: what about world textures? but then those have nodes too... */
1349         if (scene->world) {
1350                 ID *wid = (ID *)scene->world;
1351                 AnimData *adt = BKE_animdata_from_id(wid);
1352                 
1353                 if (adt && adt->drivers.first)
1354                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
1355         }
1356         
1357         /* nodes */
1358         if (scene->nodetree) {
1359                 ID *nid = (ID *)scene->nodetree;
1360                 AnimData *adt = BKE_animdata_from_id(nid);
1361                 
1362                 if (adt && adt->drivers.first)
1363                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1364         }
1365
1366         /* world nodes */
1367         if (scene->world && scene->world->nodetree) {
1368                 ID *nid = (ID *)scene->world->nodetree;
1369                 AnimData *adt = BKE_animdata_from_id(nid);
1370                 
1371                 if (adt && adt->drivers.first)
1372                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1373         }
1374
1375         /* freestyle */
1376         for (srl = scene->r.layers.first; srl; srl = srl->next) {
1377                 FreestyleConfig *config = &srl->freestyleConfig;
1378                 FreestyleLineSet *lineset;
1379
1380                 for (lineset = config->linesets.first; lineset; lineset = lineset->next) {
1381                         if (lineset->linestyle) {
1382                                 ID *lid = &lineset->linestyle->id;
1383                                 AnimData *adt = BKE_animdata_from_id(lid);
1384
1385                                 if (adt && adt->drivers.first)
1386                                         BKE_animsys_evaluate_animdata(scene, lid, adt, ctime, ADT_RECALC_DRIVERS);
1387                         }
1388                 }
1389         }
1390 }
1391
1392 /* deps hack - do extra recalcs at end */
1393 static void scene_depsgraph_hack(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1394 {
1395         Base *base;
1396                 
1397         scene->customdata_mask = scene_parent->customdata_mask;
1398         
1399         /* sets first, we allow per definition current scene to have
1400          * dependencies on sets, but not the other way around. */
1401         if (scene->set)
1402                 scene_depsgraph_hack(eval_ctx, scene->set, scene_parent);
1403         
1404         for (base = scene->base.first; base; base = base->next) {
1405                 Object *ob = base->object;
1406                 
1407                 if (ob->depsflag) {
1408                         int recalc = 0;
1409                         // printf("depshack %s\n", ob->id.name + 2);
1410                         
1411                         if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC)
1412                                 recalc |= OB_RECALC_OB;
1413                         if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC)
1414                                 recalc |= OB_RECALC_DATA;
1415                         
1416                         ob->recalc |= recalc;
1417                         BKE_object_handle_update(eval_ctx, scene_parent, ob);
1418                         
1419                         if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1420                                 GroupObject *go;
1421                                 
1422                                 for (go = ob->dup_group->gobject.first; go; go = go->next) {
1423                                         if (go->ob)
1424                                                 go->ob->recalc |= recalc;
1425                                 }
1426                                 BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, ob, ob->dup_group);
1427                         }
1428                 }
1429         }
1430 }
1431 #endif  /* WITH_LEGACY_DEPSGRAPH */
1432
1433 /* That's like really a bummer, because currently animation data for armatures
1434  * might want to use pose, and pose might be missing on the object.
1435  * This happens when changing visible layers, which leads to situations when
1436  * pose is missing or marked for recalc, animation will change it and then
1437  * object update will restore the pose.
1438  *
1439  * This could be solved by the new dependency graph, but for until then we'll
1440  * do an extra pass on the objects to ensure it's all fine.
1441  */
1442 #define POSE_ANIMATION_WORKAROUND
1443
1444 #ifdef POSE_ANIMATION_WORKAROUND
1445 static void scene_armature_depsgraph_workaround(Main *bmain)
1446 {
1447         Object *ob;
1448         if (BLI_listbase_is_empty(&bmain->armature) || !DAG_id_type_tagged(bmain, ID_OB)) {
1449                 return;
1450         }
1451         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1452                 if (ob->type == OB_ARMATURE && ob->adt && ob->adt->recalc & ADT_RECALC_ANIM) {
1453                         if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
1454                                 BKE_pose_rebuild(ob, ob->data);
1455                         }
1456                 }
1457         }
1458 }
1459 #endif
1460
1461 #ifdef WITH_LEGACY_DEPSGRAPH
1462 static void scene_rebuild_rbw_recursive(Scene *scene, float ctime)
1463 {
1464         if (scene->set)
1465                 scene_rebuild_rbw_recursive(scene->set, ctime);
1466
1467         if (BKE_scene_check_rigidbody_active(scene))
1468                 BKE_rigidbody_rebuild_world(scene, ctime);
1469 }
1470
1471 static void scene_do_rb_simulation_recursive(Scene *scene, float ctime)
1472 {
1473         if (scene->set)
1474                 scene_do_rb_simulation_recursive(scene->set, ctime);
1475
1476         if (BKE_scene_check_rigidbody_active(scene))
1477                 BKE_rigidbody_do_simulation(scene, ctime);
1478 }
1479 #endif
1480
1481 /* Used to visualize CPU threads activity during threaded object update,
1482  * would pollute STDERR with whole bunch of timing information which then
1483  * could be parsed and nicely visualized.
1484  */
1485 #ifdef WITH_LEGACY_DEPSGRAPH
1486 #  undef DETAILED_ANALYSIS_OUTPUT
1487 #else
1488 /* ALWAYS KEEY DISABLED! */
1489 #  undef DETAILED_ANALYSIS_OUTPUT
1490 #endif
1491
1492 /* Mballs evaluation uses BKE_scene_base_iter_next which calls
1493  * duplilist for all objects in the scene. This leads to conflict
1494  * accessing and writing same data from multiple threads.
1495  *
1496  * Ideally Mballs shouldn't do such an iteration and use DAG
1497  * queries instead. For the time being we've got new DAG
1498  * let's keep it simple and update mballs in a single thread.
1499  */
1500 #define MBALL_SINGLETHREAD_HACK
1501
1502 #ifdef WITH_LEGACY_DEPSGRAPH
1503 typedef struct StatisicsEntry {
1504         struct StatisicsEntry *next, *prev;
1505         Object *object;
1506         double start_time;
1507         double duration;
1508 } StatisicsEntry;
1509
1510 typedef struct ThreadedObjectUpdateState {
1511         /* TODO(sergey): We might want this to be per-thread object. */
1512         EvaluationContext *eval_ctx;
1513         Scene *scene;
1514         Scene *scene_parent;
1515         double base_time;
1516
1517 #ifdef MBALL_SINGLETHREAD_HACK
1518         bool has_mballs;
1519 #endif
1520
1521         int num_threads;
1522
1523         /* Execution statistics */
1524         bool has_updated_objects;
1525         ListBase *statistics;
1526 } ThreadedObjectUpdateState;
1527
1528 static void scene_update_object_add_task(void *node, void *user_data);
1529
1530 static void scene_update_all_bases(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1531 {
1532         Base *base;
1533
1534         for (base = scene->base.first; base; base = base->next) {
1535                 Object *object = base->object;
1536
1537                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, true);
1538
1539                 if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1540                         BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, object, object->dup_group);
1541
1542                 /* always update layer, so that animating layers works (joshua july 2010) */
1543                 /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes
1544                  * (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */
1545                 // base->lay = ob->lay;
1546         }
1547 }
1548
1549 static void scene_update_object_func(TaskPool * __restrict pool, void *taskdata, int threadid)
1550 {
1551 /* Disable print for now in favor of summary statistics at the end of update. */
1552 #define PRINT if (false) printf
1553
1554         ThreadedObjectUpdateState *state = (ThreadedObjectUpdateState *) BLI_task_pool_userdata(pool);
1555         void *node = taskdata;
1556         Object *object = DAG_get_node_object(node);
1557         EvaluationContext *eval_ctx = state->eval_ctx;
1558         Scene *scene = state->scene;
1559         Scene *scene_parent = state->scene_parent;
1560
1561 #ifdef MBALL_SINGLETHREAD_HACK
1562         if (object && object->type == OB_MBALL) {
1563                 state->has_mballs = true;
1564         }
1565         else
1566 #endif
1567         if (object) {
1568                 double start_time = 0.0;
1569                 bool add_to_stats = false;
1570
1571                 if (G.debug & G_DEBUG_DEPSGRAPH) {
1572                         if (object->recalc & OB_RECALC_ALL) {
1573                                 printf("Thread %d: update object %s\n", threadid, object->id.name);
1574                         }
1575
1576                         start_time = PIL_check_seconds_timer();
1577
1578                         if (object->recalc & OB_RECALC_ALL) {
1579                                 state->has_updated_objects = true;
1580                                 add_to_stats = true;
1581                         }
1582                 }
1583
1584                 /* We only update object itself here, dupli-group will be updated
1585                  * separately from main thread because of we've got no idea about
1586                  * dependencies inside the group.
1587                  */
1588                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, false);
1589
1590                 /* Calculate statistics. */
1591                 if (add_to_stats) {
1592                         StatisicsEntry *entry;
1593
1594                         entry = MEM_mallocN(sizeof(StatisicsEntry), "update thread statistics");
1595                         entry->object = object;
1596                         entry->start_time = start_time;
1597                         entry->duration = PIL_check_seconds_timer() - start_time;
1598
1599                         BLI_addtail(&state->statistics[threadid], entry);
1600                 }
1601         }
1602         else {
1603                 PRINT("Threda %d: update node %s\n", threadid,
1604                       DAG_get_node_name(scene, node));
1605         }
1606
1607         /* Update will decrease child's valency and schedule child with zero valency. */
1608         DAG_threaded_update_handle_node_updated(node, scene_update_object_add_task, pool);
1609
1610 #undef PRINT
1611 }
1612
1613 static void scene_update_object_add_task(void *node, void *user_data)
1614 {
1615         TaskPool *task_pool = user_data;
1616
1617         BLI_task_pool_push(task_pool, scene_update_object_func, node, false, TASK_PRIORITY_LOW);
1618 }
1619
1620 static void print_threads_statistics(ThreadedObjectUpdateState *state)
1621 {
1622         double finish_time;
1623
1624         if ((G.debug & G_DEBUG_DEPSGRAPH) == 0) {
1625                 return;
1626         }
1627
1628 #ifdef DETAILED_ANALYSIS_OUTPUT
1629         if (state->has_updated_objects) {
1630                 tot_thread = BLI_system_thread_count();
1631
1632                 fprintf(stderr, "objects update base time %f\n", state->base_time);
1633
1634                 for (i = 0; i < tot_thread; i++) {
1635                         StatisicsEntry *entry;
1636                         for (entry = state->statistics[i].first;
1637                              entry;
1638                              entry = entry->next)
1639                         {
1640                                 fprintf(stderr, "thread %d object %s start_time %f duration %f\n",
1641                                         i, entry->object->id.name + 2,
1642                                         entry->start_time, entry->duration);
1643                         }
1644                         BLI_freelistN(&state->statistics[i]);
1645                 }
1646         }
1647 #else
1648         finish_time = PIL_check_seconds_timer();
1649         int total_objects = 0;
1650
1651         for (int i = 0; i < state->num_threads; i++) {
1652                 int thread_total_objects = 0;
1653                 double thread_total_time = 0.0;
1654                 StatisicsEntry *entry;
1655
1656                 if (state->has_updated_objects) {
1657                         /* Don't pollute output if no objects were updated. */
1658                         for (entry = state->statistics[i].first;
1659                              entry;
1660                              entry = entry->next)
1661                         {
1662                                 thread_total_objects++;
1663                                 thread_total_time += entry->duration;
1664                         }
1665
1666                         printf("Thread %d: total %d objects in %f sec.\n",
1667                                i,
1668                                thread_total_objects,
1669                                thread_total_time);
1670
1671                         for (entry = state->statistics[i].first;
1672                              entry;
1673                              entry = entry->next)
1674                         {
1675                                 printf("  %s in %f sec\n", entry->object->id.name + 2, entry->duration);
1676                         }
1677
1678                         total_objects += thread_total_objects;
1679                 }
1680
1681                 BLI_freelistN(&state->statistics[i]);
1682         }
1683         if (state->has_updated_objects) {
1684                 printf("Scene updated %d objects in %f sec\n",
1685                        total_objects,
1686                        finish_time - state->base_time);
1687         }
1688 #endif
1689 }
1690
1691 static bool scene_need_update_objects(Main *bmain)
1692 {
1693         return
1694                 /* Object datablocks themselves (for OB_RECALC_OB) */
1695                 DAG_id_type_tagged(bmain, ID_OB) ||
1696
1697                 /* Objects data datablocks (for OB_RECALC_DATA) */
1698                 DAG_id_type_tagged(bmain, ID_ME)  ||  /* Mesh */
1699                 DAG_id_type_tagged(bmain, ID_CU)  ||  /* Curve */
1700                 DAG_id_type_tagged(bmain, ID_MB)  ||  /* MetaBall */
1701                 DAG_id_type_tagged(bmain, ID_LA)  ||  /* Lamp */
1702                 DAG_id_type_tagged(bmain, ID_LT)  ||  /* Lattice */
1703                 DAG_id_type_tagged(bmain, ID_CA)  ||  /* Camera */
1704                 DAG_id_type_tagged(bmain, ID_KE)  ||  /* KE */
1705                 DAG_id_type_tagged(bmain, ID_SPK) ||  /* Speaker */
1706                 DAG_id_type_tagged(bmain, ID_AR);     /* Armature */
1707 }
1708
1709 static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1710 {
1711         TaskScheduler *task_scheduler;
1712         TaskPool *task_pool;
1713         ThreadedObjectUpdateState state;
1714         bool need_singlethread_pass;
1715         bool need_free_scheduler;
1716
1717         /* Early check for whether we need to invoke all the task-based
1718          * things (spawn new ppol, traverse dependency graph and so on).
1719          *
1720          * Basically if there's no ID datablocks tagged for update which
1721          * corresponds to object->recalc flags (which are checked in
1722          * BKE_object_handle_update() then we do nothing here.
1723          */
1724         if (!scene_need_update_objects(bmain)) {
1725                 return;
1726         }
1727
1728         state.eval_ctx = eval_ctx;
1729         state.scene = scene;
1730         state.scene_parent = scene_parent;
1731
1732         if (G.debug & G_DEBUG_DEPSGRAPH_NO_THREADS) {
1733                 task_scheduler = BLI_task_scheduler_create(1);
1734                 need_free_scheduler = true;
1735         }
1736         else {
1737                 task_scheduler = BLI_task_scheduler_get();
1738                 need_free_scheduler = false;
1739         }
1740
1741         /* Those are only needed when blender is run with --debug argument. */
1742         if (G.debug & G_DEBUG_DEPSGRAPH) {
1743                 const int tot_thread = BLI_task_scheduler_num_threads(task_scheduler);
1744                 state.statistics = MEM_callocN(tot_thread * sizeof(*state.statistics),
1745                                                "scene update objects stats");
1746                 state.has_updated_objects = false;
1747                 state.base_time = PIL_check_seconds_timer();
1748                 state.num_threads = tot_thread;
1749         }
1750
1751 #ifdef MBALL_SINGLETHREAD_HACK
1752         state.has_mballs = false;
1753 #endif
1754
1755         task_pool = BLI_task_pool_create(task_scheduler, &state);
1756
1757         DAG_threaded_update_begin(scene, scene_update_object_add_task, task_pool);
1758         BLI_task_pool_work_and_wait(task_pool);
1759         BLI_task_pool_free(task_pool);
1760
1761         if (G.debug & G_DEBUG_DEPSGRAPH) {
1762                 print_threads_statistics(&state);
1763                 MEM_freeN(state.statistics);
1764         }
1765
1766         /* We do single thread pass to update all the objects which are in cyclic dependency.
1767          * Such objects can not be handled by a generic DAG traverse and it's really tricky
1768          * to detect whether cycle could be solved or not.
1769          *
1770          * In this situation we simply update all remaining objects in a single thread and
1771          * it'll happen in the same exact order as it was in single-threaded DAG.
1772          *
1773          * We couldn't use threaded update for objects which are in cycle because they might
1774          * access data of each other which is being re-evaluated.
1775          *
1776          * Also, as was explained above, for now we also update all the mballs in single thread.
1777          *
1778          *                                                                   - sergey -
1779          */
1780         need_singlethread_pass = DAG_is_acyclic(scene) == false;
1781 #ifdef MBALL_SINGLETHREAD_HACK
1782         need_singlethread_pass |= state.has_mballs;
1783 #endif
1784
1785         if (need_singlethread_pass) {
1786                 scene_update_all_bases(eval_ctx, scene, scene_parent);
1787         }
1788
1789         if (need_free_scheduler) {
1790                 BLI_task_scheduler_free(task_scheduler);
1791         }
1792 }
1793
1794 static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1795 {
1796         scene->customdata_mask = scene_parent->customdata_mask;
1797
1798         /* sets first, we allow per definition current scene to have
1799          * dependencies on sets, but not the other way around. */
1800         if (scene->set)
1801                 scene_update_tagged_recursive(eval_ctx, bmain, scene->set, scene_parent);
1802
1803         /* scene objects */
1804         scene_update_objects(eval_ctx, bmain, scene, scene_parent);
1805
1806         /* scene drivers... */
1807         scene_update_drivers(bmain, scene);
1808
1809         /* update masking curves */
1810         BKE_mask_update_scene(bmain, scene);
1811         
1812 }
1813 #endif  /* WITH_LEGACY_DEPSGRAPH */
1814
1815 static bool check_rendered_viewport_visible(Main *bmain)
1816 {
1817         wmWindowManager *wm = bmain->wm.first;
1818         wmWindow *window;
1819         for (window = wm->windows.first; window != NULL; window = window->next) {
1820                 bScreen *screen = window->screen;
1821                 ScrArea *area;
1822                 for (area = screen->areabase.first; area != NULL; area = area->next) {
1823                         View3D *v3d = area->spacedata.first;
1824                         if (area->spacetype != SPACE_VIEW3D) {
1825                                 continue;
1826                         }
1827                         if (v3d->drawtype == OB_RENDER) {
1828                                 return true;
1829                         }
1830                 }
1831         }
1832         return false;
1833 }
1834
1835 static void prepare_mesh_for_viewport_render(Main *bmain, Scene *scene)
1836 {
1837         /* This is needed to prepare mesh to be used by the render
1838          * engine from the viewport rendering. We do loading here
1839          * so all the objects which shares the same mesh datablock
1840          * are nicely tagged for update and updated.
1841          *
1842          * This makes it so viewport render engine doesn't need to
1843          * call loading of the edit data for the mesh objects.
1844          */
1845
1846         Object *obedit = scene->obedit;
1847         if (obedit) {
1848                 Mesh *mesh = obedit->data;
1849                 if ((obedit->type == OB_MESH) &&
1850                     ((obedit->id.recalc & ID_RECALC_ALL) ||
1851                      (mesh->id.recalc & ID_RECALC_ALL)))
1852                 {
1853                         if (check_rendered_viewport_visible(bmain)) {
1854                                 BMesh *bm = mesh->edit_btmesh->bm;
1855                                 BM_mesh_bm_to_me(
1856                                         bm, mesh,
1857                                         (&(struct BMeshToMeshParams){
1858                                             .calc_object_remap = true,
1859                                         }));
1860                                 DAG_id_tag_update(&mesh->id, 0);
1861                         }
1862                 }
1863         }
1864 }
1865
1866 void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *scene)
1867 {
1868         Scene *sce_iter;
1869 #ifdef WITH_LEGACY_DEPSGRAPH
1870         bool use_new_eval = !DEG_depsgraph_use_legacy();
1871 #endif
1872
1873         /* keep this first */
1874         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1875
1876         /* (re-)build dependency graph if needed */
1877         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set) {
1878                 DAG_scene_relations_update(bmain, sce_iter);
1879                 /* Uncomment this to check if dependency graph was properly tagged for update. */
1880 #if 0
1881 #ifdef WITH_LEGACY_DEPSGRAPH
1882                 if (use_new_eval)
1883 #endif
1884                 {
1885                         DAG_scene_relations_validate(bmain, sce_iter);
1886                 }
1887 #endif
1888         }
1889
1890         /* flush editing data if needed */
1891         prepare_mesh_for_viewport_render(bmain, scene);
1892
1893         /* flush recalc flags to dependencies */
1894         DAG_ids_flush_tagged(bmain);
1895
1896         /* removed calls to quick_cache, see pointcache.c */
1897         
1898         /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later
1899          * when trying to find materials with drivers that need evaluating [#32017] 
1900          */
1901         BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false);
1902         BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false);
1903
1904         /* update all objects: drivers, matrices, displists, etc. flags set
1905          * by depgraph or manual, no layer check here, gets correct flushed
1906          *
1907          * in the future this should handle updates for all datablocks, not
1908          * only objects and scenes. - brecht */
1909 #ifdef WITH_LEGACY_DEPSGRAPH
1910         if (!use_new_eval) {
1911                 scene_update_tagged_recursive(eval_ctx, bmain, scene, scene);
1912         }
1913         else
1914 #endif
1915         {
1916                 DEG_evaluate_on_refresh(eval_ctx, scene->depsgraph, scene);
1917         }
1918
1919         /* update sound system animation (TODO, move to depsgraph) */
1920         BKE_sound_update_scene(bmain, scene);
1921
1922         /* extra call here to recalc scene animation (for sequencer) */
1923         {
1924                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1925                 float ctime = BKE_scene_frame_get(scene);
1926                 
1927                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1928                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1929         }
1930
1931         /* Extra call here to recalc material animation.
1932          *
1933          * Need to do this so changing material settings from the graph/dopesheet
1934          * will update stuff in the viewport.
1935          */
1936 #ifdef WITH_LEGACY_DEPSGRAPH
1937         if (!use_new_eval && DAG_id_type_tagged(bmain, ID_MA)) {
1938                 Material *material;
1939                 float ctime = BKE_scene_frame_get(scene);
1940
1941                 for (material = bmain->mat.first;
1942                      material;
1943                      material = material->id.next)
1944                 {
1945                         AnimData *adt = BKE_animdata_from_id(&material->id);
1946                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1947                                 BKE_animsys_evaluate_animdata(scene, &material->id, adt, ctime, 0);
1948                 }
1949         }
1950
1951         /* Also do the same for node trees. */
1952         if (!use_new_eval && DAG_id_type_tagged(bmain, ID_NT)) {
1953                 float ctime = BKE_scene_frame_get(scene);
1954
1955                 FOREACH_NODETREE(bmain, ntree, id)
1956                 {
1957                         AnimData *adt = BKE_animdata_from_id(&ntree->id);
1958                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1959                                 BKE_animsys_evaluate_animdata(scene, &ntree->id, adt, ctime, 0);
1960                 }
1961                 FOREACH_NODETREE_END
1962         }
1963 #endif
1964
1965         /* notify editors and python about recalc */
1966         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1967
1968         /* Inform editors about possible changes. */
1969         DAG_ids_check_recalc(bmain, scene, false);
1970
1971         /* clear recalc flags */
1972         DAG_ids_clear_recalc(bmain);
1973 }
1974
1975 /* applies changes right away, does all sets too */
1976 void BKE_scene_update_for_newframe(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay)
1977 {
1978         BKE_scene_update_for_newframe_ex(eval_ctx, bmain, sce, lay, false);
1979 }
1980
1981 void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay, bool do_invisible_flush)
1982 {
1983         float ctime = BKE_scene_frame_get(sce);
1984         Scene *sce_iter;
1985 #ifdef DETAILED_ANALYSIS_OUTPUT
1986         double start_time = PIL_check_seconds_timer();
1987 #endif
1988 #ifdef WITH_LEGACY_DEPSGRAPH
1989         bool use_new_eval = !DEG_depsgraph_use_legacy();
1990 #else
1991         /* TODO(sergey): Pass to evaluation routines instead of storing layer in the dependency graph? */
1992         (void) do_invisible_flush;
1993 #endif
1994
1995         DAG_editors_update_pre(bmain, sce, true);
1996
1997         /* keep this first */
1998         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1999         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
2000
2001         /* update animated image textures for particles, modifiers, gpu, etc,
2002          * call this at the start so modifiers with textures don't lag 1 frame */
2003         BKE_image_update_frame(bmain, sce->r.cfra);
2004         
2005 #ifdef WITH_LEGACY_DEPSGRAPH
2006         /* rebuild rigid body worlds before doing the actual frame update
2007          * this needs to be done on start frame but animation playback usually starts one frame later
2008          * we need to do it here to avoid rebuilding the world on every simulation change, which can be very expensive
2009          */
2010         if (!use_new_eval) {
2011                 scene_rebuild_rbw_recursive(sce, ctime);
2012         }
2013 #endif
2014         
2015         BKE_sound_set_cfra(sce->r.cfra);
2016         
2017         /* clear animation overrides */
2018         /* XXX TODO... */
2019
2020         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set)
2021                 DAG_scene_relations_update(bmain, sce_iter);
2022
2023 #ifdef WITH_LEGACY_DEPSGRAPH
2024         if (!use_new_eval) {
2025                 /* flush recalc flags to dependencies, if we were only changing a frame
2026                  * this would not be necessary, but if a user or a script has modified
2027                  * some datablock before BKE_scene_update_tagged was called, we need the flush */
2028                 DAG_ids_flush_tagged(bmain);
2029
2030                 /* Following 2 functions are recursive
2031                  * so don't call within 'scene_update_tagged_recursive' */
2032                 DAG_scene_update_flags(bmain, sce, lay, true, do_invisible_flush);   // only stuff that moves or needs display still
2033                 BKE_mask_evaluate_all_masks(bmain, ctime, true);
2034         }
2035 #endif
2036
2037         /* Update animated cache files for modifiers. */
2038         BKE_cachefile_update_frame(bmain, sce, ctime, (((double)sce->r.frs_sec) / (double)sce->r.frs_sec_base));
2039
2040 #ifdef POSE_ANIMATION_WORKAROUND
2041         scene_armature_depsgraph_workaround(bmain);
2042 #endif
2043
2044         /* All 'standard' (i.e. without any dependencies) animation is handled here,
2045          * with an 'local' to 'macro' order of evaluation. This should ensure that
2046          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
2047          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
2048          * such as Scene->World->MTex/Texture) can still get correctly overridden.
2049          */
2050 #ifdef WITH_LEGACY_DEPSGRAPH
2051         if (!use_new_eval) {
2052                 BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
2053                 /*...done with recursive funcs */
2054         }
2055 #endif
2056
2057         /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later
2058          * when trying to find materials with drivers that need evaluating [#32017] 
2059          */
2060         BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false);
2061         BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false);
2062
2063         /* run rigidbody sim */
2064         /* NOTE: current position is so that rigidbody sim affects other objects, might change in the future */
2065 #ifdef WITH_LEGACY_DEPSGRAPH
2066         if (!use_new_eval) {
2067                 scene_do_rb_simulation_recursive(sce, ctime);
2068         }
2069 #endif
2070         
2071         /* BKE_object_handle_update() on all objects, groups and sets */
2072 #ifdef WITH_LEGACY_DEPSGRAPH
2073         if (use_new_eval) {
2074                 DEG_evaluate_on_framechange(eval_ctx, bmain, sce->depsgraph, ctime, lay);
2075         }
2076         else {
2077                 scene_update_tagged_recursive(eval_ctx, bmain, sce, sce);
2078         }
2079 #else
2080         DEG_evaluate_on_framechange(eval_ctx, bmain, sce->depsgraph, ctime, lay);
2081 #endif
2082
2083         /* update sound system animation (TODO, move to depsgraph) */
2084         BKE_sound_update_scene(bmain, sce);
2085
2086 #ifdef WITH_LEGACY_DEPSGRAPH
2087         if (!use_new_eval) {
2088                 scene_depsgraph_hack(eval_ctx, sce, sce);
2089         }
2090 #endif
2091
2092         /* notify editors and python about recalc */
2093         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
2094         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
2095
2096         /* Inform editors about possible changes. */
2097         DAG_ids_check_recalc(bmain, sce, true);
2098
2099         /* clear recalc flags */
2100         DAG_ids_clear_recalc(bmain);
2101
2102 #ifdef DETAILED_ANALYSIS_OUTPUT
2103         fprintf(stderr, "frame update start_time %f duration %f\n", start_time, PIL_check_seconds_timer() - start_time);
2104 #endif
2105 }
2106
2107 /* return default layer, also used to patch old files */
2108 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
2109 {
2110         SceneRenderLayer *srl;
2111
2112         if (!name)
2113                 name = DATA_("RenderLayer");
2114
2115         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
2116         BLI_strncpy(srl->name, name, sizeof(srl->name));
2117         BLI_uniquename(&sce->r.layers, srl, DATA_("RenderLayer"), '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
2118         BLI_addtail(&sce->r.layers, srl);
2119
2120         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
2121         srl->lay = (1 << 20) - 1;
2122         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
2123         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
2124         srl->pass_alpha_threshold = 0.5f;
2125         BKE_freestyle_config_init(&srl->freestyleConfig);
2126
2127         return srl;
2128 }
2129
2130 bool BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
2131 {
2132         const int act = BLI_findindex(&scene->r.layers, srl);
2133         Scene *sce;
2134
2135         if (act == -1) {
2136                 return false;
2137         }
2138         else if ( (scene->r.layers.first == scene->r.layers.last) &&
2139                   (scene->r.layers.first == srl))
2140         {
2141                 /* ensure 1 layer is kept */
2142                 return false;
2143         }
2144
2145         BKE_freestyle_config_free(&srl->freestyleConfig);
2146
2147         if (srl->prop) {
2148                 IDP_FreeProperty(srl->prop);
2149                 MEM_freeN(srl->prop);
2150         }
2151
2152         BLI_remlink(&scene->r.layers, srl);
2153         MEM_freeN(srl);
2154
2155         scene->r.actlay = 0;
2156
2157         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
2158                 if (sce->nodetree) {
2159                         bNode *node;
2160                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
2161                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
2162                                         if (node->custom1 == act)
2163                                                 node->custom1 = 0;
2164                                         else if (node->custom1 > act)
2165                                                 node->custom1--;
2166                                 }
2167                         }
2168                 }
2169         }
2170
2171         return true;
2172 }
2173
2174 /* return default view */
2175 SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name)
2176 {
2177         SceneRenderView *srv;
2178
2179         if (!name)
2180                 name = DATA_("RenderView");
2181
2182         srv = MEM_callocN(sizeof(SceneRenderView), "new render view");
2183         BLI_strncpy(srv->name, name, sizeof(srv->name));
2184         BLI_uniquename(&sce->r.views, srv, DATA_("RenderView"), '.', offsetof(SceneRenderView, name), sizeof(srv->name));
2185         BLI_addtail(&sce->r.views, srv);
2186
2187         return srv;
2188 }
2189
2190 bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
2191 {
2192         const int act = BLI_findindex(&scene->r.views, srv);
2193
2194         if (act == -1) {
2195                 return false;
2196         }
2197         else if (scene->r.views.first == scene->r.views.last) {
2198                 /* ensure 1 view is kept */
2199                 return false;
2200         }
2201
2202         BLI_remlink(&scene->r.views, srv);
2203         MEM_freeN(srv);
2204
2205         scene->r.actview = 0;
2206
2207         return true;
2208 }
2209
2210 /* render simplification */
2211
2212 int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
2213 {
2214         if (r->mode & R_SIMPLIFY) {
2215                 if (for_render)
2216                         return min_ii(r->simplify_subsurf_render, lvl);
2217                 else
2218                         return min_ii(r->simplify_subsurf, lvl);
2219         }
2220         else {
2221                 return lvl;
2222         }
2223 }
2224
2225 int get_render_child_particle_number(const RenderData *r, int num, bool for_render)
2226 {
2227         if (r->mode & R_SIMPLIFY) {
2228                 if (for_render)
2229                         return (int)(r->simplify_particles_render * num);
2230                 else
2231                         return (int)(r->simplify_particles * num);
2232         }
2233         else {
2234                 return num;
2235         }
2236 }
2237
2238 int get_render_shadow_samples(const RenderData *r, int samples)
2239 {
2240         if ((r->mode & R_SIMPLIFY) && samples > 0)
2241                 return min_ii(r->simplify_shadowsamples, samples);
2242         else
2243                 return samples;
2244 }
2245
2246 float get_render_aosss_error(const RenderData *r, float error)
2247 {
2248         if (r->mode & R_SIMPLIFY)
2249                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
2250         else
2251                 return error;
2252 }
2253
2254 /* helper function for the SETLOOPER macro */
2255 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
2256 {
2257         if (base && base->next) {
2258                 /* common case, step to the next */
2259                 return base->next;
2260         }
2261         else if (base == NULL && (*sce_iter)->base.first) {
2262                 /* first time looping, return the scenes first base */
2263                 return (Base *)(*sce_iter)->base.first;
2264         }
2265         else {
2266                 /* reached the end, get the next base in the set */
2267                 while ((*sce_iter = (*sce_iter)->set)) {
2268                         base = (Base *)(*sce_iter)->base.first;
2269                         if (base) {
2270                                 return base;
2271                         }
2272                 }
2273         }
2274
2275         return NULL;
2276 }
2277
2278 bool BKE_scene_use_new_shading_nodes(const Scene *scene)
2279 {
2280         const RenderEngineType *type = RE_engines_find(scene->r.engine);
2281         return (type && type->flag & RE_USE_SHADING_NODES);
2282 }
2283
2284 bool BKE_scene_use_shading_nodes_custom(Scene *scene)
2285 {
2286         RenderEngineType *type = RE_engines_find(scene->r.engine);
2287         return (type && type->flag & RE_USE_SHADING_NODES_CUSTOM);
2288 }
2289
2290 bool BKE_scene_use_world_space_shading(Scene *scene)
2291 {
2292         const RenderEngineType *type = RE_engines_find(scene->r.engine);
2293         return ((scene->r.mode & R_USE_WS_SHADING) ||
2294                 (type && (type->flag & RE_USE_SHADING_NODES)));
2295 }
2296
2297 bool BKE_scene_use_spherical_stereo(Scene *scene)
2298 {
2299         RenderEngineType *type = RE_engines_find(scene->r.engine);
2300         return (type && type->flag & RE_USE_SPHERICAL_STEREO);
2301 }
2302
2303 bool BKE_scene_uses_blender_internal(const  Scene *scene)
2304 {
2305         return STREQ(scene->r.engine, RE_engine_id_BLENDER_RENDER);
2306 }
2307
2308 bool BKE_scene_uses_blender_game(const Scene *scene)
2309 {
2310         return STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME);
2311 }
2312
2313 void BKE_scene_base_flag_to_objects(struct Scene *scene)
2314 {
2315         Base *base = scene->base.first;
2316
2317         while (base) {
2318                 base->object->flag = base->flag;
2319                 base = base->next;
2320         }
2321 }
2322
2323 void BKE_scene_base_flag_from_objects(struct Scene *scene)
2324 {
2325         Base *base = scene->base.first;
2326
2327         while (base) {
2328                 base->flag = base->object->flag;
2329                 base = base->next;
2330         }
2331 }
2332
2333 void BKE_scene_disable_color_management(Scene *scene)
2334 {
2335         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
2336         ColorManagedViewSettings *view_settings = &scene->view_settings;
2337         const char *view;
2338         const char *none_display_name;
2339
2340         none_display_name = IMB_colormanagement_display_get_none_name();
2341
2342         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
2343
2344         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
2345
2346         if (view) {
2347                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
2348         }
2349 }
2350
2351 bool BKE_scene_check_color_management_enabled(const Scene *scene)
2352 {
2353         return !STREQ(scene->display_settings.display_device, "None");
2354 }
2355
2356 bool BKE_scene_check_rigidbody_active(const Scene *scene)
2357 {
2358         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
2359 }
2360
2361 int BKE_render_num_threads(const RenderData *rd)
2362 {
2363         int threads;
2364
2365         /* override set from command line? */
2366         threads = BLI_system_num_threads_override_get();
2367
2368         if (threads > 0)
2369                 return threads;
2370
2371         /* fixed number of threads specified in scene? */
2372         if (rd->mode & R_FIXED_THREADS)
2373                 threads = rd->threads;
2374         else
2375                 threads = BLI_system_thread_count();
2376         
2377         return max_ii(threads, 1);
2378 }
2379
2380 int BKE_scene_num_threads(const Scene *scene)
2381 {
2382         return BKE_render_num_threads(&scene->r);
2383 }
2384
2385 int BKE_render_preview_pixel_size(const RenderData *r)
2386 {
2387         if (r->preview_pixel_size == 0) {
2388                 return (U.pixelsize > 1.5f) ? 2 : 1;
2389         }
2390         return r->preview_pixel_size;
2391 }
2392
2393 /* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently)
2394  * and unit->scale_length.
2395  */
2396 double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value)
2397 {
2398         if (unit->system == USER_UNIT_NONE) {
2399                 /* Never apply scale_length when not using a unit setting! */
2400                 return value;
2401         }
2402
2403         switch (unit_type) {
2404                 case B_UNIT_LENGTH:
2405                         return value * (double)unit->scale_length;
2406                 case B_UNIT_AREA:
2407                         return value * pow(unit->scale_length, 2);
2408                 case B_UNIT_VOLUME:
2409                         return value * pow(unit->scale_length, 3);
2410                 case B_UNIT_MASS:
2411                         return value * pow(unit->scale_length, 3);
2412                 case B_UNIT_CAMERA:  /* *Do not* use scene's unit scale for camera focal lens! See T42026. */
2413                 default:
2414                         return value;
2415         }
2416 }
2417
2418 /******************** multiview *************************/
2419
2420 int BKE_scene_multiview_num_views_get(const RenderData *rd)
2421 {
2422         SceneRenderView *srv;
2423         int totviews = 0;
2424
2425         if ((rd->scemode & R_MULTIVIEW) == 0)
2426                 return 1;
2427
2428         if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
2429                 srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
2430                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2431                         totviews++;
2432                 }
2433
2434                 srv = BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
2435                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2436                         totviews++;
2437                 }
2438         }
2439         else {
2440                 for (srv = rd->views.first; srv; srv = srv->next) {
2441                         if ((srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2442                                 totviews++;
2443                         }
2444                 }
2445         }
2446         return totviews;
2447 }
2448
2449 bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
2450 {
2451         SceneRenderView *srv[2];
2452
2453         if ((rd->scemode & R_MULTIVIEW) == 0)
2454                 return false;
2455
2456         srv[0] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
2457         srv[1] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
2458
2459         return (srv[0] && ((srv[0]->viewflag & SCE_VIEW_DISABLE) == 0) &&
2460                 srv[1] && ((srv[1]->viewflag & SCE_VIEW_DISABLE) == 0));
2461 }
2462
2463 /* return whether to render this SceneRenderView */
2464 bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
2465 {
2466         if (srv == NULL)
2467                 return false;
2468
2469         if ((rd->scemode & R_MULTIVIEW) == 0)
2470                 return false;
2471
2472         if ((srv->viewflag & SCE_VIEW_DISABLE))
2473                 return false;
2474
2475         if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW)
2476                 return true;
2477
2478         /* SCE_VIEWS_SETUP_BASIC */
2479         if (STREQ(srv->name, STEREO_LEFT_NAME) ||
2480             STREQ(srv->name, STEREO_RIGHT_NAME))
2481         {
2482                 return true;
2483         }
2484
2485         return false;
2486 }
2487
2488 /* return true if viewname is the first or if the name is NULL or not found */
2489 bool BKE_scene_multiview_is_render_view_first(const RenderData *rd, const char *viewname)
2490 {
2491         SceneRenderView *srv;
2492
2493         if ((rd->scemode & R_MULTIVIEW) == 0)
2494                 return true;
2495
2496         if ((!viewname) || (!viewname[0]))
2497                 return true;
2498
2499         for (srv = rd->views.first; srv; srv = srv->next) {
2500                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2501                         return STREQ(viewname, srv->name);
2502                 }
2503         }
2504
2505         return true;
2506 }
2507
2508 /* return true if viewname is the last or if the name is NULL or not found */
2509 bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *viewname)
2510 {
2511         SceneRenderView *srv;
2512
2513         if ((rd->scemode & R_MULTIVIEW) == 0)
2514                 return true;
2515
2516         if ((!viewname) || (!viewname[0]))
2517                 return true;
2518
2519         for (srv = rd->views.last; srv; srv = srv->prev) {
2520                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2521                         return STREQ(viewname, srv->name);
2522                 }
2523         }
2524
2525         return true;
2526 }
2527
2528 SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, const int view_id)
2529 {
2530         SceneRenderView *srv;
2531         size_t nr;
2532
2533         if ((rd->scemode & R_MULTIVIEW) == 0)
2534                 return NULL;
2535
2536         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2537                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2538                         if (nr++ == view_id)
2539                                 return srv;
2540                 }
2541         }
2542         return srv;
2543 }
2544
2545 const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const int view_id)
2546 {
2547         SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id);
2548
2549         if (srv)
2550                 return srv->name;
2551         else
2552                 return "";
2553 }
2554
2555 int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
2556 {
2557         SceneRenderView *srv;
2558         size_t nr;
2559
2560         if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0))
2561                 return 0;
2562
2563         if ((!viewname) || (!viewname[0]))
2564                 return 0;
2565
2566         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2567                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2568                         if (STREQ(viewname, srv->name)) {
2569                                 return nr;
2570                         }
2571                         else {
2572                                 nr += 1;
2573                         }
2574                 }
2575         }
2576
2577         return 0;
2578 }
2579
2580 void BKE_scene_multiview_filepath_get(
2581         SceneRenderView *srv, const char *filepath,
2582         char *r_filepath)
2583 {
2584         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2585         BLI_path_suffix(r_filepath, FILE_MAX, srv->suffix, "");
2586 }
2587
2588 /**
2589  * When multiview is not used the filepath is as usual (e.g., ``Image.jpg``).
2590  * When multiview is on, even if only one view is enabled the view is incorporated
2591  * into the file name (e.g., ``Image_L.jpg``). That allows for the user to re-render
2592  * individual views.
2593  */
2594 void BKE_scene_multiview_view_filepath_get(
2595         const RenderData *rd, const char *filepath, const char *viewname,
2596         char *r_filepath)
2597 {
2598         SceneRenderView *srv;
2599         char suffix[FILE_MAX];
2600
2601         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2602         if (srv)
2603                 BLI_strncpy(suffix, srv->suffix, sizeof(suffix));
2604         else
2605                 BLI_strncpy(suffix, viewname, sizeof(suffix));
2606
2607         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2608         BLI_path_suffix(r_filepath, FILE_MAX, suffix, "");
2609 }
2610
2611 const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char *viewname)
2612 {
2613         SceneRenderView *srv;
2614
2615         if ((viewname == NULL) || (viewname[0] == '\0'))
2616                 return viewname;
2617
2618         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2619         if (srv)
2620                 return srv->suffix;
2621         else
2622                 return viewname;
2623 }
2624
2625 const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id)
2626 {
2627         if ((rd->scemode & R_MULTIVIEW) == 0) {
2628                 return "";
2629         }
2630         else {
2631                 const char *viewname = BKE_scene_multiview_render_view_name_get(rd, view_id);
2632                 return BKE_scene_multiview_view_suffix_get(rd, viewname);
2633         }
2634 }
2635
2636 void BKE_scene_multiview_view_prefix_get(Scene *scene, const char *name, char *rprefix, const char **rext)
2637 {
2638         SceneRenderView *srv;
2639         size_t index_act;
2640         const char *suf_act;
2641         const char delims[] = {'.', '\0'};
2642
2643         rprefix[0] = '\0';
2644
2645         /* begin of extension */
2646         index_act = BLI_str_rpartition(name, delims, rext, &suf_act);
2647         if (*rext == NULL)
2648                 return;
2649         BLI_assert(index_act > 0);
2650         UNUSED_VARS_NDEBUG(index_act);
2651
2652         for (srv = scene->r.views.first; srv; srv = srv->next) {
2653                 if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
2654                         size_t len = strlen(srv->suffix);
2655                         if (strlen(*rext) >= len && STREQLEN(*rext - len, srv->suffix, len)) {
2656                                 BLI_strncpy(rprefix, name, strlen(name) - strlen(*rext) - len + 1);
2657                                 break;
2658                         }
2659                 }
2660         }
2661 }
2662
2663 void BKE_scene_multiview_videos_dimensions_get(
2664         const RenderData *rd, const size_t width, const size_t height,
2665         size_t *r_width, size_t *r_height)
2666 {
2667         if ((rd->scemode & R_MULTIVIEW) &&
2668             rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D)
2669         {
2670                 IMB_stereo3d_write_dimensions(
2671                         rd->im_format.stereo3d_format.display_mode,
2672                         (rd->im_format.stereo3d_format.flag & S3D_SQUEEZED_FRAME) != 0,
2673                         width, height,
2674                         r_width, r_height);
2675         }
2676         else {
2677                 *r_width = width;
2678                 *r_height = height;
2679         }
2680 }
2681
2682 int BKE_scene_multiview_num_videos_get(const RenderData *rd)
2683 {
2684         if (BKE_imtype_is_movie(rd->im_format.imtype) == false)
2685                 return 0;
2686
2687         if ((rd->scemode & R_MULTIVIEW) == 0)
2688                 return 1;
2689
2690         if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2691                 return 1;
2692         }
2693         else {
2694                 /* R_IMF_VIEWS_INDIVIDUAL */
2695                 return BKE_scene_multiview_num_views_get(rd);
2696         }
2697 }