Fix compile error in last commit, forgot to include this change.
[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 #ifndef WIN32
38 #  include <unistd.h>
39 #else
40 #  include <io.h>
41 #endif
42
43 #include "MEM_guardedalloc.h"
44
45 #include "DNA_anim_types.h"
46 #include "DNA_group_types.h"
47 #include "DNA_linestyle_types.h"
48 #include "DNA_node_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_rigidbody_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_screen_types.h"
53 #include "DNA_sequence_types.h"
54 #include "DNA_space_types.h"
55
56 #include "BLI_math.h"
57 #include "BLI_blenlib.h"
58 #include "BLI_utildefines.h"
59 #include "BLI_callbacks.h"
60 #include "BLI_string.h"
61 #include "BLI_threads.h"
62 #include "BLI_task.h"
63
64 #include "BLF_translation.h"
65
66 #include "BKE_anim.h"
67 #include "BKE_animsys.h"
68 #include "BKE_action.h"
69 #include "BKE_colortools.h"
70 #include "BKE_depsgraph.h"
71 #include "BKE_fcurve.h"
72 #include "BKE_freestyle.h"
73 #include "BKE_global.h"
74 #include "BKE_group.h"
75 #include "BKE_idprop.h"
76 #include "BKE_image.h"
77 #include "BKE_library.h"
78 #include "BKE_main.h"
79 #include "BKE_mask.h"
80 #include "BKE_node.h"
81 #include "BKE_object.h"
82 #include "BKE_paint.h"
83 #include "BKE_pointcache.h"
84 #include "BKE_rigidbody.h"
85 #include "BKE_scene.h"
86 #include "BKE_sequencer.h"
87 #include "BKE_sound.h"
88 #include "BKE_world.h"
89
90 #include "RE_engine.h"
91
92 #include "PIL_time.h"
93
94 #include "IMB_colormanagement.h"
95
96 //XXX #include "BIF_previewrender.h"
97 //XXX #include "BIF_editseq.h"
98
99 #ifdef WIN32
100 #else
101 #  include <sys/time.h>
102 #endif
103
104 void free_avicodecdata(AviCodecData *acd)
105 {
106         if (acd) {
107                 if (acd->lpFormat) {
108                         MEM_freeN(acd->lpFormat);
109                         acd->lpFormat = NULL;
110                         acd->cbFormat = 0;
111                 }
112                 if (acd->lpParms) {
113                         MEM_freeN(acd->lpParms);
114                         acd->lpParms = NULL;
115                         acd->cbParms = 0;
116                 }
117         }
118 }
119
120 void free_qtcodecdata(QuicktimeCodecData *qcd)
121 {
122         if (qcd) {
123                 if (qcd->cdParms) {
124                         MEM_freeN(qcd->cdParms);
125                         qcd->cdParms = NULL;
126                         qcd->cdSize = 0;
127                 }
128         }
129 }
130
131 static void remove_sequencer_fcurves(Scene *sce)
132 {
133         AnimData *adt = BKE_animdata_from_id(&sce->id);
134
135         if (adt && adt->action) {
136                 FCurve *fcu, *nextfcu;
137                 
138                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
139                         nextfcu = fcu->next;
140                         
141                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
142                                 action_groups_remove_channel(adt->action, fcu);
143                                 free_fcurve(fcu);
144                         }
145                 }
146         }
147 }
148
149 Scene *BKE_scene_copy(Scene *sce, int type)
150 {
151         Scene *scen;
152         SceneRenderLayer *srl, *new_srl;
153         ToolSettings *ts;
154         Base *base, *obase;
155         
156         if (type == SCE_COPY_EMPTY) {
157                 ListBase lb;
158                 /* XXX. main should become an arg */
159                 scen = BKE_scene_add(G.main, sce->id.name + 2);
160                 
161                 lb = scen->r.layers;
162                 scen->r = sce->r;
163                 scen->r.layers = lb;
164                 scen->r.actlay = 0;
165                 scen->unit = sce->unit;
166                 scen->physics_settings = sce->physics_settings;
167                 scen->gm = sce->gm;
168                 scen->audio = sce->audio;
169
170                 if (sce->id.properties)
171                         scen->id.properties = IDP_CopyProperty(sce->id.properties);
172
173                 MEM_freeN(scen->toolsettings);
174         }
175         else {
176                 scen = BKE_libblock_copy(&sce->id);
177                 BLI_duplicatelist(&(scen->base), &(sce->base));
178                 
179                 BKE_main_id_clear_newpoins(G.main);
180                 
181                 id_us_plus((ID *)scen->world);
182                 id_us_plus((ID *)scen->set);
183                 id_us_plus((ID *)scen->gm.dome.warptext);
184
185                 scen->ed = NULL;
186                 scen->theDag = NULL;
187                 scen->obedit = NULL;
188                 scen->stats = NULL;
189                 scen->fps_info = NULL;
190
191                 if (sce->rigidbody_world)
192                         scen->rigidbody_world = BKE_rigidbody_world_copy(sce->rigidbody_world);
193
194                 BLI_duplicatelist(&(scen->markers), &(sce->markers));
195                 BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
196                 BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
197                 BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
198
199                 if (sce->nodetree) {
200                         /* ID's are managed on both copy and switch */
201                         scen->nodetree = ntreeCopyTree(sce->nodetree);
202                         ntreeSwitchID(scen->nodetree, &sce->id, &scen->id);
203                 }
204
205                 obase = sce->base.first;
206                 base = scen->base.first;
207                 while (base) {
208                         id_us_plus(&base->object->id);
209                         if (obase == sce->basact) scen->basact = base;
210         
211                         obase = obase->next;
212                         base = base->next;
213                 }
214
215                 /* copy color management settings */
216                 BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings);
217                 BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings);
218                 BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings);
219
220                 BLI_strncpy(scen->sequencer_colorspace_settings.name, sce->sequencer_colorspace_settings.name,
221                             sizeof(scen->sequencer_colorspace_settings.name));
222
223                 /* copy action and remove animation used by sequencer */
224                 BKE_copy_animdata_id_action(&scen->id);
225
226                 if (type != SCE_COPY_FULL)
227                         remove_sequencer_fcurves(scen);
228
229                 /* copy Freestyle settings */
230                 new_srl = scen->r.layers.first;
231                 for (srl = sce->r.layers.first; srl; srl = srl->next) {
232                         BKE_freestyle_config_copy(&new_srl->freestyleConfig, &srl->freestyleConfig);
233                         new_srl = new_srl->next;
234                 }
235         }
236
237         /* tool settings */
238         scen->toolsettings = MEM_dupallocN(sce->toolsettings);
239
240         ts = scen->toolsettings;
241         if (ts) {
242                 if (ts->vpaint) {
243                         ts->vpaint = MEM_dupallocN(ts->vpaint);
244                         ts->vpaint->paintcursor = NULL;
245                         ts->vpaint->vpaint_prev = NULL;
246                         ts->vpaint->wpaint_prev = NULL;
247                         BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint);
248                 }
249                 if (ts->wpaint) {
250                         ts->wpaint = MEM_dupallocN(ts->wpaint);
251                         ts->wpaint->paintcursor = NULL;
252                         ts->wpaint->vpaint_prev = NULL;
253                         ts->wpaint->wpaint_prev = NULL;
254                         BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint);
255                 }
256                 if (ts->sculpt) {
257                         ts->sculpt = MEM_dupallocN(ts->sculpt);
258                         BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint);
259                 }
260
261                 BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint);
262                 ts->imapaint.paintcursor = NULL;
263                 ts->particle.paintcursor = NULL;
264         }
265         
266         /* make a private copy of the avicodecdata */
267         if (sce->r.avicodecdata) {
268                 scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
269                 scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
270                 scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
271         }
272         
273         /* make a private copy of the qtcodecdata */
274         if (sce->r.qtcodecdata) {
275                 scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
276                 scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
277         }
278         
279         if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
280                 scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
281         }
282
283         /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
284          * are done outside of blenkernel with ED_objects_single_users! */
285
286         /*  camera */
287         if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
288                 ID_NEW(scen->camera);
289         }
290         
291         /* before scene copy */
292         sound_create_scene(scen);
293
294         /* world */
295         if (type == SCE_COPY_FULL) {
296                 if (scen->world) {
297                         id_us_plus((ID *)scen->world);
298                         scen->world = BKE_world_copy(scen->world);
299                         BKE_copy_animdata_id_action((ID *)scen->world);
300                 }
301
302                 if (sce->ed) {
303                         scen->ed = MEM_callocN(sizeof(Editing), "addseq");
304                         scen->ed->seqbasep = &scen->ed->seqbase;
305                         BKE_sequence_base_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL);
306                 }
307         }
308
309         return scen;
310 }
311
312 void BKE_scene_groups_relink(Scene *sce)
313 {
314         if (sce->rigidbody_world)
315                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
316 }
317
318 /* do not free scene itself */
319 void BKE_scene_free(Scene *sce)
320 {
321         Base *base;
322         SceneRenderLayer *srl;
323
324         /* check all sequences */
325         BKE_sequencer_clear_scene_in_allseqs(G.main, sce);
326
327         base = sce->base.first;
328         while (base) {
329                 base->object->id.us--;
330                 base = base->next;
331         }
332         /* do not free objects! */
333         
334         if (sce->gpd) {
335 #if 0   /* removed since this can be invalid memory when freeing everything */
336                 /* since the grease pencil data is freed before the scene.
337                  * since grease pencil data is not (yet?), shared between objects
338                  * its probably safe not to do this, some save and reload will free this. */
339                 sce->gpd->id.us--;
340 #endif
341                 sce->gpd = NULL;
342         }
343
344         BLI_freelistN(&sce->base);
345         BKE_sequencer_editing_free(sce);
346
347         BKE_free_animdata((ID *)sce);
348         BKE_keyingsets_free(&sce->keyingsets);
349         
350         if (sce->rigidbody_world)
351                 BKE_rigidbody_free_world(sce->rigidbody_world);
352         
353         if (sce->r.avicodecdata) {
354                 free_avicodecdata(sce->r.avicodecdata);
355                 MEM_freeN(sce->r.avicodecdata);
356                 sce->r.avicodecdata = NULL;
357         }
358         if (sce->r.qtcodecdata) {
359                 free_qtcodecdata(sce->r.qtcodecdata);
360                 MEM_freeN(sce->r.qtcodecdata);
361                 sce->r.qtcodecdata = NULL;
362         }
363         if (sce->r.ffcodecdata.properties) {
364                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
365                 MEM_freeN(sce->r.ffcodecdata.properties);
366                 sce->r.ffcodecdata.properties = NULL;
367         }
368         
369         for (srl = sce->r.layers.first; srl; srl = srl->next) {
370                 BKE_freestyle_config_free(&srl->freestyleConfig);
371         }
372         
373         BLI_freelistN(&sce->markers);
374         BLI_freelistN(&sce->transform_spaces);
375         BLI_freelistN(&sce->r.layers);
376         
377         if (sce->toolsettings) {
378                 if (sce->toolsettings->vpaint) {
379                         BKE_paint_free(&sce->toolsettings->vpaint->paint);
380                         MEM_freeN(sce->toolsettings->vpaint);
381                 }
382                 if (sce->toolsettings->wpaint) {
383                         BKE_paint_free(&sce->toolsettings->wpaint->paint);
384                         MEM_freeN(sce->toolsettings->wpaint);
385                 }
386                 if (sce->toolsettings->sculpt) {
387                         BKE_paint_free(&sce->toolsettings->sculpt->paint);
388                         MEM_freeN(sce->toolsettings->sculpt);
389                 }
390                 if (sce->toolsettings->uvsculpt) {
391                         BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
392                         MEM_freeN(sce->toolsettings->uvsculpt);
393                 }
394                 BKE_paint_free(&sce->toolsettings->imapaint.paint);
395
396                 MEM_freeN(sce->toolsettings);
397                 sce->toolsettings = NULL;
398         }
399         
400         DAG_scene_free(sce);
401         
402         if (sce->nodetree) {
403                 ntreeFreeTree(sce->nodetree);
404                 MEM_freeN(sce->nodetree);
405         }
406
407         if (sce->stats)
408                 MEM_freeN(sce->stats);
409         if (sce->fps_info)
410                 MEM_freeN(sce->fps_info);
411
412         sound_destroy_scene(sce);
413
414         BKE_color_managed_view_settings_free(&sce->view_settings);
415 }
416
417 Scene *BKE_scene_add(Main *bmain, const char *name)
418 {
419         Scene *sce;
420         ParticleEditSettings *pset;
421         int a;
422         const char *colorspace_name;
423
424         sce = BKE_libblock_alloc(bmain, ID_SCE, name);
425         sce->lay = sce->layact = 1;
426         
427         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
428         sce->r.cfra = 1;
429         sce->r.sfra = 1;
430         sce->r.efra = 250;
431         sce->r.frame_step = 1;
432         sce->r.xsch = 1920;
433         sce->r.ysch = 1080;
434         sce->r.xasp = 1;
435         sce->r.yasp = 1;
436         sce->r.tilex = 256;
437         sce->r.tiley = 256;
438         sce->r.mblur_samples = 1;
439         sce->r.filtertype = R_FILTER_MITCH;
440         sce->r.size = 50;
441
442         sce->r.im_format.planes = R_IMF_PLANES_RGBA;
443         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
444         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
445         sce->r.im_format.quality = 90;
446         sce->r.im_format.compress = 15;
447
448         sce->r.displaymode = R_OUTPUT_AREA;
449         sce->r.framapto = 100;
450         sce->r.images = 100;
451         sce->r.framelen = 1.0;
452         sce->r.blurfac = 0.5;
453         sce->r.frs_sec = 24;
454         sce->r.frs_sec_base = 1;
455         sce->r.edgeint = 10;
456         sce->r.ocres = 128;
457
458         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
459          *            images would look in the same way as in current blender
460          *
461          *            perhaps at some point should be completely deprecated?
462          */
463         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
464
465         sce->r.gauss = 1.0;
466         
467         /* deprecated but keep for upwards compat */
468         sce->r.postgamma = 1.0;
469         sce->r.posthue = 0.0;
470         sce->r.postsat = 1.0;
471
472         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
473         sce->r.bake_filter = 16;
474         sce->r.bake_osa = 5;
475         sce->r.bake_flag = R_BAKE_CLEAR;
476         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
477         sce->r.bake_samples = 256;
478         sce->r.bake_biasdist = 0.001;
479         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
480         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME;
481         sce->r.stamp_font_id = 12;
482         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
483         sce->r.fg_stamp[3] = 1.0f;
484         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
485         sce->r.bg_stamp[3] = 0.25f;
486         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
487
488         sce->r.seq_prev_type = OB_SOLID;
489         sce->r.seq_rend_type = OB_SOLID;
490         sce->r.seq_flag = R_SEQ_GL_PREV;
491
492         sce->r.threads = 1;
493
494         sce->r.simplify_subsurf = 6;
495         sce->r.simplify_particles = 1.0f;
496         sce->r.simplify_shadowsamples = 16;
497         sce->r.simplify_aosss = 1.0f;
498
499         sce->r.border.xmin = 0.0f;
500         sce->r.border.ymin = 0.0f;
501         sce->r.border.xmax = 1.0f;
502         sce->r.border.ymax = 1.0f;
503         
504         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
505         sce->toolsettings->doublimit = 0.001;
506         sce->toolsettings->uvcalc_margin = 0.001f;
507         sce->toolsettings->unwrapper = 1;
508         sce->toolsettings->select_thresh = 0.01f;
509
510         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
511         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
512         sce->toolsettings->normalsize = 0.1;
513         sce->toolsettings->autokey_mode = U.autokey_mode;
514
515         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
516
517         sce->toolsettings->skgen_resolution = 100;
518         sce->toolsettings->skgen_threshold_internal     = 0.01f;
519         sce->toolsettings->skgen_threshold_external     = 0.01f;
520         sce->toolsettings->skgen_angle_limit            = 45.0f;
521         sce->toolsettings->skgen_length_ratio           = 1.3f;
522         sce->toolsettings->skgen_length_limit           = 1.5f;
523         sce->toolsettings->skgen_correlation_limit      = 0.98f;
524         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
525         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
526         sce->toolsettings->skgen_postpro_passes = 1;
527         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
528         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
529         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
530         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
531
532         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
533         sce->toolsettings->statvis.overhang_min = 0;
534         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
535         sce->toolsettings->statvis.thickness_max = 0.1f;
536         sce->toolsettings->statvis.thickness_samples = 1;
537         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
538         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
539
540         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
541         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
542
543         sce->toolsettings->proportional_size = 1.0f;
544
545         sce->physics_settings.gravity[0] = 0.0f;
546         sce->physics_settings.gravity[1] = 0.0f;
547         sce->physics_settings.gravity[2] = -9.81f;
548         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
549
550         sce->unit.scale_length = 1.0f;
551
552         pset = &sce->toolsettings->particle;
553         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
554         pset->emitterdist = 0.25f;
555         pset->totrekey = 5;
556         pset->totaddkey = 5;
557         pset->brushtype = PE_BRUSH_NONE;
558         pset->draw_step = 2;
559         pset->fade_frames = 2;
560         pset->selectmode = SCE_SELECT_PATH;
561         for (a = 0; a < PE_TOT_BRUSH; a++) {
562                 pset->brush[a].strength = 0.5;
563                 pset->brush[a].size = 50;
564                 pset->brush[a].step = 10;
565                 pset->brush[a].count = 10;
566         }
567         pset->brush[PE_BRUSH_CUT].strength = 100;
568
569         sce->r.ffcodecdata.audio_mixrate = 44100;
570         sce->r.ffcodecdata.audio_volume = 1.0f;
571         sce->r.ffcodecdata.audio_bitrate = 192;
572         sce->r.ffcodecdata.audio_channels = 2;
573
574         BLI_strncpy(sce->r.engine, "BLENDER_RENDER", sizeof(sce->r.engine));
575
576         sce->audio.distance_model = 2.0f;
577         sce->audio.doppler_factor = 1.0f;
578         sce->audio.speed_of_sound = 343.3f;
579         sce->audio.volume = 1.0f;
580
581         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
582
583         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
584         sce->r.osa = 8;
585
586         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
587         BKE_scene_add_render_layer(sce, NULL);
588         
589         /* game data */
590         sce->gm.stereoflag = STEREO_NOSTEREO;
591         sce->gm.stereomode = STEREO_ANAGLYPH;
592         sce->gm.eyeseparation = 0.10;
593
594         sce->gm.dome.angle = 180;
595         sce->gm.dome.mode = DOME_FISHEYE;
596         sce->gm.dome.res = 4;
597         sce->gm.dome.resbuf = 1.0f;
598         sce->gm.dome.tilt = 0;
599
600         sce->gm.xplay = 640;
601         sce->gm.yplay = 480;
602         sce->gm.freqplay = 60;
603         sce->gm.depth = 32;
604
605         sce->gm.gravity = 9.8f;
606         sce->gm.physicsEngine = WOPHY_BULLET;
607         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
608         sce->gm.occlusionRes = 128;
609         sce->gm.ticrate = 60;
610         sce->gm.maxlogicstep = 5;
611         sce->gm.physubstep = 1;
612         sce->gm.maxphystep = 5;
613         sce->gm.lineardeactthreshold = 0.8f;
614         sce->gm.angulardeactthreshold = 1.0f;
615         sce->gm.deactivationtime = 0.0f;
616
617         sce->gm.flag = GAME_DISPLAY_LISTS;
618         sce->gm.matmode = GAME_MAT_MULTITEX;
619
620         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
621         sce->gm.levelHeight = 2.f;
622
623         sce->gm.recastData.cellsize = 0.3f;
624         sce->gm.recastData.cellheight = 0.2f;
625         sce->gm.recastData.agentmaxslope = M_PI / 2;
626         sce->gm.recastData.agentmaxclimb = 0.9f;
627         sce->gm.recastData.agentheight = 2.0f;
628         sce->gm.recastData.agentradius = 0.6f;
629         sce->gm.recastData.edgemaxlen = 12.0f;
630         sce->gm.recastData.edgemaxerror = 1.3f;
631         sce->gm.recastData.regionminsize = 8.f;
632         sce->gm.recastData.regionmergesize = 20.f;
633         sce->gm.recastData.vertsperpoly = 6;
634         sce->gm.recastData.detailsampledist = 6.0f;
635         sce->gm.recastData.detailsamplemaxerror = 1.0f;
636
637         sce->gm.exitkey = 218; // Blender key code for ESC
638
639         sound_create_scene(sce);
640
641         /* color management */
642         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
643
644         BKE_color_managed_display_settings_init(&sce->display_settings);
645         BKE_color_managed_view_settings_init(&sce->view_settings);
646         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
647                     sizeof(sce->sequencer_colorspace_settings.name));
648
649         return sce;
650 }
651
652 Base *BKE_scene_base_find(Scene *scene, Object *ob)
653 {
654         return BLI_findptr(&scene->base, ob, offsetof(Base, object));
655 }
656
657 void BKE_scene_set_background(Main *bmain, Scene *scene)
658 {
659         Scene *sce;
660         Base *base;
661         Object *ob;
662         Group *group;
663         GroupObject *go;
664         int flag;
665         
666         /* check for cyclic sets, for reading old files but also for definite security (py?) */
667         BKE_scene_validate_setscene(bmain, scene);
668         
669         /* can happen when switching modes in other scenes */
670         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
671                 scene->obedit = NULL;
672
673         /* deselect objects (for dataselect) */
674         for (ob = bmain->object.first; ob; ob = ob->id.next)
675                 ob->flag &= ~(SELECT | OB_FROMGROUP);
676
677         /* group flags again */
678         for (group = bmain->group.first; group; group = group->id.next) {
679                 for (go = group->gobject.first; go; go = go->next) {
680                         if (go->ob) {
681                                 go->ob->flag |= OB_FROMGROUP;
682                         }
683                 }
684         }
685
686         /* sort baselist for scene and sets */
687         for (sce = scene; sce; sce = sce->set)
688                 DAG_scene_relations_rebuild(bmain, sce);
689
690         /* copy layers and flags from bases to objects */
691         for (base = scene->base.first; base; base = base->next) {
692                 ob = base->object;
693                 ob->lay = base->lay;
694                 
695                 /* group patch... */
696                 base->flag &= ~(OB_FROMGROUP);
697                 flag = ob->flag & (OB_FROMGROUP);
698                 base->flag |= flag;
699                 
700                 /* not too nice... for recovering objects with lost data */
701                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
702                 ob->flag = base->flag;
703         }
704         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
705 }
706
707 /* called from creator.c */
708 Scene *BKE_scene_set_name(Main *bmain, const char *name)
709 {
710         Scene *sce = (Scene *)BKE_libblock_find_name(ID_SCE, name);
711         if (sce) {
712                 BKE_scene_set_background(bmain, sce);
713                 printf("Scene switch: '%s' in file: '%s'\n", name, G.main->name);
714                 return sce;
715         }
716
717         printf("Can't find scene: '%s' in file: '%s'\n", name, G.main->name);
718         return NULL;
719 }
720
721 static void scene_unlink_space_node(SpaceNode *snode, Scene *sce)
722 {
723         if (snode->id == &sce->id) {
724                 /* nasty DNA logic for SpaceNode:
725                  * ideally should be handled by editor code, but would be bad level call
726                  */
727                 bNodeTreePath *path, *path_next;
728                 for (path = snode->treepath.first; path; path = path_next) {
729                         path_next = path->next;
730                         MEM_freeN(path);
731                 }
732                 snode->treepath.first = snode->treepath.last = NULL;
733                 
734                 snode->id = NULL;
735                 snode->from = NULL;
736                 snode->nodetree = NULL;
737                 snode->edittree = NULL;
738         }
739 }
740
741 void BKE_scene_unlink(Main *bmain, Scene *sce, Scene *newsce)
742 {
743         Scene *sce1;
744         bScreen *screen;
745
746         /* check all sets */
747         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next)
748                 if (sce1->set == sce)
749                         sce1->set = NULL;
750         
751         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next) {
752                 bNode *node;
753                 
754                 if (sce1 == sce || !sce1->nodetree)
755                         continue;
756                 
757                 for (node = sce1->nodetree->nodes.first; node; node = node->next) {
758                         if (node->id == &sce->id)
759                                 node->id = NULL;
760                 }
761         }
762         
763         /* all screens */
764         for (screen = bmain->screen.first; screen; screen = screen->id.next) {
765                 ScrArea *area;
766                 
767                 if (screen->scene == sce)
768                         screen->scene = newsce;
769                 
770                 for (area = screen->areabase.first; area; area = area->next) {
771                         SpaceLink *space_link;
772                         for (space_link = area->spacedata.first; space_link; space_link = space_link->next) {
773                                 if (space_link->spacetype == SPACE_NODE)
774                                         scene_unlink_space_node((SpaceNode *)space_link, sce);
775                         }
776                 }
777         }
778
779         BKE_libblock_free(bmain, sce);
780 }
781
782 /* used by metaballs
783  * doesn't return the original duplicated object, only dupli's
784  */
785 int BKE_scene_base_iter_next(EvaluationContext *eval_ctx, SceneBaseIter *iter,
786                              Scene **scene, int val, Base **base, Object **ob)
787 {
788         bool run_again = true;
789         
790         /* init */
791         if (val == 0) {
792                 iter->phase = F_START;
793                 iter->dupob = NULL;
794                 iter->duplilist = NULL;
795         }
796         else {
797                 /* run_again is set when a duplilist has been ended */
798                 while (run_again) {
799                         run_again = 0;
800
801                         /* the first base */
802                         if (iter->phase == F_START) {
803                                 *base = (*scene)->base.first;
804                                 if (*base) {
805                                         *ob = (*base)->object;
806                                         iter->phase = F_SCENE;
807                                 }
808                                 else {
809                                         /* exception: empty scene */
810                                         while ((*scene)->set) {
811                                                 (*scene) = (*scene)->set;
812                                                 if ((*scene)->base.first) {
813                                                         *base = (*scene)->base.first;
814                                                         *ob = (*base)->object;
815                                                         iter->phase = F_SCENE;
816                                                         break;
817                                                 }
818                                         }
819                                 }
820                         }
821                         else {
822                                 if (*base && iter->phase != F_DUPLI) {
823                                         *base = (*base)->next;
824                                         if (*base) {
825                                                 *ob = (*base)->object;
826                                         }
827                                         else {
828                                                 if (iter->phase == F_SCENE) {
829                                                         /* (*scene) is finished, now do the set */
830                                                         while ((*scene)->set) {
831                                                                 (*scene) = (*scene)->set;
832                                                                 if ((*scene)->base.first) {
833                                                                         *base = (*scene)->base.first;
834                                                                         *ob = (*base)->object;
835                                                                         break;
836                                                                 }
837                                                         }
838                                                 }
839                                         }
840                                 }
841                         }
842                         
843                         if (*base == NULL) {
844                                 iter->phase = F_START;
845                         }
846                         else {
847                                 if (iter->phase != F_DUPLI) {
848                                         if ( (*base)->object->transflag & OB_DUPLI) {
849                                                 /* groups cannot be duplicated for mballs yet, 
850                                                  * this enters eternal loop because of 
851                                                  * makeDispListMBall getting called inside of group_duplilist */
852                                                 if ((*base)->object->dup_group == NULL) {
853                                                         iter->duplilist = object_duplilist_ex(eval_ctx, (*scene), (*base)->object, false);
854                                                         
855                                                         iter->dupob = iter->duplilist->first;
856
857                                                         if (!iter->dupob)
858                                                                 free_object_duplilist(iter->duplilist);
859                                                 }
860                                         }
861                                 }
862                                 /* handle dupli's */
863                                 if (iter->dupob) {
864                                         
865                                         copy_m4_m4(iter->omat, iter->dupob->ob->obmat);
866                                         copy_m4_m4(iter->dupob->ob->obmat, iter->dupob->mat);
867                                         
868                                         (*base)->flag |= OB_FROMDUPLI;
869                                         *ob = iter->dupob->ob;
870                                         iter->phase = F_DUPLI;
871                                         
872                                         iter->dupob = iter->dupob->next;
873                                 }
874                                 else if (iter->phase == F_DUPLI) {
875                                         iter->phase = F_SCENE;
876                                         (*base)->flag &= ~OB_FROMDUPLI;
877                                         
878                                         for (iter->dupob = iter->duplilist->first; iter->dupob; iter->dupob = iter->dupob->next) {
879                                                 copy_m4_m4(iter->dupob->ob->obmat, iter->omat);
880                                         }
881                                         
882                                         free_object_duplilist(iter->duplilist);
883                                         iter->duplilist = NULL;
884                                         run_again = 1;
885                                 }
886                         }
887                 }
888         }
889
890 #if 0
891         if (ob && *ob) {
892                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
893         }
894 #endif
895
896         return iter->phase;
897 }
898
899 Object *BKE_scene_camera_find(Scene *sc)
900 {
901         Base *base;
902         
903         for (base = sc->base.first; base; base = base->next)
904                 if (base->object->type == OB_CAMERA)
905                         return base->object;
906
907         return NULL;
908 }
909
910 #ifdef DURIAN_CAMERA_SWITCH
911 Object *BKE_scene_camera_switch_find(Scene *scene)
912 {
913         TimeMarker *m;
914         int cfra = scene->r.cfra;
915         int frame = -(MAXFRAME + 1);
916         int min_frame = MAXFRAME + 1;
917         Object *camera = NULL;
918         Object *first_camera = NULL;
919
920         for (m = scene->markers.first; m; m = m->next) {
921                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
922                         if ((m->frame <= cfra) && (m->frame > frame)) {
923                                 camera = m->camera;
924                                 frame = m->frame;
925
926                                 if (frame == cfra)
927                                         break;
928                         }
929
930                         if (m->frame < min_frame) {
931                                 first_camera = m->camera;
932                                 min_frame = m->frame;
933                         }
934                 }
935         }
936
937         if (camera == NULL) {
938                 /* If there's no marker to the left of current frame,
939                  * use camera from left-most marker to solve all sort
940                  * of Schrodinger uncertainties.
941                  */
942                 return first_camera;
943         }
944
945         return camera;
946 }
947 #endif
948
949 int BKE_scene_camera_switch_update(Scene *scene)
950 {
951 #ifdef DURIAN_CAMERA_SWITCH
952         Object *camera = BKE_scene_camera_switch_find(scene);
953         if (camera) {
954                 scene->camera = camera;
955                 return 1;
956         }
957 #else
958         (void)scene;
959 #endif
960         return 0;
961 }
962
963 char *BKE_scene_find_marker_name(Scene *scene, int frame)
964 {
965         ListBase *markers = &scene->markers;
966         TimeMarker *m1, *m2;
967
968         /* search through markers for match */
969         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
970                 if (m1->frame == frame)
971                         return m1->name;
972
973                 if (m1 == m2)
974                         break;
975
976                 if (m2->frame == frame)
977                         return m2->name;
978         }
979
980         return NULL;
981 }
982
983 /* return the current marker for this frame,
984  * we can have more than 1 marker per frame, this just returns the first :/ */
985 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
986 {
987         TimeMarker *marker, *best_marker = NULL;
988         int best_frame = -MAXFRAME * 2;
989         for (marker = scene->markers.first; marker; marker = marker->next) {
990                 if (marker->frame == frame) {
991                         return marker->name;
992                 }
993
994                 if (marker->frame > best_frame && marker->frame < frame) {
995                         best_marker = marker;
996                         best_frame = marker->frame;
997                 }
998         }
999
1000         return best_marker ? best_marker->name : NULL;
1001 }
1002
1003
1004 Base *BKE_scene_base_add(Scene *sce, Object *ob)
1005 {
1006         Base *b = MEM_callocN(sizeof(*b), "BKE_scene_base_add");
1007         BLI_addhead(&sce->base, b);
1008
1009         b->object = ob;
1010         b->flag = ob->flag;
1011         b->lay = ob->lay;
1012
1013         return b;
1014 }
1015
1016 void BKE_scene_base_unlink(Scene *sce, Base *base)
1017 {
1018         /* remove rigid body constraint from world before removing object */
1019         if (base->object->rigidbody_constraint)
1020                 BKE_rigidbody_remove_constraint(sce, base->object);
1021         /* remove rigid body object from world before removing object */
1022         if (base->object->rigidbody_object)
1023                 BKE_rigidbody_remove_object(sce, base->object);
1024         
1025         BLI_remlink(&sce->base, base);
1026 }
1027
1028 void BKE_scene_base_deselect_all(Scene *sce)
1029 {
1030         Base *b;
1031
1032         for (b = sce->base.first; b; b = b->next) {
1033                 b->flag &= ~SELECT;
1034                 b->object->flag = b->flag;
1035         }
1036 }
1037
1038 void BKE_scene_base_select(Scene *sce, Base *selbase)
1039 {
1040         selbase->flag |= SELECT;
1041         selbase->object->flag = selbase->flag;
1042
1043         sce->basact = selbase;
1044 }
1045
1046 /* checks for cycle, returns 1 if it's all OK */
1047 int BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1048 {
1049         Scene *scene;
1050         int a, totscene;
1051         
1052         if (sce->set == NULL) return 1;
1053         
1054         totscene = 0;
1055         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1056                 totscene++;
1057         
1058         for (a = 0, scene = sce; scene->set; scene = scene->set, a++) {
1059                 /* more iterations than scenes means we have a cycle */
1060                 if (a > totscene) {
1061                         /* the tested scene gets zero'ed, that's typically current scene */
1062                         sce->set = NULL;
1063                         return 0;
1064                 }
1065         }
1066
1067         return 1;
1068 }
1069
1070 /* This function is needed to cope with fractional frames - including two Blender rendering features
1071  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1072  */
1073 float BKE_scene_frame_get(Scene *scene)
1074 {
1075         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1076 }
1077
1078 /* This function is used to obtain arbitrary fractional frames */
1079 float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame)
1080 {
1081         float ctime = frame;
1082         ctime += scene->r.subframe;
1083         ctime *= scene->r.framelen;
1084         
1085         return ctime;
1086 }
1087
1088 /**
1089  * Sets the frame int/float components.
1090  */
1091 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1092 {
1093         double intpart;
1094         scene->r.subframe = modf(cfra, &intpart);
1095         scene->r.cfra = (int)intpart;
1096
1097         if (cfra < 0.0) {
1098                 scene->r.cfra -= 1;
1099                 scene->r.subframe = 1.0f + scene->r.subframe;
1100         }
1101 }
1102
1103 /* drivers support/hacks 
1104  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
1105  *      - these are always run since the depsgraph can't handle non-object data
1106  *      - these happen after objects are all done so that we can read in their final transform values,
1107  *        though this means that objects can't refer to scene info for guidance...
1108  */
1109 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
1110 {
1111         SceneRenderLayer *srl;
1112         float ctime = BKE_scene_frame_get(scene);
1113         
1114         /* scene itself */
1115         if (scene->adt && scene->adt->drivers.first) {
1116                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
1117         }
1118
1119         /* world */
1120         /* TODO: what about world textures? but then those have nodes too... */
1121         if (scene->world) {
1122                 ID *wid = (ID *)scene->world;
1123                 AnimData *adt = BKE_animdata_from_id(wid);
1124                 
1125                 if (adt && adt->drivers.first)
1126                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
1127         }
1128         
1129         /* nodes */
1130         if (scene->nodetree) {
1131                 ID *nid = (ID *)scene->nodetree;
1132                 AnimData *adt = BKE_animdata_from_id(nid);
1133                 
1134                 if (adt && adt->drivers.first)
1135                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1136         }
1137
1138         /* world nodes */
1139         if (scene->world && scene->world->nodetree) {
1140                 ID *nid = (ID *)scene->world->nodetree;
1141                 AnimData *adt = BKE_animdata_from_id(nid);
1142                 
1143                 if (adt && adt->drivers.first)
1144                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1145         }
1146
1147         /* freestyle */
1148         for (srl = scene->r.layers.first; srl; srl = srl->next) {
1149                 FreestyleConfig *config = &srl->freestyleConfig;
1150                 FreestyleLineSet *lineset;
1151
1152                 for (lineset = config->linesets.first; lineset; lineset = lineset->next) {
1153                         if (lineset->linestyle) {
1154                                 ID *lid = &lineset->linestyle->id;
1155                                 AnimData *adt = BKE_animdata_from_id(lid);
1156
1157                                 if (adt && adt->drivers.first)
1158                                         BKE_animsys_evaluate_animdata(scene, lid, adt, ctime, ADT_RECALC_DRIVERS);
1159                         }
1160                 }
1161         }
1162 }
1163
1164 /* deps hack - do extra recalcs at end */
1165 static void scene_depsgraph_hack(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1166 {
1167         Base *base;
1168                 
1169         scene->customdata_mask = scene_parent->customdata_mask;
1170         
1171         /* sets first, we allow per definition current scene to have
1172          * dependencies on sets, but not the other way around. */
1173         if (scene->set)
1174                 scene_depsgraph_hack(eval_ctx, scene->set, scene_parent);
1175         
1176         for (base = scene->base.first; base; base = base->next) {
1177                 Object *ob = base->object;
1178                 
1179                 if (ob->depsflag) {
1180                         int recalc = 0;
1181                         // printf("depshack %s\n", ob->id.name + 2);
1182                         
1183                         if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC)
1184                                 recalc |= OB_RECALC_OB;
1185                         if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC)
1186                                 recalc |= OB_RECALC_DATA;
1187                         
1188                         ob->recalc |= recalc;
1189                         BKE_object_handle_update(eval_ctx, scene_parent, ob);
1190                         
1191                         if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1192                                 GroupObject *go;
1193                                 
1194                                 for (go = ob->dup_group->gobject.first; go; go = go->next) {
1195                                         if (go->ob)
1196                                                 go->ob->recalc |= recalc;
1197                                 }
1198                                 BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, ob, ob->dup_group);
1199                         }
1200                 }
1201         }
1202
1203 }
1204
1205 static void scene_rebuild_rbw_recursive(Scene *scene, float ctime)
1206 {
1207         if (scene->set)
1208                 scene_rebuild_rbw_recursive(scene->set, ctime);
1209
1210         if (BKE_scene_check_rigidbody_active(scene))
1211                 BKE_rigidbody_rebuild_world(scene, ctime);
1212 }
1213
1214 static void scene_do_rb_simulation_recursive(Scene *scene, float ctime)
1215 {
1216         if (scene->set)
1217                 scene_do_rb_simulation_recursive(scene->set, ctime);
1218
1219         if (BKE_scene_check_rigidbody_active(scene))
1220                 BKE_rigidbody_do_simulation(scene, ctime);
1221 }
1222
1223 /* Used to visualize CPU threads activity during threaded object update,
1224  * would pollute STDERR with whole bunch of timing information which then
1225  * could be parsed and nicely visualized.
1226  */
1227 #undef DETAILED_ANALYSIS_OUTPUT
1228
1229 /* Mballs evaluation uses BKE_scene_base_iter_next which calls
1230  * duplilist for all objects in the scene. This leads to conflict
1231  * accessing and writing same data from multiple threads.
1232  *
1233  * Ideally Mballs shouldn't do such an iteration and use DAG
1234  * queries instead. For the time being we've got new DAG
1235  * let's keep it simple and update mballs in a ingle thread.
1236  */
1237 #define MBALL_SINGLETHREAD_HACK
1238
1239 typedef struct StatisicsEntry {
1240         struct StatisicsEntry *next, *prev;
1241         Object *object;
1242         double start_time;
1243         double duration;
1244 } StatisicsEntry;
1245
1246 typedef struct ThreadedObjectUpdateState {
1247         /* TODO(sergey): We might want this to be per-thread object. */
1248         EvaluationContext *eval_ctx;
1249         Scene *scene;
1250         Scene *scene_parent;
1251         double base_time;
1252
1253         /* Execution statistics */
1254         ListBase statistics[BLENDER_MAX_THREADS];
1255         bool has_updated_objects;
1256
1257 #ifdef MBALL_SINGLETHREAD_HACK
1258         bool has_mballs;
1259 #endif
1260 } ThreadedObjectUpdateState;
1261
1262 static void scene_update_object_add_task(void *node, void *user_data);
1263
1264 static void scene_update_all_bases(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1265 {
1266         Base *base;
1267
1268         for (base = scene->base.first; base; base = base->next) {
1269                 Object *object = base->object;
1270
1271                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world);
1272
1273                 if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1274                         BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, object, object->dup_group);
1275
1276                 /* always update layer, so that animating layers works (joshua july 2010) */
1277                 /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes
1278                  * (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */
1279                 // base->lay = ob->lay;
1280         }
1281 }
1282
1283 static void scene_update_object_func(TaskPool *pool, void *taskdata, int threadid)
1284 {
1285 /* Disable print for now in favor of summary statistics at the end of update. */
1286 #define PRINT if (false) printf
1287
1288         ThreadedObjectUpdateState *state = (ThreadedObjectUpdateState *) BLI_task_pool_userdata(pool);
1289         void *node = taskdata;
1290         Object *object = DAG_get_node_object(node);
1291         EvaluationContext *eval_ctx = state->eval_ctx;
1292         Scene *scene = state->scene;
1293         Scene *scene_parent = state->scene_parent;
1294
1295 #ifdef MBALL_SINGLETHREAD_HACK
1296         if (object && object->type == OB_MBALL) {
1297                 state->has_mballs = true;
1298         }
1299         else
1300 #endif
1301         if (object) {
1302                 double start_time = 0.0;
1303                 bool add_to_stats = false;
1304
1305                 PRINT("Thread %d: update object %s\n", threadid, object->id.name);
1306
1307                 if (G.debug & G_DEBUG_DEPSGRAPH) {
1308                         start_time = PIL_check_seconds_timer();
1309
1310                         if (object->recalc & OB_RECALC_ALL) {
1311                                 state->has_updated_objects = true;
1312                                 add_to_stats = true;
1313                         }
1314                 }
1315
1316                 /* We only update object itself here, dupli-group will be updated
1317                  * separately from main thread because of we've got no idea about
1318                  * dependencies inside the group.
1319                  */
1320                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world);
1321
1322                 /* Calculate statistics. */
1323                 if (add_to_stats) {
1324                         StatisicsEntry *entry;
1325
1326                         entry = MEM_mallocN(sizeof(StatisicsEntry), "update thread statistics");
1327                         entry->object = object;
1328                         entry->start_time = start_time;
1329                         entry->duration = PIL_check_seconds_timer() - start_time;
1330
1331                         BLI_addtail(&state->statistics[threadid], entry);
1332                 }
1333         }
1334         else {
1335                 PRINT("Threda %d: update node %s\n", threadid,
1336                       DAG_get_node_name(node));
1337         }
1338
1339         /* Update will decrease child's valency and schedule child with zero valency. */
1340         DAG_threaded_update_handle_node_updated(node, scene_update_object_add_task, pool);
1341
1342 #undef PRINT
1343 }
1344
1345 static void scene_update_object_add_task(void *node, void *user_data)
1346 {
1347         TaskPool *task_pool = user_data;
1348
1349         BLI_task_pool_push(task_pool, scene_update_object_func, node, false, TASK_PRIORITY_LOW);
1350 }
1351
1352 static void print_threads_statistics(ThreadedObjectUpdateState *state)
1353 {
1354         int i, tot_thread;
1355
1356         if ((G.debug & G_DEBUG_DEPSGRAPH) == 0) {
1357                 return;
1358         }
1359
1360 #ifdef DETAILED_ANALYSIS_OUTPUT
1361         if (state->has_updated_objects) {
1362                 tot_thread = BLI_system_thread_count();
1363
1364                 fprintf(stderr, "objects update base time %f\n", state->base_time);
1365
1366                 for (i = 0; i < tot_thread; i++) {
1367                         StatisicsEntry *entry;
1368                         for (entry = state->statistics[i].first;
1369                              entry;
1370                              entry = entry->next)
1371                         {
1372                                 fprintf(stderr, "thread %d object %s start_time %f duration %f\n",
1373                                         i, entry->object->id.name + 2,
1374                                         entry->start_time, entry->duration);
1375                         }
1376                         BLI_freelistN(&state->statistics[i]);
1377                 }
1378         }
1379 #else
1380         tot_thread = BLI_system_thread_count();
1381
1382         for (i = 0; i < tot_thread; i++) {
1383                 int total_objects = 0;
1384                 double total_time = 0.0;
1385                 StatisicsEntry *entry;
1386
1387                 if (state->has_updated_objects) {
1388                         /* Don't pollute output if no objects were updated. */
1389                         for (entry = state->statistics[i].first;
1390                              entry;
1391                              entry = entry->next)
1392                         {
1393                                 total_objects++;
1394                                 total_time += entry->duration;
1395                         }
1396
1397                         printf("Thread %d: total %d objects in %f sec.\n", i, total_objects, total_time);
1398
1399                         for (entry = state->statistics[i].first;
1400                              entry;
1401                              entry = entry->next)
1402                         {
1403                                 printf("  %s in %f sec\n", entry->object->id.name + 2, entry->duration);
1404                         }
1405                 }
1406
1407                 BLI_freelistN(&state->statistics[i]);
1408         }
1409 #endif
1410 }
1411
1412 static bool scene_need_update_objects(Main *bmain)
1413 {
1414         return
1415                 /* Object datablocks themselves (for OB_RECALC_OB) */
1416                 DAG_id_type_tagged(bmain, ID_OB) ||
1417
1418                 /* Objects data datablocks (for OB_RECALC_DATA) */
1419                 DAG_id_type_tagged(bmain, ID_ME)  ||  /* Mesh */
1420                 DAG_id_type_tagged(bmain, ID_CU)  ||  /* Curve */
1421                 DAG_id_type_tagged(bmain, ID_MB)  ||  /* MetaBall */
1422                 DAG_id_type_tagged(bmain, ID_LA)  ||  /* Lamp */
1423                 DAG_id_type_tagged(bmain, ID_LT)  ||  /* Lattice */
1424                 DAG_id_type_tagged(bmain, ID_CA)  ||  /* Camera */
1425                 DAG_id_type_tagged(bmain, ID_KE)  ||  /* KE */
1426                 DAG_id_type_tagged(bmain, ID_SPK) ||  /* Speaker */
1427                 DAG_id_type_tagged(bmain, ID_AR);     /* Armature */
1428 }
1429
1430 static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1431 {
1432         TaskScheduler *task_scheduler = BLI_task_scheduler_get();
1433         TaskPool *task_pool;
1434         ThreadedObjectUpdateState state;
1435         bool need_singlethread_pass;
1436
1437         /* Early check for whether we need to invoke all the task-based
1438          * tihngs (spawn new ppol, traverse dependency graph and so on).
1439          *
1440          * Basically if there's no ID datablocks tagged for update which
1441          * corresponds to object->recalc flags (which are checked in
1442          * BKE_object_handle_update() then we do nothing here.
1443          */
1444         if (!scene_need_update_objects(bmain)) {
1445                 /* For debug builds we check whether early return didn't give
1446                  * us any regressions in terms of missing updates.
1447                  *
1448                  * TODO(sergey): Remove once we're sure the check above is correct.
1449                  */
1450 #ifndef NDEBUG
1451                 Base *base;
1452
1453                 for (base = scene->base.first; base; base = base->next) {
1454                         Object *object = base->object;
1455
1456                         BLI_assert((object->recalc & OB_RECALC_ALL) == 0);
1457
1458                         if (object->proxy) {
1459                                 BLI_assert((object->proxy->recalc & OB_RECALC_ALL) == 0);
1460                         }
1461
1462                         if (object->dup_group && (object->transflag & OB_DUPLIGROUP)) {
1463                                 GroupObject *go;
1464                                 for (go = object->dup_group->gobject.first; go; go = go->next) {
1465                                         if (go->ob) {
1466                                                 BLI_assert((go->ob->recalc & OB_RECALC_ALL) == 0);
1467                                         }
1468                                 }
1469                         }
1470                 }
1471 #endif
1472
1473                 return;
1474         }
1475
1476         state.eval_ctx = eval_ctx;
1477         state.scene = scene;
1478         state.scene_parent = scene_parent;
1479
1480         /* Those are only needed when blender is run with --debug argument. */
1481         if (G.debug & G_DEBUG_DEPSGRAPH) {
1482                 memset(state.statistics, 0, sizeof(state.statistics));
1483                 state.has_updated_objects = false;
1484                 state.base_time = PIL_check_seconds_timer();
1485         }
1486
1487 #ifdef MBALL_SINGLETHREAD_HACK
1488         state.has_mballs = false;
1489 #endif
1490
1491         task_pool = BLI_task_pool_create(task_scheduler, &state);
1492
1493         DAG_threaded_update_begin(scene, scene_update_object_add_task, task_pool);
1494         BLI_task_pool_work_and_wait(task_pool);
1495         BLI_task_pool_free(task_pool);
1496
1497         if (G.debug & G_DEBUG_DEPSGRAPH) {
1498                 print_threads_statistics(&state);
1499         }
1500
1501         /* We do single thread pass to update all the objects which are in cyclic dependency.
1502          * Such objects can not be handled by a generic DAG traverse and it's really tricky
1503          * to detect whether cycle could be solved or not.
1504          *
1505          * In this situation we simply update all remaining objects in a single thread and
1506          * it'll happen in the same exact order as it was in single-threaded DAG.
1507          *
1508          * We couldn't use threaded update for objects which are in cycle because they might
1509          * access data of each other which is being re-evaluated.
1510          *
1511          * Also, as was explained above, for now we also update all the mballs in single thread.
1512          *
1513          *                                                                   - sergey -
1514          */
1515         need_singlethread_pass = DAG_is_acyclic(scene) == false;
1516 #ifdef MBALL_SINGLETHREAD_HACK
1517         need_singlethread_pass |= state.has_mballs;
1518 #endif
1519
1520         if (need_singlethread_pass) {
1521                 scene_update_all_bases(eval_ctx, scene, scene_parent);
1522         }
1523 }
1524
1525 static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1526 {
1527         scene->customdata_mask = scene_parent->customdata_mask;
1528
1529         /* sets first, we allow per definition current scene to have
1530          * dependencies on sets, but not the other way around. */
1531         if (scene->set)
1532                 scene_update_tagged_recursive(eval_ctx, bmain, scene->set, scene_parent);
1533
1534         /* scene objects */
1535         scene_update_objects(eval_ctx, bmain, scene, scene_parent);
1536
1537         /* scene drivers... */
1538         scene_update_drivers(bmain, scene);
1539
1540         /* update sound system animation */
1541         sound_update_scene(scene);
1542
1543         /* update masking curves */
1544         BKE_mask_update_scene(bmain, scene);
1545         
1546 }
1547
1548 void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *scene)
1549 {
1550         Scene *sce_iter;
1551         
1552         /* keep this first */
1553         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1554
1555         /* (re-)build dependency graph if needed */
1556         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
1557                 DAG_scene_relations_update(bmain, sce_iter);
1558
1559         /* flush recalc flags to dependencies */
1560         DAG_ids_flush_tagged(bmain);
1561
1562         /* removed calls to quick_cache, see pointcache.c */
1563         
1564         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1565          * when trying to find materials with drivers that need evaluating [#32017] 
1566          */
1567         BKE_main_id_tag_idcode(bmain, ID_MA, false);
1568         BKE_main_id_tag_idcode(bmain, ID_LA, false);
1569
1570         /* update all objects: drivers, matrices, displists, etc. flags set
1571          * by depgraph or manual, no layer check here, gets correct flushed
1572          *
1573          * in the future this should handle updates for all datablocks, not
1574          * only objects and scenes. - brecht */
1575         scene_update_tagged_recursive(eval_ctx, bmain, scene, scene);
1576
1577         /* extra call here to recalc scene animation (for sequencer) */
1578         {
1579                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1580                 float ctime = BKE_scene_frame_get(scene);
1581                 
1582                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1583                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1584         }
1585
1586         /* Extra call here to recalc aterial animation.
1587          *
1588          * Need to do this so changing material settings from the graph/dopesheet
1589          * will update suff in the viewport.
1590          */
1591         if (DAG_id_type_tagged(bmain, ID_MA)) {
1592                 Material *material;
1593                 float ctime = BKE_scene_frame_get(scene);
1594
1595                 for (material = bmain->mat.first;
1596                      material;
1597                      material = material->id.next)
1598                 {
1599                         AnimData *adt = BKE_animdata_from_id(&material->id);
1600                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1601                                 BKE_animsys_evaluate_animdata(scene, &material->id, adt, ctime, 0);
1602                 }
1603         }
1604         
1605         /* notify editors and python about recalc */
1606         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1607         DAG_ids_check_recalc(bmain, scene, FALSE);
1608
1609         /* clear recalc flags */
1610         DAG_ids_clear_recalc(bmain);
1611 }
1612
1613 /* applies changes right away, does all sets too */
1614 void BKE_scene_update_for_newframe(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay)
1615 {
1616         float ctime = BKE_scene_frame_get(sce);
1617         Scene *sce_iter;
1618 #ifdef DETAILED_ANALYSIS_OUTPUT
1619         double start_time = PIL_check_seconds_timer();
1620 #endif
1621
1622         /* keep this first */
1623         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1624         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1625
1626         /* update animated image textures for particles, modifiers, gpu, etc,
1627          * call this at the start so modifiers with textures don't lag 1 frame */
1628         BKE_image_update_frame(bmain, sce->r.cfra);
1629         
1630         /* rebuild rigid body worlds before doing the actual frame update
1631          * this needs to be done on start frame but animation playback usually starts one frame later
1632          * we need to do it here to avoid rebuilding the world on every simulation change, which can be very expensive
1633          */
1634         scene_rebuild_rbw_recursive(sce, ctime);
1635
1636         sound_set_cfra(sce->r.cfra);
1637         
1638         /* clear animation overrides */
1639         /* XXX TODO... */
1640
1641         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set)
1642                 DAG_scene_relations_update(bmain, sce_iter);
1643
1644         /* flush recalc flags to dependencies, if we were only changing a frame
1645          * this would not be necessary, but if a user or a script has modified
1646          * some datablock before BKE_scene_update_tagged was called, we need the flush */
1647         DAG_ids_flush_tagged(bmain);
1648
1649         /* Following 2 functions are recursive
1650          * so don't call within 'scene_update_tagged_recursive' */
1651         DAG_scene_update_flags(bmain, sce, lay, TRUE);   // only stuff that moves or needs display still
1652
1653         BKE_mask_evaluate_all_masks(bmain, ctime, true);
1654
1655         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1656          * with an 'local' to 'macro' order of evaluation. This should ensure that
1657          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1658          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1659          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1660          */
1661         BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1662         /*...done with recursive funcs */
1663
1664         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1665          * when trying to find materials with drivers that need evaluating [#32017] 
1666          */
1667         BKE_main_id_tag_idcode(bmain, ID_MA, false);
1668         BKE_main_id_tag_idcode(bmain, ID_LA, false);
1669
1670         /* run rigidbody sim */
1671         /* NOTE: current position is so that rigidbody sim affects other objects, might change in the future */
1672         scene_do_rb_simulation_recursive(sce, ctime);
1673
1674         /* BKE_object_handle_update() on all objects, groups and sets */
1675         scene_update_tagged_recursive(eval_ctx, bmain, sce, sce);
1676
1677         scene_depsgraph_hack(eval_ctx, sce, sce);
1678
1679         /* notify editors and python about recalc */
1680         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1681         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1682
1683         DAG_ids_check_recalc(bmain, sce, TRUE);
1684
1685         /* clear recalc flags */
1686         DAG_ids_clear_recalc(bmain);
1687
1688 #ifdef DETAILED_ANALYSIS_OUTPUT
1689         fprintf(stderr, "frame update start_time %f duration %f\n", start_time, PIL_check_seconds_timer() - start_time);
1690 #endif
1691 }
1692
1693 /* return default layer, also used to patch old files */
1694 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
1695 {
1696         SceneRenderLayer *srl;
1697
1698         if (!name)
1699                 name = DATA_("RenderLayer");
1700
1701         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1702         BLI_strncpy(srl->name, name, sizeof(srl->name));
1703         BLI_uniquename(&sce->r.layers, srl, DATA_("RenderLayer"), '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1704         BLI_addtail(&sce->r.layers, srl);
1705
1706         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1707         srl->lay = (1 << 20) - 1;
1708         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
1709         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
1710         srl->pass_alpha_threshold = 0.5f;
1711         BKE_freestyle_config_init(&srl->freestyleConfig);
1712
1713         return srl;
1714 }
1715
1716 bool BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
1717 {
1718         const int act = BLI_findindex(&scene->r.layers, srl);
1719         Scene *sce;
1720
1721         if (act == -1) {
1722                 return 0;
1723         }
1724         else if ( (scene->r.layers.first == scene->r.layers.last) &&
1725                   (scene->r.layers.first == srl))
1726         {
1727                 /* ensure 1 layer is kept */
1728                 return 0;
1729         }
1730
1731         BLI_remlink(&scene->r.layers, srl);
1732         MEM_freeN(srl);
1733
1734         scene->r.actlay = 0;
1735
1736         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1737                 if (sce->nodetree) {
1738                         bNode *node;
1739                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1740                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
1741                                         if (node->custom1 == act)
1742                                                 node->custom1 = 0;
1743                                         else if (node->custom1 > act)
1744                                                 node->custom1--;
1745                                 }
1746                         }
1747                 }
1748         }
1749
1750         return 1;
1751 }
1752
1753 /* render simplification */
1754
1755 int get_render_subsurf_level(RenderData *r, int lvl)
1756 {
1757         if (r->mode & R_SIMPLIFY)
1758                 return min_ii(r->simplify_subsurf, lvl);
1759         else
1760                 return lvl;
1761 }
1762
1763 int get_render_child_particle_number(RenderData *r, int num)
1764 {
1765         if (r->mode & R_SIMPLIFY)
1766                 return (int)(r->simplify_particles * num);
1767         else
1768                 return num;
1769 }
1770
1771 int get_render_shadow_samples(RenderData *r, int samples)
1772 {
1773         if ((r->mode & R_SIMPLIFY) && samples > 0)
1774                 return min_ii(r->simplify_shadowsamples, samples);
1775         else
1776                 return samples;
1777 }
1778
1779 float get_render_aosss_error(RenderData *r, float error)
1780 {
1781         if (r->mode & R_SIMPLIFY)
1782                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
1783         else
1784                 return error;
1785 }
1786
1787 /* helper function for the SETLOOPER macro */
1788 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1789 {
1790         if (base && base->next) {
1791                 /* common case, step to the next */
1792                 return base->next;
1793         }
1794         else if (base == NULL && (*sce_iter)->base.first) {
1795                 /* first time looping, return the scenes first base */
1796                 return (Base *)(*sce_iter)->base.first;
1797         }
1798         else {
1799                 /* reached the end, get the next base in the set */
1800                 while ((*sce_iter = (*sce_iter)->set)) {
1801                         base = (Base *)(*sce_iter)->base.first;
1802                         if (base) {
1803                                 return base;
1804                         }
1805                 }
1806         }
1807
1808         return NULL;
1809 }
1810
1811 bool BKE_scene_use_new_shading_nodes(Scene *scene)
1812 {
1813         RenderEngineType *type = RE_engines_find(scene->r.engine);
1814         return (type && type->flag & RE_USE_SHADING_NODES);
1815 }
1816
1817 void BKE_scene_base_flag_to_objects(struct Scene *scene)
1818 {
1819         Base *base = scene->base.first;
1820
1821         while (base) {
1822                 base->object->flag = base->flag;
1823                 base = base->next;
1824         }
1825 }
1826
1827 void BKE_scene_base_flag_from_objects(struct Scene *scene)
1828 {
1829         Base *base = scene->base.first;
1830
1831         while (base) {
1832                 base->flag = base->object->flag;
1833                 base = base->next;
1834         }
1835 }
1836
1837 void BKE_scene_disable_color_management(Scene *scene)
1838 {
1839         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1840         ColorManagedViewSettings *view_settings = &scene->view_settings;
1841         const char *view;
1842         const char *none_display_name;
1843
1844         none_display_name = IMB_colormanagement_display_get_none_name();
1845
1846         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
1847
1848         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1849
1850         if (view) {
1851                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1852         }
1853 }
1854
1855 bool BKE_scene_check_color_management_enabled(const Scene *scene)
1856 {
1857         return strcmp(scene->display_settings.display_device, "None") != 0;
1858 }
1859
1860 bool BKE_scene_check_rigidbody_active(const Scene *scene)
1861 {
1862         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1863 }
1864
1865 int BKE_render_num_threads(const RenderData *rd)
1866 {
1867         int threads;
1868
1869         /* override set from command line? */
1870         threads = BLI_system_num_threads_override_get();
1871
1872         if (threads > 0)
1873                 return threads;
1874
1875         /* fixed number of threads specified in scene? */
1876         if (rd->mode & R_FIXED_THREADS)
1877                 threads = rd->threads;
1878         else
1879                 threads = BLI_system_thread_count();
1880         
1881         return max_ii(threads, 1);
1882 }
1883
1884 int BKE_scene_num_threads(const Scene *scene)
1885 {
1886         return BKE_render_num_threads(&scene->r);
1887 }
1888