28cc4305da84fc02eff3d33b9d72a3911ade3290
[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->toolsettings->imapaint.paint.flags |= PAINT_SHOW_BRUSH;
546
547         sce->physics_settings.gravity[0] = 0.0f;
548         sce->physics_settings.gravity[1] = 0.0f;
549         sce->physics_settings.gravity[2] = -9.81f;
550         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
551
552         sce->unit.scale_length = 1.0f;
553
554         pset = &sce->toolsettings->particle;
555         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
556         pset->emitterdist = 0.25f;
557         pset->totrekey = 5;
558         pset->totaddkey = 5;
559         pset->brushtype = PE_BRUSH_NONE;
560         pset->draw_step = 2;
561         pset->fade_frames = 2;
562         pset->selectmode = SCE_SELECT_PATH;
563         for (a = 0; a < PE_TOT_BRUSH; a++) {
564                 pset->brush[a].strength = 0.5;
565                 pset->brush[a].size = 50;
566                 pset->brush[a].step = 10;
567                 pset->brush[a].count = 10;
568         }
569         pset->brush[PE_BRUSH_CUT].strength = 100;
570
571         sce->r.ffcodecdata.audio_mixrate = 44100;
572         sce->r.ffcodecdata.audio_volume = 1.0f;
573         sce->r.ffcodecdata.audio_bitrate = 192;
574         sce->r.ffcodecdata.audio_channels = 2;
575
576         BLI_strncpy(sce->r.engine, "BLENDER_RENDER", sizeof(sce->r.engine));
577
578         sce->audio.distance_model = 2.0f;
579         sce->audio.doppler_factor = 1.0f;
580         sce->audio.speed_of_sound = 343.3f;
581         sce->audio.volume = 1.0f;
582
583         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
584
585         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
586         sce->r.osa = 8;
587
588         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
589         BKE_scene_add_render_layer(sce, NULL);
590         
591         /* game data */
592         sce->gm.stereoflag = STEREO_NOSTEREO;
593         sce->gm.stereomode = STEREO_ANAGLYPH;
594         sce->gm.eyeseparation = 0.10;
595
596         sce->gm.dome.angle = 180;
597         sce->gm.dome.mode = DOME_FISHEYE;
598         sce->gm.dome.res = 4;
599         sce->gm.dome.resbuf = 1.0f;
600         sce->gm.dome.tilt = 0;
601
602         sce->gm.xplay = 640;
603         sce->gm.yplay = 480;
604         sce->gm.freqplay = 60;
605         sce->gm.depth = 32;
606
607         sce->gm.gravity = 9.8f;
608         sce->gm.physicsEngine = WOPHY_BULLET;
609         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
610         sce->gm.occlusionRes = 128;
611         sce->gm.ticrate = 60;
612         sce->gm.maxlogicstep = 5;
613         sce->gm.physubstep = 1;
614         sce->gm.maxphystep = 5;
615         sce->gm.lineardeactthreshold = 0.8f;
616         sce->gm.angulardeactthreshold = 1.0f;
617         sce->gm.deactivationtime = 0.0f;
618
619         sce->gm.flag = GAME_DISPLAY_LISTS;
620         sce->gm.matmode = GAME_MAT_MULTITEX;
621
622         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
623         sce->gm.levelHeight = 2.f;
624
625         sce->gm.recastData.cellsize = 0.3f;
626         sce->gm.recastData.cellheight = 0.2f;
627         sce->gm.recastData.agentmaxslope = M_PI / 2;
628         sce->gm.recastData.agentmaxclimb = 0.9f;
629         sce->gm.recastData.agentheight = 2.0f;
630         sce->gm.recastData.agentradius = 0.6f;
631         sce->gm.recastData.edgemaxlen = 12.0f;
632         sce->gm.recastData.edgemaxerror = 1.3f;
633         sce->gm.recastData.regionminsize = 8.f;
634         sce->gm.recastData.regionmergesize = 20.f;
635         sce->gm.recastData.vertsperpoly = 6;
636         sce->gm.recastData.detailsampledist = 6.0f;
637         sce->gm.recastData.detailsamplemaxerror = 1.0f;
638
639         sce->gm.exitkey = 218; // Blender key code for ESC
640
641         sound_create_scene(sce);
642
643         /* color management */
644         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
645
646         BKE_color_managed_display_settings_init(&sce->display_settings);
647         BKE_color_managed_view_settings_init(&sce->view_settings);
648         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
649                     sizeof(sce->sequencer_colorspace_settings.name));
650
651         return sce;
652 }
653
654 Base *BKE_scene_base_find(Scene *scene, Object *ob)
655 {
656         return BLI_findptr(&scene->base, ob, offsetof(Base, object));
657 }
658
659 void BKE_scene_set_background(Main *bmain, Scene *scene)
660 {
661         Scene *sce;
662         Base *base;
663         Object *ob;
664         Group *group;
665         GroupObject *go;
666         int flag;
667         
668         /* check for cyclic sets, for reading old files but also for definite security (py?) */
669         BKE_scene_validate_setscene(bmain, scene);
670         
671         /* can happen when switching modes in other scenes */
672         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
673                 scene->obedit = NULL;
674
675         /* deselect objects (for dataselect) */
676         for (ob = bmain->object.first; ob; ob = ob->id.next)
677                 ob->flag &= ~(SELECT | OB_FROMGROUP);
678
679         /* group flags again */
680         for (group = bmain->group.first; group; group = group->id.next) {
681                 for (go = group->gobject.first; go; go = go->next) {
682                         if (go->ob) {
683                                 go->ob->flag |= OB_FROMGROUP;
684                         }
685                 }
686         }
687
688         /* sort baselist for scene and sets */
689         for (sce = scene; sce; sce = sce->set)
690                 DAG_scene_relations_rebuild(bmain, sce);
691
692         /* copy layers and flags from bases to objects */
693         for (base = scene->base.first; base; base = base->next) {
694                 ob = base->object;
695                 ob->lay = base->lay;
696                 
697                 /* group patch... */
698                 base->flag &= ~(OB_FROMGROUP);
699                 flag = ob->flag & (OB_FROMGROUP);
700                 base->flag |= flag;
701                 
702                 /* not too nice... for recovering objects with lost data */
703                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
704                 ob->flag = base->flag;
705         }
706         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
707 }
708
709 /* called from creator.c */
710 Scene *BKE_scene_set_name(Main *bmain, const char *name)
711 {
712         Scene *sce = (Scene *)BKE_libblock_find_name(ID_SCE, name);
713         if (sce) {
714                 BKE_scene_set_background(bmain, sce);
715                 printf("Scene switch: '%s' in file: '%s'\n", name, G.main->name);
716                 return sce;
717         }
718
719         printf("Can't find scene: '%s' in file: '%s'\n", name, G.main->name);
720         return NULL;
721 }
722
723 static void scene_unlink_space_node(SpaceNode *snode, Scene *sce)
724 {
725         if (snode->id == &sce->id) {
726                 /* nasty DNA logic for SpaceNode:
727                  * ideally should be handled by editor code, but would be bad level call
728                  */
729                 bNodeTreePath *path, *path_next;
730                 for (path = snode->treepath.first; path; path = path_next) {
731                         path_next = path->next;
732                         MEM_freeN(path);
733                 }
734                 BLI_listbase_clear(&snode->treepath);
735                 
736                 snode->id = NULL;
737                 snode->from = NULL;
738                 snode->nodetree = NULL;
739                 snode->edittree = NULL;
740         }
741 }
742
743 void BKE_scene_unlink(Main *bmain, Scene *sce, Scene *newsce)
744 {
745         Scene *sce1;
746         bScreen *screen;
747
748         /* check all sets */
749         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next)
750                 if (sce1->set == sce)
751                         sce1->set = NULL;
752         
753         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next) {
754                 bNode *node;
755                 
756                 if (sce1 == sce || !sce1->nodetree)
757                         continue;
758                 
759                 for (node = sce1->nodetree->nodes.first; node; node = node->next) {
760                         if (node->id == &sce->id)
761                                 node->id = NULL;
762                 }
763         }
764         
765         /* all screens */
766         for (screen = bmain->screen.first; screen; screen = screen->id.next) {
767                 ScrArea *area;
768                 
769                 if (screen->scene == sce)
770                         screen->scene = newsce;
771                 
772                 for (area = screen->areabase.first; area; area = area->next) {
773                         SpaceLink *space_link;
774                         for (space_link = area->spacedata.first; space_link; space_link = space_link->next) {
775                                 if (space_link->spacetype == SPACE_NODE)
776                                         scene_unlink_space_node((SpaceNode *)space_link, sce);
777                         }
778                 }
779         }
780
781         BKE_libblock_free(bmain, sce);
782 }
783
784 /* used by metaballs
785  * doesn't return the original duplicated object, only dupli's
786  */
787 int BKE_scene_base_iter_next(EvaluationContext *eval_ctx, SceneBaseIter *iter,
788                              Scene **scene, int val, Base **base, Object **ob)
789 {
790         bool run_again = true;
791         
792         /* init */
793         if (val == 0) {
794                 iter->phase = F_START;
795                 iter->dupob = NULL;
796                 iter->duplilist = NULL;
797         }
798         else {
799                 /* run_again is set when a duplilist has been ended */
800                 while (run_again) {
801                         run_again = 0;
802
803                         /* the first base */
804                         if (iter->phase == F_START) {
805                                 *base = (*scene)->base.first;
806                                 if (*base) {
807                                         *ob = (*base)->object;
808                                         iter->phase = F_SCENE;
809                                 }
810                                 else {
811                                         /* exception: empty scene */
812                                         while ((*scene)->set) {
813                                                 (*scene) = (*scene)->set;
814                                                 if ((*scene)->base.first) {
815                                                         *base = (*scene)->base.first;
816                                                         *ob = (*base)->object;
817                                                         iter->phase = F_SCENE;
818                                                         break;
819                                                 }
820                                         }
821                                 }
822                         }
823                         else {
824                                 if (*base && iter->phase != F_DUPLI) {
825                                         *base = (*base)->next;
826                                         if (*base) {
827                                                 *ob = (*base)->object;
828                                         }
829                                         else {
830                                                 if (iter->phase == F_SCENE) {
831                                                         /* (*scene) is finished, now do the set */
832                                                         while ((*scene)->set) {
833                                                                 (*scene) = (*scene)->set;
834                                                                 if ((*scene)->base.first) {
835                                                                         *base = (*scene)->base.first;
836                                                                         *ob = (*base)->object;
837                                                                         break;
838                                                                 }
839                                                         }
840                                                 }
841                                         }
842                                 }
843                         }
844                         
845                         if (*base == NULL) {
846                                 iter->phase = F_START;
847                         }
848                         else {
849                                 if (iter->phase != F_DUPLI) {
850                                         if ( (*base)->object->transflag & OB_DUPLI) {
851                                                 /* groups cannot be duplicated for mballs yet, 
852                                                  * this enters eternal loop because of 
853                                                  * makeDispListMBall getting called inside of group_duplilist */
854                                                 if ((*base)->object->dup_group == NULL) {
855                                                         iter->duplilist = object_duplilist_ex(eval_ctx, (*scene), (*base)->object, false);
856                                                         
857                                                         iter->dupob = iter->duplilist->first;
858
859                                                         if (!iter->dupob)
860                                                                 free_object_duplilist(iter->duplilist);
861                                                 }
862                                         }
863                                 }
864                                 /* handle dupli's */
865                                 if (iter->dupob) {
866                                         
867                                         copy_m4_m4(iter->omat, iter->dupob->ob->obmat);
868                                         copy_m4_m4(iter->dupob->ob->obmat, iter->dupob->mat);
869                                         
870                                         (*base)->flag |= OB_FROMDUPLI;
871                                         *ob = iter->dupob->ob;
872                                         iter->phase = F_DUPLI;
873                                         
874                                         iter->dupob = iter->dupob->next;
875                                 }
876                                 else if (iter->phase == F_DUPLI) {
877                                         iter->phase = F_SCENE;
878                                         (*base)->flag &= ~OB_FROMDUPLI;
879                                         
880                                         for (iter->dupob = iter->duplilist->first; iter->dupob; iter->dupob = iter->dupob->next) {
881                                                 copy_m4_m4(iter->dupob->ob->obmat, iter->omat);
882                                         }
883                                         
884                                         free_object_duplilist(iter->duplilist);
885                                         iter->duplilist = NULL;
886                                         run_again = 1;
887                                 }
888                         }
889                 }
890         }
891
892 #if 0
893         if (ob && *ob) {
894                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
895         }
896 #endif
897
898         return iter->phase;
899 }
900
901 Object *BKE_scene_camera_find(Scene *sc)
902 {
903         Base *base;
904         
905         for (base = sc->base.first; base; base = base->next)
906                 if (base->object->type == OB_CAMERA)
907                         return base->object;
908
909         return NULL;
910 }
911
912 #ifdef DURIAN_CAMERA_SWITCH
913 Object *BKE_scene_camera_switch_find(Scene *scene)
914 {
915         TimeMarker *m;
916         int cfra = scene->r.cfra;
917         int frame = -(MAXFRAME + 1);
918         int min_frame = MAXFRAME + 1;
919         Object *camera = NULL;
920         Object *first_camera = NULL;
921
922         for (m = scene->markers.first; m; m = m->next) {
923                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
924                         if ((m->frame <= cfra) && (m->frame > frame)) {
925                                 camera = m->camera;
926                                 frame = m->frame;
927
928                                 if (frame == cfra)
929                                         break;
930                         }
931
932                         if (m->frame < min_frame) {
933                                 first_camera = m->camera;
934                                 min_frame = m->frame;
935                         }
936                 }
937         }
938
939         if (camera == NULL) {
940                 /* If there's no marker to the left of current frame,
941                  * use camera from left-most marker to solve all sort
942                  * of Schrodinger uncertainties.
943                  */
944                 return first_camera;
945         }
946
947         return camera;
948 }
949 #endif
950
951 int BKE_scene_camera_switch_update(Scene *scene)
952 {
953 #ifdef DURIAN_CAMERA_SWITCH
954         Object *camera = BKE_scene_camera_switch_find(scene);
955         if (camera) {
956                 scene->camera = camera;
957                 return 1;
958         }
959 #else
960         (void)scene;
961 #endif
962         return 0;
963 }
964
965 char *BKE_scene_find_marker_name(Scene *scene, int frame)
966 {
967         ListBase *markers = &scene->markers;
968         TimeMarker *m1, *m2;
969
970         /* search through markers for match */
971         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
972                 if (m1->frame == frame)
973                         return m1->name;
974
975                 if (m1 == m2)
976                         break;
977
978                 if (m2->frame == frame)
979                         return m2->name;
980         }
981
982         return NULL;
983 }
984
985 /* return the current marker for this frame,
986  * we can have more than 1 marker per frame, this just returns the first :/ */
987 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
988 {
989         TimeMarker *marker, *best_marker = NULL;
990         int best_frame = -MAXFRAME * 2;
991         for (marker = scene->markers.first; marker; marker = marker->next) {
992                 if (marker->frame == frame) {
993                         return marker->name;
994                 }
995
996                 if (marker->frame > best_frame && marker->frame < frame) {
997                         best_marker = marker;
998                         best_frame = marker->frame;
999                 }
1000         }
1001
1002         return best_marker ? best_marker->name : NULL;
1003 }
1004
1005
1006 Base *BKE_scene_base_add(Scene *sce, Object *ob)
1007 {
1008         Base *b = MEM_callocN(sizeof(*b), "BKE_scene_base_add");
1009         BLI_addhead(&sce->base, b);
1010
1011         b->object = ob;
1012         b->flag = ob->flag;
1013         b->lay = ob->lay;
1014
1015         return b;
1016 }
1017
1018 void BKE_scene_base_unlink(Scene *sce, Base *base)
1019 {
1020         /* remove rigid body constraint from world before removing object */
1021         if (base->object->rigidbody_constraint)
1022                 BKE_rigidbody_remove_constraint(sce, base->object);
1023         /* remove rigid body object from world before removing object */
1024         if (base->object->rigidbody_object)
1025                 BKE_rigidbody_remove_object(sce, base->object);
1026         
1027         BLI_remlink(&sce->base, base);
1028 }
1029
1030 void BKE_scene_base_deselect_all(Scene *sce)
1031 {
1032         Base *b;
1033
1034         for (b = sce->base.first; b; b = b->next) {
1035                 b->flag &= ~SELECT;
1036                 b->object->flag = b->flag;
1037         }
1038 }
1039
1040 void BKE_scene_base_select(Scene *sce, Base *selbase)
1041 {
1042         selbase->flag |= SELECT;
1043         selbase->object->flag = selbase->flag;
1044
1045         sce->basact = selbase;
1046 }
1047
1048 /* checks for cycle, returns 1 if it's all OK */
1049 int BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1050 {
1051         Scene *scene;
1052         int a, totscene;
1053         
1054         if (sce->set == NULL) return 1;
1055         
1056         totscene = 0;
1057         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1058                 totscene++;
1059         
1060         for (a = 0, scene = sce; scene->set; scene = scene->set, a++) {
1061                 /* more iterations than scenes means we have a cycle */
1062                 if (a > totscene) {
1063                         /* the tested scene gets zero'ed, that's typically current scene */
1064                         sce->set = NULL;
1065                         return 0;
1066                 }
1067         }
1068
1069         return 1;
1070 }
1071
1072 /* This function is needed to cope with fractional frames - including two Blender rendering features
1073  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1074  */
1075 float BKE_scene_frame_get(Scene *scene)
1076 {
1077         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1078 }
1079
1080 /* This function is used to obtain arbitrary fractional frames */
1081 float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame)
1082 {
1083         float ctime = frame;
1084         ctime += scene->r.subframe;
1085         ctime *= scene->r.framelen;
1086         
1087         return ctime;
1088 }
1089
1090 /**
1091  * Sets the frame int/float components.
1092  */
1093 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1094 {
1095         double intpart;
1096         scene->r.subframe = modf(cfra, &intpart);
1097         scene->r.cfra = (int)intpart;
1098
1099         if (cfra < 0.0) {
1100                 scene->r.cfra -= 1;
1101                 scene->r.subframe = 1.0f + scene->r.subframe;
1102         }
1103 }
1104
1105 /* drivers support/hacks 
1106  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
1107  *      - these are always run since the depsgraph can't handle non-object data
1108  *      - these happen after objects are all done so that we can read in their final transform values,
1109  *        though this means that objects can't refer to scene info for guidance...
1110  */
1111 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
1112 {
1113         SceneRenderLayer *srl;
1114         float ctime = BKE_scene_frame_get(scene);
1115         
1116         /* scene itself */
1117         if (scene->adt && scene->adt->drivers.first) {
1118                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
1119         }
1120
1121         /* world */
1122         /* TODO: what about world textures? but then those have nodes too... */
1123         if (scene->world) {
1124                 ID *wid = (ID *)scene->world;
1125                 AnimData *adt = BKE_animdata_from_id(wid);
1126                 
1127                 if (adt && adt->drivers.first)
1128                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
1129         }
1130         
1131         /* nodes */
1132         if (scene->nodetree) {
1133                 ID *nid = (ID *)scene->nodetree;
1134                 AnimData *adt = BKE_animdata_from_id(nid);
1135                 
1136                 if (adt && adt->drivers.first)
1137                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1138         }
1139
1140         /* world nodes */
1141         if (scene->world && scene->world->nodetree) {
1142                 ID *nid = (ID *)scene->world->nodetree;
1143                 AnimData *adt = BKE_animdata_from_id(nid);
1144                 
1145                 if (adt && adt->drivers.first)
1146                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1147         }
1148
1149         /* freestyle */
1150         for (srl = scene->r.layers.first; srl; srl = srl->next) {
1151                 FreestyleConfig *config = &srl->freestyleConfig;
1152                 FreestyleLineSet *lineset;
1153
1154                 for (lineset = config->linesets.first; lineset; lineset = lineset->next) {
1155                         if (lineset->linestyle) {
1156                                 ID *lid = &lineset->linestyle->id;
1157                                 AnimData *adt = BKE_animdata_from_id(lid);
1158
1159                                 if (adt && adt->drivers.first)
1160                                         BKE_animsys_evaluate_animdata(scene, lid, adt, ctime, ADT_RECALC_DRIVERS);
1161                         }
1162                 }
1163         }
1164 }
1165
1166 /* deps hack - do extra recalcs at end */
1167 static void scene_depsgraph_hack(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1168 {
1169         Base *base;
1170                 
1171         scene->customdata_mask = scene_parent->customdata_mask;
1172         
1173         /* sets first, we allow per definition current scene to have
1174          * dependencies on sets, but not the other way around. */
1175         if (scene->set)
1176                 scene_depsgraph_hack(eval_ctx, scene->set, scene_parent);
1177         
1178         for (base = scene->base.first; base; base = base->next) {
1179                 Object *ob = base->object;
1180                 
1181                 if (ob->depsflag) {
1182                         int recalc = 0;
1183                         // printf("depshack %s\n", ob->id.name + 2);
1184                         
1185                         if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC)
1186                                 recalc |= OB_RECALC_OB;
1187                         if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC)
1188                                 recalc |= OB_RECALC_DATA;
1189                         
1190                         ob->recalc |= recalc;
1191                         BKE_object_handle_update(eval_ctx, scene_parent, ob);
1192                         
1193                         if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1194                                 GroupObject *go;
1195                                 
1196                                 for (go = ob->dup_group->gobject.first; go; go = go->next) {
1197                                         if (go->ob)
1198                                                 go->ob->recalc |= recalc;
1199                                 }
1200                                 BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, ob, ob->dup_group);
1201                         }
1202                 }
1203         }
1204
1205 }
1206
1207 static void scene_rebuild_rbw_recursive(Scene *scene, float ctime)
1208 {
1209         if (scene->set)
1210                 scene_rebuild_rbw_recursive(scene->set, ctime);
1211
1212         if (BKE_scene_check_rigidbody_active(scene))
1213                 BKE_rigidbody_rebuild_world(scene, ctime);
1214 }
1215
1216 static void scene_do_rb_simulation_recursive(Scene *scene, float ctime)
1217 {
1218         if (scene->set)
1219                 scene_do_rb_simulation_recursive(scene->set, ctime);
1220
1221         if (BKE_scene_check_rigidbody_active(scene))
1222                 BKE_rigidbody_do_simulation(scene, ctime);
1223 }
1224
1225 /* Used to visualize CPU threads activity during threaded object update,
1226  * would pollute STDERR with whole bunch of timing information which then
1227  * could be parsed and nicely visualized.
1228  */
1229 #undef DETAILED_ANALYSIS_OUTPUT
1230
1231 /* Mballs evaluation uses BKE_scene_base_iter_next which calls
1232  * duplilist for all objects in the scene. This leads to conflict
1233  * accessing and writing same data from multiple threads.
1234  *
1235  * Ideally Mballs shouldn't do such an iteration and use DAG
1236  * queries instead. For the time being we've got new DAG
1237  * let's keep it simple and update mballs in a ingle thread.
1238  */
1239 #define MBALL_SINGLETHREAD_HACK
1240
1241 typedef struct StatisicsEntry {
1242         struct StatisicsEntry *next, *prev;
1243         Object *object;
1244         double start_time;
1245         double duration;
1246 } StatisicsEntry;
1247
1248 typedef struct ThreadedObjectUpdateState {
1249         /* TODO(sergey): We might want this to be per-thread object. */
1250         EvaluationContext *eval_ctx;
1251         Scene *scene;
1252         Scene *scene_parent;
1253         double base_time;
1254
1255         /* Execution statistics */
1256         ListBase statistics[BLENDER_MAX_THREADS];
1257         bool has_updated_objects;
1258
1259 #ifdef MBALL_SINGLETHREAD_HACK
1260         bool has_mballs;
1261 #endif
1262 } ThreadedObjectUpdateState;
1263
1264 static void scene_update_object_add_task(void *node, void *user_data);
1265
1266 static void scene_update_all_bases(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1267 {
1268         Base *base;
1269
1270         for (base = scene->base.first; base; base = base->next) {
1271                 Object *object = base->object;
1272
1273                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, true);
1274
1275                 if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1276                         BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, object, object->dup_group);
1277
1278                 /* always update layer, so that animating layers works (joshua july 2010) */
1279                 /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes
1280                  * (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */
1281                 // base->lay = ob->lay;
1282         }
1283 }
1284
1285 static void scene_update_object_func(TaskPool *pool, void *taskdata, int threadid)
1286 {
1287 /* Disable print for now in favor of summary statistics at the end of update. */
1288 #define PRINT if (false) printf
1289
1290         ThreadedObjectUpdateState *state = (ThreadedObjectUpdateState *) BLI_task_pool_userdata(pool);
1291         void *node = taskdata;
1292         Object *object = DAG_get_node_object(node);
1293         EvaluationContext *eval_ctx = state->eval_ctx;
1294         Scene *scene = state->scene;
1295         Scene *scene_parent = state->scene_parent;
1296
1297 #ifdef MBALL_SINGLETHREAD_HACK
1298         if (object && object->type == OB_MBALL) {
1299                 state->has_mballs = true;
1300         }
1301         else
1302 #endif
1303         if (object) {
1304                 double start_time = 0.0;
1305                 bool add_to_stats = false;
1306
1307                 if (G.debug & G_DEBUG_DEPSGRAPH) {
1308                         if (object->recalc & OB_RECALC_ALL) {
1309                                 printf("Thread %d: update object %s\n", threadid, object->id.name);
1310                         }
1311
1312                         start_time = PIL_check_seconds_timer();
1313
1314                         if (object->recalc & OB_RECALC_ALL) {
1315                                 state->has_updated_objects = true;
1316                                 add_to_stats = true;
1317                         }
1318                 }
1319
1320                 /* We only update object itself here, dupli-group will be updated
1321                  * separately from main thread because of we've got no idea about
1322                  * dependencies inside the group.
1323                  */
1324                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, false);
1325
1326                 /* Calculate statistics. */
1327                 if (add_to_stats) {
1328                         StatisicsEntry *entry;
1329
1330                         entry = MEM_mallocN(sizeof(StatisicsEntry), "update thread statistics");
1331                         entry->object = object;
1332                         entry->start_time = start_time;
1333                         entry->duration = PIL_check_seconds_timer() - start_time;
1334
1335                         BLI_addtail(&state->statistics[threadid], entry);
1336                 }
1337         }
1338         else {
1339                 PRINT("Threda %d: update node %s\n", threadid,
1340                       DAG_get_node_name(node));
1341         }
1342
1343         /* Update will decrease child's valency and schedule child with zero valency. */
1344         DAG_threaded_update_handle_node_updated(node, scene_update_object_add_task, pool);
1345
1346 #undef PRINT
1347 }
1348
1349 static void scene_update_object_add_task(void *node, void *user_data)
1350 {
1351         TaskPool *task_pool = user_data;
1352
1353         BLI_task_pool_push(task_pool, scene_update_object_func, node, false, TASK_PRIORITY_LOW);
1354 }
1355
1356 static void print_threads_statistics(ThreadedObjectUpdateState *state)
1357 {
1358         int i, tot_thread;
1359
1360         if ((G.debug & G_DEBUG_DEPSGRAPH) == 0) {
1361                 return;
1362         }
1363
1364 #ifdef DETAILED_ANALYSIS_OUTPUT
1365         if (state->has_updated_objects) {
1366                 tot_thread = BLI_system_thread_count();
1367
1368                 fprintf(stderr, "objects update base time %f\n", state->base_time);
1369
1370                 for (i = 0; i < tot_thread; i++) {
1371                         StatisicsEntry *entry;
1372                         for (entry = state->statistics[i].first;
1373                              entry;
1374                              entry = entry->next)
1375                         {
1376                                 fprintf(stderr, "thread %d object %s start_time %f duration %f\n",
1377                                         i, entry->object->id.name + 2,
1378                                         entry->start_time, entry->duration);
1379                         }
1380                         BLI_freelistN(&state->statistics[i]);
1381                 }
1382         }
1383 #else
1384         tot_thread = BLI_system_thread_count();
1385
1386         for (i = 0; i < tot_thread; i++) {
1387                 int total_objects = 0;
1388                 double total_time = 0.0;
1389                 StatisicsEntry *entry;
1390
1391                 if (state->has_updated_objects) {
1392                         /* Don't pollute output if no objects were updated. */
1393                         for (entry = state->statistics[i].first;
1394                              entry;
1395                              entry = entry->next)
1396                         {
1397                                 total_objects++;
1398                                 total_time += entry->duration;
1399                         }
1400
1401                         printf("Thread %d: total %d objects in %f sec.\n", i, total_objects, total_time);
1402
1403                         for (entry = state->statistics[i].first;
1404                              entry;
1405                              entry = entry->next)
1406                         {
1407                                 printf("  %s in %f sec\n", entry->object->id.name + 2, entry->duration);
1408                         }
1409                 }
1410
1411                 BLI_freelistN(&state->statistics[i]);
1412         }
1413 #endif
1414 }
1415
1416 static bool scene_need_update_objects(Main *bmain)
1417 {
1418         return
1419                 /* Object datablocks themselves (for OB_RECALC_OB) */
1420                 DAG_id_type_tagged(bmain, ID_OB) ||
1421
1422                 /* Objects data datablocks (for OB_RECALC_DATA) */
1423                 DAG_id_type_tagged(bmain, ID_ME)  ||  /* Mesh */
1424                 DAG_id_type_tagged(bmain, ID_CU)  ||  /* Curve */
1425                 DAG_id_type_tagged(bmain, ID_MB)  ||  /* MetaBall */
1426                 DAG_id_type_tagged(bmain, ID_LA)  ||  /* Lamp */
1427                 DAG_id_type_tagged(bmain, ID_LT)  ||  /* Lattice */
1428                 DAG_id_type_tagged(bmain, ID_CA)  ||  /* Camera */
1429                 DAG_id_type_tagged(bmain, ID_KE)  ||  /* KE */
1430                 DAG_id_type_tagged(bmain, ID_SPK) ||  /* Speaker */
1431                 DAG_id_type_tagged(bmain, ID_AR);     /* Armature */
1432 }
1433
1434 static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1435 {
1436         TaskScheduler *task_scheduler = BLI_task_scheduler_get();
1437         TaskPool *task_pool;
1438         ThreadedObjectUpdateState state;
1439         bool need_singlethread_pass;
1440
1441         /* Early check for whether we need to invoke all the task-based
1442          * tihngs (spawn new ppol, traverse dependency graph and so on).
1443          *
1444          * Basically if there's no ID datablocks tagged for update which
1445          * corresponds to object->recalc flags (which are checked in
1446          * BKE_object_handle_update() then we do nothing here.
1447          */
1448         if (!scene_need_update_objects(bmain)) {
1449                 return;
1450         }
1451
1452         state.eval_ctx = eval_ctx;
1453         state.scene = scene;
1454         state.scene_parent = scene_parent;
1455
1456         /* Those are only needed when blender is run with --debug argument. */
1457         if (G.debug & G_DEBUG_DEPSGRAPH) {
1458                 memset(state.statistics, 0, sizeof(state.statistics));
1459                 state.has_updated_objects = false;
1460                 state.base_time = PIL_check_seconds_timer();
1461         }
1462
1463 #ifdef MBALL_SINGLETHREAD_HACK
1464         state.has_mballs = false;
1465 #endif
1466
1467         task_pool = BLI_task_pool_create(task_scheduler, &state);
1468
1469         DAG_threaded_update_begin(scene, scene_update_object_add_task, task_pool);
1470         BLI_task_pool_work_and_wait(task_pool);
1471         BLI_task_pool_free(task_pool);
1472
1473         if (G.debug & G_DEBUG_DEPSGRAPH) {
1474                 print_threads_statistics(&state);
1475         }
1476
1477         /* We do single thread pass to update all the objects which are in cyclic dependency.
1478          * Such objects can not be handled by a generic DAG traverse and it's really tricky
1479          * to detect whether cycle could be solved or not.
1480          *
1481          * In this situation we simply update all remaining objects in a single thread and
1482          * it'll happen in the same exact order as it was in single-threaded DAG.
1483          *
1484          * We couldn't use threaded update for objects which are in cycle because they might
1485          * access data of each other which is being re-evaluated.
1486          *
1487          * Also, as was explained above, for now we also update all the mballs in single thread.
1488          *
1489          *                                                                   - sergey -
1490          */
1491         need_singlethread_pass = DAG_is_acyclic(scene) == false;
1492 #ifdef MBALL_SINGLETHREAD_HACK
1493         need_singlethread_pass |= state.has_mballs;
1494 #endif
1495
1496         if (need_singlethread_pass) {
1497                 scene_update_all_bases(eval_ctx, scene, scene_parent);
1498         }
1499 }
1500
1501 static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1502 {
1503         scene->customdata_mask = scene_parent->customdata_mask;
1504
1505         /* sets first, we allow per definition current scene to have
1506          * dependencies on sets, but not the other way around. */
1507         if (scene->set)
1508                 scene_update_tagged_recursive(eval_ctx, bmain, scene->set, scene_parent);
1509
1510         /* scene objects */
1511         scene_update_objects(eval_ctx, bmain, scene, scene_parent);
1512
1513         /* scene drivers... */
1514         scene_update_drivers(bmain, scene);
1515
1516         /* update masking curves */
1517         BKE_mask_update_scene(bmain, scene);
1518         
1519 }
1520
1521 void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *scene)
1522 {
1523         Scene *sce_iter;
1524         
1525         /* keep this first */
1526         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1527
1528         /* (re-)build dependency graph if needed */
1529         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
1530                 DAG_scene_relations_update(bmain, sce_iter);
1531
1532         /* flush recalc flags to dependencies */
1533         DAG_ids_flush_tagged(bmain);
1534
1535         /* removed calls to quick_cache, see pointcache.c */
1536         
1537         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1538          * when trying to find materials with drivers that need evaluating [#32017] 
1539          */
1540         BKE_main_id_tag_idcode(bmain, ID_MA, false);
1541         BKE_main_id_tag_idcode(bmain, ID_LA, false);
1542
1543         /* update all objects: drivers, matrices, displists, etc. flags set
1544          * by depgraph or manual, no layer check here, gets correct flushed
1545          *
1546          * in the future this should handle updates for all datablocks, not
1547          * only objects and scenes. - brecht */
1548         scene_update_tagged_recursive(eval_ctx, bmain, scene, scene);
1549         /* update sound system animation (TODO, move to depsgraph) */
1550         sound_update_scene(bmain, scene);
1551
1552         /* extra call here to recalc scene animation (for sequencer) */
1553         {
1554                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1555                 float ctime = BKE_scene_frame_get(scene);
1556                 
1557                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1558                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1559         }
1560
1561         /* Extra call here to recalc aterial animation.
1562          *
1563          * Need to do this so changing material settings from the graph/dopesheet
1564          * will update suff in the viewport.
1565          */
1566         if (DAG_id_type_tagged(bmain, ID_MA)) {
1567                 Material *material;
1568                 float ctime = BKE_scene_frame_get(scene);
1569
1570                 for (material = bmain->mat.first;
1571                      material;
1572                      material = material->id.next)
1573                 {
1574                         AnimData *adt = BKE_animdata_from_id(&material->id);
1575                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1576                                 BKE_animsys_evaluate_animdata(scene, &material->id, adt, ctime, 0);
1577                 }
1578         }
1579         
1580         /* notify editors and python about recalc */
1581         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1582         DAG_ids_check_recalc(bmain, scene, FALSE);
1583
1584         /* clear recalc flags */
1585         DAG_ids_clear_recalc(bmain);
1586 }
1587
1588 /* applies changes right away, does all sets too */
1589 void BKE_scene_update_for_newframe(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay)
1590 {
1591         BKE_scene_update_for_newframe_ex(eval_ctx, bmain, sce, lay, false);
1592 }
1593
1594 void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay, bool do_invisible_flush)
1595 {
1596         float ctime = BKE_scene_frame_get(sce);
1597         Scene *sce_iter;
1598 #ifdef DETAILED_ANALYSIS_OUTPUT
1599         double start_time = PIL_check_seconds_timer();
1600 #endif
1601
1602         /* keep this first */
1603         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1604         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1605
1606         /* update animated image textures for particles, modifiers, gpu, etc,
1607          * call this at the start so modifiers with textures don't lag 1 frame */
1608         BKE_image_update_frame(bmain, sce->r.cfra);
1609         
1610         /* rebuild rigid body worlds before doing the actual frame update
1611          * this needs to be done on start frame but animation playback usually starts one frame later
1612          * we need to do it here to avoid rebuilding the world on every simulation change, which can be very expensive
1613          */
1614         scene_rebuild_rbw_recursive(sce, ctime);
1615
1616         sound_set_cfra(sce->r.cfra);
1617         
1618         /* clear animation overrides */
1619         /* XXX TODO... */
1620
1621         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set)
1622                 DAG_scene_relations_update(bmain, sce_iter);
1623
1624         /* flush recalc flags to dependencies, if we were only changing a frame
1625          * this would not be necessary, but if a user or a script has modified
1626          * some datablock before BKE_scene_update_tagged was called, we need the flush */
1627         DAG_ids_flush_tagged(bmain);
1628
1629         /* Following 2 functions are recursive
1630          * so don't call within 'scene_update_tagged_recursive' */
1631         DAG_scene_update_flags(bmain, sce, lay, true, do_invisible_flush);   // only stuff that moves or needs display still
1632
1633         BKE_mask_evaluate_all_masks(bmain, ctime, true);
1634
1635         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1636          * with an 'local' to 'macro' order of evaluation. This should ensure that
1637          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1638          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1639          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1640          */
1641         BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1642         /*...done with recursive funcs */
1643
1644         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1645          * when trying to find materials with drivers that need evaluating [#32017] 
1646          */
1647         BKE_main_id_tag_idcode(bmain, ID_MA, false);
1648         BKE_main_id_tag_idcode(bmain, ID_LA, false);
1649
1650         /* run rigidbody sim */
1651         /* NOTE: current position is so that rigidbody sim affects other objects, might change in the future */
1652         scene_do_rb_simulation_recursive(sce, ctime);
1653
1654         /* BKE_object_handle_update() on all objects, groups and sets */
1655         scene_update_tagged_recursive(eval_ctx, bmain, sce, sce);
1656         /* update sound system animation (TODO, move to depsgraph) */
1657         sound_update_scene(bmain, sce);
1658
1659         scene_depsgraph_hack(eval_ctx, sce, sce);
1660
1661         /* notify editors and python about recalc */
1662         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1663         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1664
1665         DAG_ids_check_recalc(bmain, sce, TRUE);
1666
1667         /* clear recalc flags */
1668         DAG_ids_clear_recalc(bmain);
1669
1670 #ifdef DETAILED_ANALYSIS_OUTPUT
1671         fprintf(stderr, "frame update start_time %f duration %f\n", start_time, PIL_check_seconds_timer() - start_time);
1672 #endif
1673 }
1674
1675 /* return default layer, also used to patch old files */
1676 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
1677 {
1678         SceneRenderLayer *srl;
1679
1680         if (!name)
1681                 name = DATA_("RenderLayer");
1682
1683         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1684         BLI_strncpy(srl->name, name, sizeof(srl->name));
1685         BLI_uniquename(&sce->r.layers, srl, DATA_("RenderLayer"), '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1686         BLI_addtail(&sce->r.layers, srl);
1687
1688         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1689         srl->lay = (1 << 20) - 1;
1690         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
1691         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
1692         srl->pass_alpha_threshold = 0.5f;
1693         BKE_freestyle_config_init(&srl->freestyleConfig);
1694
1695         return srl;
1696 }
1697
1698 bool BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
1699 {
1700         const int act = BLI_findindex(&scene->r.layers, srl);
1701         Scene *sce;
1702
1703         if (act == -1) {
1704                 return 0;
1705         }
1706         else if ( (scene->r.layers.first == scene->r.layers.last) &&
1707                   (scene->r.layers.first == srl))
1708         {
1709                 /* ensure 1 layer is kept */
1710                 return 0;
1711         }
1712
1713         BLI_remlink(&scene->r.layers, srl);
1714         MEM_freeN(srl);
1715
1716         scene->r.actlay = 0;
1717
1718         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1719                 if (sce->nodetree) {
1720                         bNode *node;
1721                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1722                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
1723                                         if (node->custom1 == act)
1724                                                 node->custom1 = 0;
1725                                         else if (node->custom1 > act)
1726                                                 node->custom1--;
1727                                 }
1728                         }
1729                 }
1730         }
1731
1732         return 1;
1733 }
1734
1735 /* render simplification */
1736
1737 int get_render_subsurf_level(RenderData *r, int lvl)
1738 {
1739         if (r->mode & R_SIMPLIFY)
1740                 return min_ii(r->simplify_subsurf, lvl);
1741         else
1742                 return lvl;
1743 }
1744
1745 int get_render_child_particle_number(RenderData *r, int num)
1746 {
1747         if (r->mode & R_SIMPLIFY)
1748                 return (int)(r->simplify_particles * num);
1749         else
1750                 return num;
1751 }
1752
1753 int get_render_shadow_samples(RenderData *r, int samples)
1754 {
1755         if ((r->mode & R_SIMPLIFY) && samples > 0)
1756                 return min_ii(r->simplify_shadowsamples, samples);
1757         else
1758                 return samples;
1759 }
1760
1761 float get_render_aosss_error(RenderData *r, float error)
1762 {
1763         if (r->mode & R_SIMPLIFY)
1764                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
1765         else
1766                 return error;
1767 }
1768
1769 /* helper function for the SETLOOPER macro */
1770 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1771 {
1772         if (base && base->next) {
1773                 /* common case, step to the next */
1774                 return base->next;
1775         }
1776         else if (base == NULL && (*sce_iter)->base.first) {
1777                 /* first time looping, return the scenes first base */
1778                 return (Base *)(*sce_iter)->base.first;
1779         }
1780         else {
1781                 /* reached the end, get the next base in the set */
1782                 while ((*sce_iter = (*sce_iter)->set)) {
1783                         base = (Base *)(*sce_iter)->base.first;
1784                         if (base) {
1785                                 return base;
1786                         }
1787                 }
1788         }
1789
1790         return NULL;
1791 }
1792
1793 bool BKE_scene_use_new_shading_nodes(Scene *scene)
1794 {
1795         RenderEngineType *type = RE_engines_find(scene->r.engine);
1796         return (type && type->flag & RE_USE_SHADING_NODES);
1797 }
1798
1799 void BKE_scene_base_flag_to_objects(struct Scene *scene)
1800 {
1801         Base *base = scene->base.first;
1802
1803         while (base) {
1804                 base->object->flag = base->flag;
1805                 base = base->next;
1806         }
1807 }
1808
1809 void BKE_scene_base_flag_from_objects(struct Scene *scene)
1810 {
1811         Base *base = scene->base.first;
1812
1813         while (base) {
1814                 base->flag = base->object->flag;
1815                 base = base->next;
1816         }
1817 }
1818
1819 void BKE_scene_disable_color_management(Scene *scene)
1820 {
1821         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1822         ColorManagedViewSettings *view_settings = &scene->view_settings;
1823         const char *view;
1824         const char *none_display_name;
1825
1826         none_display_name = IMB_colormanagement_display_get_none_name();
1827
1828         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
1829
1830         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1831
1832         if (view) {
1833                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1834         }
1835 }
1836
1837 bool BKE_scene_check_color_management_enabled(const Scene *scene)
1838 {
1839         return strcmp(scene->display_settings.display_device, "None") != 0;
1840 }
1841
1842 bool BKE_scene_check_rigidbody_active(const Scene *scene)
1843 {
1844         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1845 }
1846
1847 int BKE_render_num_threads(const RenderData *rd)
1848 {
1849         int threads;
1850
1851         /* override set from command line? */
1852         threads = BLI_system_num_threads_override_get();
1853
1854         if (threads > 0)
1855                 return threads;
1856
1857         /* fixed number of threads specified in scene? */
1858         if (rd->mode & R_FIXED_THREADS)
1859                 threads = rd->threads;
1860         else
1861                 threads = BLI_system_thread_count();
1862         
1863         return max_ii(threads, 1);
1864 }
1865
1866 int BKE_scene_num_threads(const Scene *scene)
1867 {
1868         return BKE_render_num_threads(&scene->r);
1869 }
1870