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