Merging r58266 through r58279 from trunk into soc-2013-depsgraph_mt
[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_node_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_rigidbody_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_sequence_types.h"
53
54 #include "BLI_math.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_utildefines.h"
57 #include "BLI_callbacks.h"
58 #include "BLI_string.h"
59 #include "BLI_threads.h"
60 #include "BLI_task.h"
61
62 #include "BLF_translation.h"
63
64 #include "BKE_anim.h"
65 #include "BKE_animsys.h"
66 #include "BKE_action.h"
67 #include "BKE_colortools.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_fcurve.h"
70 #include "BKE_freestyle.h"
71 #include "BKE_global.h"
72 #include "BKE_group.h"
73 #include "BKE_idprop.h"
74 #include "BKE_image.h"
75 #include "BKE_library.h"
76 #include "BKE_main.h"
77 #include "BKE_mask.h"
78 #include "BKE_node.h"
79 #include "BKE_object.h"
80 #include "BKE_paint.h"
81 #include "BKE_pointcache.h"
82 #include "BKE_rigidbody.h"
83 #include "BKE_scene.h"
84 #include "BKE_sequencer.h"
85 #include "BKE_sound.h"
86 #include "BKE_world.h"
87
88 #include "RE_engine.h"
89
90 #include "IMB_colormanagement.h"
91
92 //XXX #include "BIF_previewrender.h"
93 //XXX #include "BIF_editseq.h"
94
95 #ifdef WIN32
96 #else
97 #include <sys/time.h>
98 #endif
99
100 void free_avicodecdata(AviCodecData *acd)
101 {
102         if (acd) {
103                 if (acd->lpFormat) {
104                         MEM_freeN(acd->lpFormat);
105                         acd->lpFormat = NULL;
106                         acd->cbFormat = 0;
107                 }
108                 if (acd->lpParms) {
109                         MEM_freeN(acd->lpParms);
110                         acd->lpParms = NULL;
111                         acd->cbParms = 0;
112                 }
113         }
114 }
115
116 void free_qtcodecdata(QuicktimeCodecData *qcd)
117 {
118         if (qcd) {
119                 if (qcd->cdParms) {
120                         MEM_freeN(qcd->cdParms);
121                         qcd->cdParms = NULL;
122                         qcd->cdSize = 0;
123                 }
124         }
125 }
126
127 static void remove_sequencer_fcurves(Scene *sce)
128 {
129         AnimData *adt = BKE_animdata_from_id(&sce->id);
130
131         if (adt && adt->action) {
132                 FCurve *fcu, *nextfcu;
133                 
134                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
135                         nextfcu = fcu->next;
136                         
137                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
138                                 action_groups_remove_channel(adt->action, fcu);
139                                 free_fcurve(fcu);
140                         }
141                 }
142         }
143 }
144
145 Scene *BKE_scene_copy(Scene *sce, int type)
146 {
147         Scene *scen;
148         SceneRenderLayer *srl, *new_srl;
149         ToolSettings *ts;
150         Base *base, *obase;
151         
152         if (type == SCE_COPY_EMPTY) {
153                 ListBase lb;
154                 /* XXX. main should become an arg */
155                 scen = BKE_scene_add(G.main, sce->id.name + 2);
156                 
157                 lb = scen->r.layers;
158                 scen->r = sce->r;
159                 scen->r.layers = lb;
160                 scen->unit = sce->unit;
161                 scen->physics_settings = sce->physics_settings;
162                 scen->gm = sce->gm;
163                 scen->audio = sce->audio;
164
165                 MEM_freeN(scen->toolsettings);
166         }
167         else {
168                 scen = BKE_libblock_copy(&sce->id);
169                 BLI_duplicatelist(&(scen->base), &(sce->base));
170                 
171                 clear_id_newpoins();
172                 
173                 id_us_plus((ID *)scen->world);
174                 id_us_plus((ID *)scen->set);
175                 id_us_plus((ID *)scen->gm.dome.warptext);
176
177                 scen->ed = NULL;
178                 scen->theDag = NULL;
179                 scen->obedit = NULL;
180                 scen->stats = NULL;
181                 scen->fps_info = NULL;
182
183                 if (sce->rigidbody_world)
184                         scen->rigidbody_world = BKE_rigidbody_world_copy(sce->rigidbody_world);
185
186                 BLI_duplicatelist(&(scen->markers), &(sce->markers));
187                 BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
188                 BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
189                 BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
190
191                 if (sce->nodetree) {
192                         /* ID's are managed on both copy and switch */
193                         scen->nodetree = ntreeCopyTree(sce->nodetree);
194                         ntreeSwitchID(scen->nodetree, &sce->id, &scen->id);
195                 }
196
197                 obase = sce->base.first;
198                 base = scen->base.first;
199                 while (base) {
200                         id_us_plus(&base->object->id);
201                         if (obase == sce->basact) scen->basact = base;
202         
203                         obase = obase->next;
204                         base = base->next;
205                 }
206
207                 /* copy color management settings */
208                 BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings);
209                 BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings);
210                 BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings);
211
212                 BLI_strncpy(scen->sequencer_colorspace_settings.name, sce->sequencer_colorspace_settings.name,
213                             sizeof(scen->sequencer_colorspace_settings.name));
214
215                 /* remove animation used by sequencer */
216                 if (type != SCE_COPY_FULL)
217                         remove_sequencer_fcurves(scen);
218
219                 /* copy Freestyle settings */
220                 new_srl = scen->r.layers.first;
221                 for (srl = sce->r.layers.first; srl; srl = srl->next) {
222                         BKE_freestyle_config_copy(&new_srl->freestyleConfig, &srl->freestyleConfig);
223                         new_srl = new_srl->next;
224                 }
225         }
226
227         /* tool settings */
228         scen->toolsettings = MEM_dupallocN(sce->toolsettings);
229
230         ts = scen->toolsettings;
231         if (ts) {
232                 if (ts->vpaint) {
233                         ts->vpaint = MEM_dupallocN(ts->vpaint);
234                         ts->vpaint->paintcursor = NULL;
235                         ts->vpaint->vpaint_prev = NULL;
236                         ts->vpaint->wpaint_prev = NULL;
237                         BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint);
238                 }
239                 if (ts->wpaint) {
240                         ts->wpaint = MEM_dupallocN(ts->wpaint);
241                         ts->wpaint->paintcursor = NULL;
242                         ts->wpaint->vpaint_prev = NULL;
243                         ts->wpaint->wpaint_prev = NULL;
244                         BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint);
245                 }
246                 if (ts->sculpt) {
247                         ts->sculpt = MEM_dupallocN(ts->sculpt);
248                         BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint);
249                 }
250
251                 BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint);
252                 ts->imapaint.paintcursor = NULL;
253                 ts->particle.paintcursor = NULL;
254         }
255         
256         /* make a private copy of the avicodecdata */
257         if (sce->r.avicodecdata) {
258                 scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
259                 scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
260                 scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
261         }
262         
263         /* make a private copy of the qtcodecdata */
264         if (sce->r.qtcodecdata) {
265                 scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
266                 scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
267         }
268         
269         if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
270                 scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
271         }
272
273         /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
274          * are done outside of blenkernel with ED_objects_single_users! */
275
276         /*  camera */
277         if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
278                 ID_NEW(scen->camera);
279         }
280         
281         /* before scene copy */
282         sound_create_scene(scen);
283
284         /* world */
285         if (type == SCE_COPY_FULL) {
286                 BKE_copy_animdata_id_action((ID *)scen);
287                 if (scen->world) {
288                         id_us_plus((ID *)scen->world);
289                         scen->world = BKE_world_copy(scen->world);
290                         BKE_copy_animdata_id_action((ID *)scen->world);
291                 }
292
293                 if (sce->ed) {
294                         scen->ed = MEM_callocN(sizeof(Editing), "addseq");
295                         scen->ed->seqbasep = &scen->ed->seqbase;
296                         BKE_sequence_base_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL);
297                 }
298         }
299
300         return scen;
301 }
302
303 void BKE_scene_groups_relink(Scene *sce)
304 {
305         if (sce->rigidbody_world)
306                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
307 }
308
309 /* do not free scene itself */
310 void BKE_scene_free(Scene *sce)
311 {
312         Base *base;
313         SceneRenderLayer *srl;
314
315         /* check all sequences */
316         BKE_sequencer_clear_scene_in_allseqs(G.main, sce);
317
318         base = sce->base.first;
319         while (base) {
320                 base->object->id.us--;
321                 base = base->next;
322         }
323         /* do not free objects! */
324         
325         if (sce->gpd) {
326 #if 0   /* removed since this can be invalid memory when freeing everything */
327                 /* since the grease pencil data is freed before the scene.
328                  * since grease pencil data is not (yet?), shared between objects
329                  * its probably safe not to do this, some save and reload will free this. */
330                 sce->gpd->id.us--;
331 #endif
332                 sce->gpd = NULL;
333         }
334
335         BLI_freelistN(&sce->base);
336         BKE_sequencer_editing_free(sce);
337
338         BKE_free_animdata((ID *)sce);
339         BKE_keyingsets_free(&sce->keyingsets);
340         
341         if (sce->rigidbody_world)
342                 BKE_rigidbody_free_world(sce->rigidbody_world);
343         
344         if (sce->r.avicodecdata) {
345                 free_avicodecdata(sce->r.avicodecdata);
346                 MEM_freeN(sce->r.avicodecdata);
347                 sce->r.avicodecdata = NULL;
348         }
349         if (sce->r.qtcodecdata) {
350                 free_qtcodecdata(sce->r.qtcodecdata);
351                 MEM_freeN(sce->r.qtcodecdata);
352                 sce->r.qtcodecdata = NULL;
353         }
354         if (sce->r.ffcodecdata.properties) {
355                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
356                 MEM_freeN(sce->r.ffcodecdata.properties);
357                 sce->r.ffcodecdata.properties = NULL;
358         }
359         
360         for (srl = sce->r.layers.first; srl; srl = srl->next) {
361                 BKE_freestyle_config_free(&srl->freestyleConfig);
362         }
363         
364         BLI_freelistN(&sce->markers);
365         BLI_freelistN(&sce->transform_spaces);
366         BLI_freelistN(&sce->r.layers);
367         
368         if (sce->toolsettings) {
369                 if (sce->toolsettings->vpaint) {
370                         BKE_paint_free(&sce->toolsettings->vpaint->paint);
371                         MEM_freeN(sce->toolsettings->vpaint);
372                 }
373                 if (sce->toolsettings->wpaint) {
374                         BKE_paint_free(&sce->toolsettings->wpaint->paint);
375                         MEM_freeN(sce->toolsettings->wpaint);
376                 }
377                 if (sce->toolsettings->sculpt) {
378                         BKE_paint_free(&sce->toolsettings->sculpt->paint);
379                         MEM_freeN(sce->toolsettings->sculpt);
380                 }
381                 if (sce->toolsettings->uvsculpt) {
382                         BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
383                         MEM_freeN(sce->toolsettings->uvsculpt);
384                 }
385                 BKE_paint_free(&sce->toolsettings->imapaint.paint);
386
387                 MEM_freeN(sce->toolsettings);
388                 sce->toolsettings = NULL;
389         }
390         
391         DAG_scene_free(sce);
392         
393         if (sce->nodetree) {
394                 ntreeFreeTree(sce->nodetree);
395                 MEM_freeN(sce->nodetree);
396         }
397
398         if (sce->stats)
399                 MEM_freeN(sce->stats);
400         if (sce->fps_info)
401                 MEM_freeN(sce->fps_info);
402
403         sound_destroy_scene(sce);
404
405         BKE_color_managed_view_settings_free(&sce->view_settings);
406 }
407
408 Scene *BKE_scene_add(Main *bmain, const char *name)
409 {
410         Scene *sce;
411         ParticleEditSettings *pset;
412         int a;
413         const char *colorspace_name;
414
415         sce = BKE_libblock_alloc(&bmain->scene, ID_SCE, name);
416         sce->lay = sce->layact = 1;
417         
418         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
419         sce->r.cfra = 1;
420         sce->r.sfra = 1;
421         sce->r.efra = 250;
422         sce->r.frame_step = 1;
423         sce->r.xsch = 1920;
424         sce->r.ysch = 1080;
425         sce->r.xasp = 1;
426         sce->r.yasp = 1;
427         sce->r.tilex = 256;
428         sce->r.tiley = 256;
429         sce->r.mblur_samples = 1;
430         sce->r.filtertype = R_FILTER_MITCH;
431         sce->r.size = 50;
432
433         sce->r.im_format.planes = R_IMF_PLANES_RGB;
434         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
435         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
436         sce->r.im_format.quality = 90;
437         sce->r.im_format.compress = 90;
438
439         sce->r.displaymode = R_OUTPUT_AREA;
440         sce->r.framapto = 100;
441         sce->r.images = 100;
442         sce->r.framelen = 1.0;
443         sce->r.blurfac = 0.5;
444         sce->r.frs_sec = 24;
445         sce->r.frs_sec_base = 1;
446         sce->r.edgeint = 10;
447         sce->r.ocres = 128;
448
449         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
450          *            images would look in the same way as in current blender
451          *
452          *            perhaps at some point should be completely deprecated?
453          */
454         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
455
456         sce->r.gauss = 1.0;
457         
458         /* deprecated but keep for upwards compat */
459         sce->r.postgamma = 1.0;
460         sce->r.posthue = 0.0;
461         sce->r.postsat = 1.0;
462
463         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
464         sce->r.bake_filter = 16;
465         sce->r.bake_osa = 5;
466         sce->r.bake_flag = R_BAKE_CLEAR;
467         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
468         sce->r.bake_samples = 256;
469         sce->r.bake_biasdist = 0.001;
470         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
471         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME;
472         sce->r.stamp_font_id = 12;
473         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
474         sce->r.fg_stamp[3] = 1.0f;
475         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
476         sce->r.bg_stamp[3] = 0.25f;
477         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
478
479         sce->r.seq_prev_type = OB_SOLID;
480         sce->r.seq_rend_type = OB_SOLID;
481         sce->r.seq_flag = R_SEQ_GL_PREV;
482
483         sce->r.threads = 1;
484
485         sce->r.simplify_subsurf = 6;
486         sce->r.simplify_particles = 1.0f;
487         sce->r.simplify_shadowsamples = 16;
488         sce->r.simplify_aosss = 1.0f;
489
490         sce->r.border.xmin = 0.0f;
491         sce->r.border.ymin = 0.0f;
492         sce->r.border.xmax = 1.0f;
493         sce->r.border.ymax = 1.0f;
494         
495         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
496         sce->toolsettings->cornertype = 1;
497         sce->toolsettings->degr = 90; 
498         sce->toolsettings->step = 9;
499         sce->toolsettings->turn = 1;
500         sce->toolsettings->extr_offs = 1; 
501         sce->toolsettings->doublimit = 0.001;
502         sce->toolsettings->segments = 32;
503         sce->toolsettings->rings = 32;
504         sce->toolsettings->vertices = 32;
505         sce->toolsettings->uvcalc_radius = 1.0f;
506         sce->toolsettings->uvcalc_cubesize = 1.0f;
507         sce->toolsettings->uvcalc_mapdir = 1;
508         sce->toolsettings->uvcalc_mapalign = 1;
509         sce->toolsettings->uvcalc_margin = 0.001f;
510         sce->toolsettings->unwrapper = 1;
511         sce->toolsettings->select_thresh = 0.01f;
512         sce->toolsettings->jointrilimit = 0.8f;
513
514         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
515         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
516         sce->toolsettings->normalsize = 0.1;
517         sce->toolsettings->autokey_mode = U.autokey_mode;
518
519         sce->toolsettings->skgen_resolution = 100;
520         sce->toolsettings->skgen_threshold_internal     = 0.01f;
521         sce->toolsettings->skgen_threshold_external     = 0.01f;
522         sce->toolsettings->skgen_angle_limit            = 45.0f;
523         sce->toolsettings->skgen_length_ratio           = 1.3f;
524         sce->toolsettings->skgen_length_limit           = 1.5f;
525         sce->toolsettings->skgen_correlation_limit      = 0.98f;
526         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
527         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
528         sce->toolsettings->skgen_postpro_passes = 1;
529         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
530         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
531         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
532         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
533
534         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
535         sce->toolsettings->statvis.overhang_min = 0;
536         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
537         sce->toolsettings->statvis.thickness_max = 0.1f;
538         sce->toolsettings->statvis.thickness_samples = 1;
539         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
540         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
541
542         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
543         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
544
545         sce->toolsettings->proportional_size = 1.0f;
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 void BKE_scene_unlink(Main *bmain, Scene *sce, Scene *newsce)
724 {
725         Scene *sce1;
726         bScreen *sc;
727
728         /* check all sets */
729         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next)
730                 if (sce1->set == sce)
731                         sce1->set = NULL;
732         
733         /* check render layer nodes in other scenes */
734         clear_scene_in_nodes(bmain, sce);
735         
736         /* al screens */
737         for (sc = bmain->screen.first; sc; sc = sc->id.next)
738                 if (sc->scene == sce)
739                         sc->scene = newsce;
740
741         BKE_libblock_free(&bmain->scene, sce);
742 }
743
744 /* used by metaballs
745  * doesn't return the original duplicated object, only dupli's
746  */
747 int BKE_scene_base_iter_next(SceneBaseIter *iter, Scene **scene, int val, Base **base, Object **ob)
748 {
749         static int in_next_object = 0;
750         int run_again = 1;
751         
752         /* init */
753         if (val == 0) {
754                 iter->fase = F_START;
755                 iter->dupob = NULL;
756                 iter->duplilist = NULL;
757                 
758                 /* XXX particle systems with metas+dupligroups call this recursively */
759                 /* see bug #18725 */
760                 if (in_next_object) {
761                         printf("ERROR: Metaball generation called recursively, not supported\n");
762                         
763                         return F_ERROR;
764                 }
765         }
766         else {
767                 in_next_object = 1;
768                 
769                 /* run_again is set when a duplilist has been ended */
770                 while (run_again) {
771                         run_again = 0;
772
773                         /* the first base */
774                         if (iter->fase == F_START) {
775                                 *base = (*scene)->base.first;
776                                 if (*base) {
777                                         *ob = (*base)->object;
778                                         iter->fase = F_SCENE;
779                                 }
780                                 else {
781                                         /* exception: empty scene */
782                                         while ((*scene)->set) {
783                                                 (*scene) = (*scene)->set;
784                                                 if ((*scene)->base.first) {
785                                                         *base = (*scene)->base.first;
786                                                         *ob = (*base)->object;
787                                                         iter->fase = F_SCENE;
788                                                         break;
789                                                 }
790                                         }
791                                 }
792                         }
793                         else {
794                                 if (*base && iter->fase != F_DUPLI) {
795                                         *base = (*base)->next;
796                                         if (*base) {
797                                                 *ob = (*base)->object;
798                                         }
799                                         else {
800                                                 if (iter->fase == F_SCENE) {
801                                                         /* (*scene) is finished, now do the set */
802                                                         while ((*scene)->set) {
803                                                                 (*scene) = (*scene)->set;
804                                                                 if ((*scene)->base.first) {
805                                                                         *base = (*scene)->base.first;
806                                                                         *ob = (*base)->object;
807                                                                         break;
808                                                                 }
809                                                         }
810                                                 }
811                                         }
812                                 }
813                         }
814                         
815                         if (*base == NULL) {
816                                 iter->fase = F_START;
817                         }
818                         else {
819                                 if (iter->fase != F_DUPLI) {
820                                         if ( (*base)->object->transflag & OB_DUPLI) {
821                                                 /* groups cannot be duplicated for mballs yet, 
822                                                  * this enters eternal loop because of 
823                                                  * makeDispListMBall getting called inside of group_duplilist */
824                                                 if ((*base)->object->dup_group == NULL) {
825                                                         iter->duplilist = object_duplilist((*scene), (*base)->object, FALSE);
826                                                         
827                                                         iter->dupob = iter->duplilist->first;
828
829                                                         if (!iter->dupob)
830                                                                 free_object_duplilist(iter->duplilist);
831                                                 }
832                                         }
833                                 }
834                                 /* handle dupli's */
835                                 if (iter->dupob) {
836                                         
837                                         copy_m4_m4(iter->dupob->ob->obmat, iter->dupob->mat);
838                                         
839                                         (*base)->flag |= OB_FROMDUPLI;
840                                         *ob = iter->dupob->ob;
841                                         iter->fase = F_DUPLI;
842                                         
843                                         iter->dupob = iter->dupob->next;
844                                 }
845                                 else if (iter->fase == F_DUPLI) {
846                                         iter->fase = F_SCENE;
847                                         (*base)->flag &= ~OB_FROMDUPLI;
848                                         
849                                         for (iter->dupob = iter->duplilist->first; iter->dupob; iter->dupob = iter->dupob->next) {
850                                                 copy_m4_m4(iter->dupob->ob->obmat, iter->dupob->omat);
851                                         }
852                                         
853                                         free_object_duplilist(iter->duplilist);
854                                         iter->duplilist = NULL;
855                                         run_again = 1;
856                                 }
857                         }
858                 }
859         }
860
861 #if 0
862         if (ob && *ob) {
863                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
864         }
865 #endif
866
867         /* reset recursion test */
868         in_next_object = 0;
869         
870         return iter->fase;
871 }
872
873 Object *BKE_scene_camera_find(Scene *sc)
874 {
875         Base *base;
876         
877         for (base = sc->base.first; base; base = base->next)
878                 if (base->object->type == OB_CAMERA)
879                         return base->object;
880
881         return NULL;
882 }
883
884 #ifdef DURIAN_CAMERA_SWITCH
885 Object *BKE_scene_camera_switch_find(Scene *scene)
886 {
887         TimeMarker *m;
888         int cfra = scene->r.cfra;
889         int frame = -(MAXFRAME + 1);
890         Object *camera = NULL;
891
892         for (m = scene->markers.first; m; m = m->next) {
893                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0 && (m->frame <= cfra) && (m->frame > frame)) {
894                         camera = m->camera;
895                         frame = m->frame;
896
897                         if (frame == cfra)
898                                 break;
899
900                 }
901         }
902         return camera;
903 }
904 #endif
905
906 int BKE_scene_camera_switch_update(Scene *scene)
907 {
908 #ifdef DURIAN_CAMERA_SWITCH
909         Object *camera = BKE_scene_camera_switch_find(scene);
910         if (camera) {
911                 scene->camera = camera;
912                 return 1;
913         }
914 #else
915         (void)scene;
916 #endif
917         return 0;
918 }
919
920 char *BKE_scene_find_marker_name(Scene *scene, int frame)
921 {
922         ListBase *markers = &scene->markers;
923         TimeMarker *m1, *m2;
924
925         /* search through markers for match */
926         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
927                 if (m1->frame == frame)
928                         return m1->name;
929
930                 if (m1 == m2)
931                         break;
932
933                 if (m2->frame == frame)
934                         return m2->name;
935         }
936
937         return NULL;
938 }
939
940 /* return the current marker for this frame,
941  * we can have more than 1 marker per frame, this just returns the first :/ */
942 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
943 {
944         TimeMarker *marker, *best_marker = NULL;
945         int best_frame = -MAXFRAME * 2;
946         for (marker = scene->markers.first; marker; marker = marker->next) {
947                 if (marker->frame == frame) {
948                         return marker->name;
949                 }
950
951                 if (marker->frame > best_frame && marker->frame < frame) {
952                         best_marker = marker;
953                         best_frame = marker->frame;
954                 }
955         }
956
957         return best_marker ? best_marker->name : NULL;
958 }
959
960
961 Base *BKE_scene_base_add(Scene *sce, Object *ob)
962 {
963         Base *b = MEM_callocN(sizeof(*b), "BKE_scene_base_add");
964         BLI_addhead(&sce->base, b);
965
966         b->object = ob;
967         b->flag = ob->flag;
968         b->lay = ob->lay;
969
970         return b;
971 }
972
973 void BKE_scene_base_unlink(Scene *sce, Base *base)
974 {
975         /* remove rigid body constraint from world before removing object */
976         if (base->object->rigidbody_constraint)
977                 BKE_rigidbody_remove_constraint(sce, base->object);
978         /* remove rigid body object from world before removing object */
979         if (base->object->rigidbody_object)
980                 BKE_rigidbody_remove_object(sce, base->object);
981         
982         BLI_remlink(&sce->base, base);
983 }
984
985 void BKE_scene_base_deselect_all(Scene *sce)
986 {
987         Base *b;
988
989         for (b = sce->base.first; b; b = b->next) {
990                 b->flag &= ~SELECT;
991                 b->object->flag = b->flag;
992         }
993 }
994
995 void BKE_scene_base_select(Scene *sce, Base *selbase)
996 {
997         selbase->flag |= SELECT;
998         selbase->object->flag = selbase->flag;
999
1000         sce->basact = selbase;
1001 }
1002
1003 /* checks for cycle, returns 1 if it's all OK */
1004 int BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1005 {
1006         Scene *scene;
1007         int a, totscene;
1008         
1009         if (sce->set == NULL) return 1;
1010         
1011         totscene = 0;
1012         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1013                 totscene++;
1014         
1015         for (a = 0, scene = sce; scene->set; scene = scene->set, a++) {
1016                 /* more iterations than scenes means we have a cycle */
1017                 if (a > totscene) {
1018                         /* the tested scene gets zero'ed, that's typically current scene */
1019                         sce->set = NULL;
1020                         return 0;
1021                 }
1022         }
1023
1024         return 1;
1025 }
1026
1027 /* This function is needed to cope with fractional frames - including two Blender rendering features
1028  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1029  */
1030 float BKE_scene_frame_get(Scene *scene)
1031 {
1032         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1033 }
1034
1035 /* This function is used to obtain arbitrary fractional frames */
1036 float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame)
1037 {
1038         float ctime = frame;
1039         ctime += scene->r.subframe;
1040         ctime *= scene->r.framelen;
1041         
1042         return ctime;
1043 }
1044
1045 /**
1046  * Sets the frame int/float components.
1047  */
1048 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1049 {
1050         double intpart;
1051         scene->r.subframe = modf(cfra, &intpart);
1052         scene->r.cfra = (int)intpart;
1053
1054         if (cfra < 0.0) {
1055                 scene->r.cfra -= 1;
1056                 scene->r.subframe = 1.0f + scene->r.subframe;
1057         }
1058 }
1059
1060 /* drivers support/hacks 
1061  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
1062  *      - these are always run since the depsgraph can't handle non-object data
1063  *      - these happen after objects are all done so that we can read in their final transform values,
1064  *        though this means that objects can't refer to scene info for guidance...
1065  */
1066 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
1067 {
1068         float ctime = BKE_scene_frame_get(scene);
1069         
1070         /* scene itself */
1071         if (scene->adt && scene->adt->drivers.first) {
1072                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
1073         }
1074
1075         /* world */
1076         /* TODO: what about world textures? but then those have nodes too... */
1077         if (scene->world) {
1078                 ID *wid = (ID *)scene->world;
1079                 AnimData *adt = BKE_animdata_from_id(wid);
1080                 
1081                 if (adt && adt->drivers.first)
1082                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
1083         }
1084         
1085         /* nodes */
1086         if (scene->nodetree) {
1087                 ID *nid = (ID *)scene->nodetree;
1088                 AnimData *adt = BKE_animdata_from_id(nid);
1089                 
1090                 if (adt && adt->drivers.first)
1091                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1092         }
1093
1094         /* world nodes */
1095         if (scene->world && scene->world->nodetree) {
1096                 ID *nid = (ID *)scene->world->nodetree;
1097                 AnimData *adt = BKE_animdata_from_id(nid);
1098                 
1099                 if (adt && adt->drivers.first)
1100                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1101         }
1102 }
1103
1104 /* deps hack - do extra recalcs at end */
1105 static void scene_depsgraph_hack(Scene *scene, Scene *scene_parent)
1106 {
1107         Base *base;
1108                 
1109         scene->customdata_mask = scene_parent->customdata_mask;
1110         
1111         /* sets first, we allow per definition current scene to have
1112          * dependencies on sets, but not the other way around. */
1113         if (scene->set)
1114                 scene_depsgraph_hack(scene->set, scene_parent);
1115         
1116         for (base = scene->base.first; base; base = base->next) {
1117                 Object *ob = base->object;
1118                 
1119                 if (ob->depsflag) {
1120                         int recalc = 0;
1121                         // printf("depshack %s\n", ob->id.name + 2);
1122                         
1123                         if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC)
1124                                 recalc |= OB_RECALC_OB;
1125                         if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC)
1126                                 recalc |= OB_RECALC_DATA;
1127                         
1128                         ob->recalc |= recalc;
1129                         BKE_object_handle_update(scene_parent, ob);
1130                         
1131                         if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1132                                 GroupObject *go;
1133                                 
1134                                 for (go = ob->dup_group->gobject.first; go; go = go->next) {
1135                                         if (go->ob)
1136                                                 go->ob->recalc |= recalc;
1137                                 }
1138                                 BKE_group_handle_recalc_and_update(scene_parent, ob, ob->dup_group);
1139                         }
1140                 }
1141         }
1142
1143 }
1144
1145 static void scene_rebuild_rbw_recursive(Scene *scene, float ctime)
1146 {
1147         if (scene->set)
1148                 scene_rebuild_rbw_recursive(scene->set, ctime);
1149
1150         if (BKE_scene_check_rigidbody_active(scene))
1151                 BKE_rigidbody_rebuild_world(scene, ctime);
1152 }
1153
1154 static void scene_do_rb_simulation_recursive(Scene *scene, float ctime)
1155 {
1156         if (scene->set)
1157                 scene_do_rb_simulation_recursive(scene->set, ctime);
1158
1159         if (BKE_scene_check_rigidbody_active(scene))
1160                 BKE_rigidbody_do_simulation(scene, ctime);
1161 }
1162
1163 typedef struct ThreadedObjectUpdateState {
1164         Scene *scene;
1165         Scene *scene_parent;
1166         SpinLock lock;
1167 } ThreadedObjectUpdateState;
1168
1169 static void scene_update_object_add_task(void *node, void *user_data);
1170
1171 static void scene_update_all_bases(Scene *scene, Scene *scene_parent)
1172 {
1173         Base *base;
1174
1175         for (base = scene->base.first; base; base = base->next) {
1176                 Object *object = base->object;
1177
1178                 BKE_object_handle_update_ex(scene_parent, object, scene->rigidbody_world);
1179
1180                 if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1181                         BKE_group_handle_recalc_and_update(scene_parent, object, object->dup_group);
1182
1183                 /* always update layer, so that animating layers works (joshua july 2010) */
1184                 /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes
1185                  * (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */
1186                 // base->lay = ob->lay;
1187         }
1188 }
1189
1190 static void scene_update_object_func(TaskPool *pool, void *taskdata, int threadid)
1191 {
1192 #define PRINT if (G.debug & G_DEBUG) printf
1193
1194         ThreadedObjectUpdateState *state = (ThreadedObjectUpdateState *) BLI_task_pool_userdata(pool);
1195         void *node = taskdata;
1196         Object *object = DAG_threaded_update_get_node_object(node);
1197         Scene *scene = state->scene;
1198         Scene *scene_parent = state->scene_parent;
1199
1200         if (object) {
1201                 PRINT("Thread %d: update object %s\n", threadid, object->id.name);
1202
1203                 /* We only update object itself here, dupli-group will be updated
1204                  * separately from main thread because of we've got no idea about
1205                  * dependnecies inside the group.
1206                  */
1207                 BKE_object_handle_update_ex(scene_parent, object, scene->rigidbody_world);
1208         }
1209         else {
1210                 PRINT("Threda %d: update node %s\n", threadid,
1211                         DAG_threaded_update_get_node_name(node));
1212         }
1213
1214         BLI_spin_lock(&state->lock);
1215         /* Update will decrease child's valency and schedule child with zero valency. */
1216         DAG_threaded_update_handle_node_updated(node,scene_update_object_add_task, pool);
1217         BLI_spin_unlock(&state->lock);
1218
1219 #undef PRINT
1220 }
1221
1222 static void scene_update_object_add_task(void *node, void *user_data)
1223 {
1224         TaskPool *task_pool = user_data;
1225
1226         BLI_task_pool_push(task_pool, scene_update_object_func, node, false, TASK_PRIORITY_LOW);
1227 }
1228
1229 static void scene_update_objects_threaded(Scene *scene, Scene *scene_parent)
1230 {
1231         TaskScheduler *task_scheduler;
1232         TaskPool *task_pool;
1233         ThreadedObjectUpdateState state;
1234         int tot_thread = BLI_system_thread_count();
1235
1236         if (tot_thread == 1) {
1237                 /* If only one thread is possible we don't bother self with
1238                  * task pool, which would be an overhead in cas e of single
1239                  * CPU core.
1240                  */
1241                 scene_update_all_bases(scene, scene_parent);
1242                 return;
1243         }
1244
1245         /* Ensure malloc will go go fine from threads,
1246          * this is needed because we could be in main thread here
1247          * and malloc could be non-threda safe at this point because
1248          * no other jobs are running.
1249          */
1250         BLI_begin_threaded_malloc();
1251
1252         /* XXX: Releasing DrawObject is not thread safe, but adding lock
1253          *      around it is gonna to harm even more. So for now let's
1254          *      free all caches from main thread.
1255          *
1256          * TODO(sergey): Making DrawObject thread-safe is a nice task on
1257          *               it's own and it'll also make it possible to remove
1258          *               this hack.
1259          */
1260         {
1261                 Base *base;
1262                 for (base = scene->base.first; base; base = base->next) {
1263                         Object *ob = base->object;
1264
1265                         if (ob->recalc & OB_RECALC_ALL) {
1266                                 BKE_object_free_derived_caches(ob);
1267
1268                                 if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1269                                         GroupObject *go;
1270                                         for (go = ob->dup_group->gobject.first; go; go = go->next) {
1271                                                 if (go->ob && go->ob->recalc) {
1272                                                         BKE_object_free_derived_caches(go->ob);
1273                                                 }
1274                                         }
1275                                 }
1276                         }
1277                 }
1278         }
1279
1280         state.scene = scene;
1281         state.scene_parent = scene_parent;
1282         BLI_spin_init(&state.lock);
1283
1284         task_scheduler = BLI_task_scheduler_create(tot_thread);
1285         task_pool = BLI_task_pool_create(task_scheduler, &state);
1286
1287         /* Initialize run-time data in the graph needed for traversing it
1288          * from multiple threads.
1289          *
1290          * This will mark DAG nodes as object/non-object and will calculate
1291          * "valency" of nodes (which is how many non-updated parents node
1292          * have, which helps a lot checking whether node could be scheduled
1293          * already or not).
1294          */
1295         DAG_threaded_update_begin(scene);
1296
1297         /* Put all nodes which are already ready for schedule to the task pool.
1298          * usually its just a Scene node.
1299          *
1300          * We do lock here so no tthreads will start updating nodes valency
1301          * while we're still fillign the queue in. Otherwise it's possible
1302          * to run into situations when the same task is adding twice to the
1303          * queue due to non-safe nature of function below.
1304          */
1305         BLI_spin_lock(&state.lock);
1306         DAG_threaded_update_foreach_ready_node(scene, scene_update_object_add_task, task_pool);
1307         BLI_spin_unlock(&state.lock);
1308
1309         /* work and wait until tasks are done */
1310         BLI_task_pool_work_and_wait(task_pool);
1311
1312         /* free */
1313         BLI_task_pool_free(task_pool);
1314         BLI_task_scheduler_free(task_scheduler);
1315
1316         BLI_end_threaded_malloc();
1317
1318         BLI_spin_end(&state.lock);
1319
1320         /* XXX: Weak, very weak!
1321          *
1322          * We update dupligroups in single thread! :S
1323          *
1324          * This is because we've got absolutely no idea about dependencies
1325          * inside the group and we only know order of objects in which we
1326          * need to perform objects update.
1327          *
1328          * We even can not update different groups in different threads,
1329          * because groups could share the objects and detecting whether
1330          * object is updating in multiple threads is not so much easy.
1331          *
1332          * This is solvable with local group dependency graph or expanding
1333          * current dependency graph to be aware of dependencies inside
1334          * groups.
1335          *
1336          * P.S. Objects from the dup_group are very much likely in scene's
1337          *      dependency graph and were alreayd updated in threaded tasks
1338          *      scheduler already.
1339          *
1340          *      So objects from the dupli_groups are likely don't have
1341          *      OB_RECALC_ALL flag here, but it seems they still do have
1342          *      non-zero recalc flags, and here we make sure things are
1343          *      100% by calling BKE_group_handle_recalc_and_update.
1344          */
1345         {
1346                 Base *base;
1347                 for (base = scene->base.first; base; base = base->next) {
1348                         Object *object = base->object;
1349
1350                         if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1351                                 BKE_group_handle_recalc_and_update(scene_parent, object, object->dup_group);
1352                 }
1353         }
1354 }
1355
1356 static void scene_update_objects(Scene *scene, Scene *scene_parent)
1357 {
1358         Base *base;
1359         int update_count = 0;
1360
1361         /* Optimization thing: don't do threads if no modifier
1362          * stack need to be evaluated.
1363          */
1364         for (base = scene->base.first; base; base = base->next) {
1365                 Object *ob = base->object;
1366
1367                 if (ob->recalc & OB_RECALC_ALL) {
1368                         update_count++;
1369                 }
1370         }
1371
1372         if (update_count > 1) {
1373                 scene_update_objects_threaded(scene, scene_parent);
1374         }
1375         else {
1376                 scene_update_all_bases(scene, scene_parent);
1377         }
1378 }
1379
1380 static void scene_update_tagged_recursive(Main *bmain, Scene *scene, Scene *scene_parent)
1381 {
1382         scene->customdata_mask = scene_parent->customdata_mask;
1383
1384         /* sets first, we allow per definition current scene to have
1385          * dependencies on sets, but not the other way around. */
1386         if (scene->set)
1387                 scene_update_tagged_recursive(bmain, scene->set, scene_parent);
1388
1389         /* scene objects */
1390         scene_update_objects(scene, scene_parent);
1391
1392         /* scene drivers... */
1393         scene_update_drivers(bmain, scene);
1394
1395         /* update sound system animation */
1396         sound_update_scene(scene);
1397
1398         /* update masking curves */
1399         BKE_mask_update_scene(bmain, scene);
1400         
1401 }
1402
1403 /* this is called in main loop, doing tagged updates before redraw */
1404 void BKE_scene_update_tagged(Main *bmain, Scene *scene)
1405 {
1406         Scene *sce_iter;
1407         
1408         /* keep this first */
1409         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1410
1411         /* (re-)build dependency graph if needed */
1412         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
1413                 DAG_scene_relations_update(bmain, sce_iter);
1414
1415         /* flush recalc flags to dependencies */
1416         DAG_ids_flush_tagged(bmain);
1417
1418         /* removed calls to quick_cache, see pointcache.c */
1419         
1420         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1421          * when trying to find materials with drivers that need evaluating [#32017] 
1422          */
1423         tag_main_idcode(bmain, ID_MA, FALSE);
1424         tag_main_idcode(bmain, ID_LA, FALSE);
1425
1426         /* update all objects: drivers, matrices, displists, etc. flags set
1427          * by depgraph or manual, no layer check here, gets correct flushed
1428          *
1429          * in the future this should handle updates for all datablocks, not
1430          * only objects and scenes. - brecht */
1431         scene_update_tagged_recursive(bmain, scene, scene);
1432
1433         /* extra call here to recalc scene animation (for sequencer) */
1434         {
1435                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1436                 float ctime = BKE_scene_frame_get(scene);
1437                 
1438                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1439                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1440         }
1441         
1442         /* notify editors and python about recalc */
1443         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1444         DAG_ids_check_recalc(bmain, scene, FALSE);
1445
1446         /* clear recalc flags */
1447         DAG_ids_clear_recalc(bmain);
1448 }
1449
1450 /* applies changes right away, does all sets too */
1451 void BKE_scene_update_for_newframe(Main *bmain, Scene *sce, unsigned int lay)
1452 {
1453         float ctime = BKE_scene_frame_get(sce);
1454         Scene *sce_iter;
1455
1456         /* keep this first */
1457         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1458         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1459
1460         /* update animated image textures for particles, modifiers, gpu, etc,
1461          * call this at the start so modifiers with textures don't lag 1 frame */
1462         BKE_image_update_frame(bmain, sce->r.cfra);
1463         
1464         /* rebuild rigid body worlds before doing the actual frame update
1465          * this needs to be done on start frame but animation playback usually starts one frame later
1466          * we need to do it here to avoid rebuilding the world on every simulation change, which can be very expensive
1467          */
1468         scene_rebuild_rbw_recursive(sce, ctime);
1469
1470         sound_set_cfra(sce->r.cfra);
1471         
1472         /* clear animation overrides */
1473         /* XXX TODO... */
1474
1475         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set)
1476                 DAG_scene_relations_update(bmain, sce_iter);
1477
1478         /* flush recalc flags to dependencies, if we were only changing a frame
1479          * this would not be necessary, but if a user or a script has modified
1480          * some datablock before BKE_scene_update_tagged was called, we need the flush */
1481         DAG_ids_flush_tagged(bmain);
1482
1483         /* Following 2 functions are recursive
1484          * so don't call within 'scene_update_tagged_recursive' */
1485         DAG_scene_update_flags(bmain, sce, lay, TRUE);   // only stuff that moves or needs display still
1486
1487         BKE_mask_evaluate_all_masks(bmain, ctime, TRUE);
1488
1489         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1490          * with an 'local' to 'macro' order of evaluation. This should ensure that
1491          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1492          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1493          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1494          */
1495         BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1496         /*...done with recursive funcs */
1497
1498         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later 
1499          * when trying to find materials with drivers that need evaluating [#32017] 
1500          */
1501         tag_main_idcode(bmain, ID_MA, FALSE);
1502         tag_main_idcode(bmain, ID_LA, FALSE);
1503
1504         /* run rigidbody sim */
1505         /* NOTE: current position is so that rigidbody sim affects other objects, might change in the future */
1506         scene_do_rb_simulation_recursive(sce, ctime);
1507
1508         /* BKE_object_handle_update() on all objects, groups and sets */
1509         scene_update_tagged_recursive(bmain, sce, sce);
1510
1511         scene_depsgraph_hack(sce, sce);
1512
1513         /* notify editors and python about recalc */
1514         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1515         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1516
1517         DAG_ids_check_recalc(bmain, sce, TRUE);
1518
1519         /* clear recalc flags */
1520         DAG_ids_clear_recalc(bmain);
1521 }
1522
1523 /* return default layer, also used to patch old files */
1524 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
1525 {
1526         SceneRenderLayer *srl;
1527
1528         if (!name)
1529                 name = DATA_("RenderLayer");
1530
1531         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1532         BLI_strncpy(srl->name, name, sizeof(srl->name));
1533         BLI_uniquename(&sce->r.layers, srl, DATA_("RenderLayer"), '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1534         BLI_addtail(&sce->r.layers, srl);
1535
1536         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1537         srl->lay = (1 << 20) - 1;
1538         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
1539         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
1540         BKE_freestyle_config_init(&srl->freestyleConfig);
1541
1542         return srl;
1543 }
1544
1545 int BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
1546 {
1547         const int act = BLI_findindex(&scene->r.layers, srl);
1548         Scene *sce;
1549
1550         if (act == -1) {
1551                 return 0;
1552         }
1553         else if ( (scene->r.layers.first == scene->r.layers.last) &&
1554                   (scene->r.layers.first == srl))
1555         {
1556                 /* ensure 1 layer is kept */
1557                 return 0;
1558         }
1559
1560         BLI_remlink(&scene->r.layers, srl);
1561         MEM_freeN(srl);
1562
1563         scene->r.actlay = 0;
1564
1565         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1566                 if (sce->nodetree) {
1567                         bNode *node;
1568                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1569                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
1570                                         if (node->custom1 == act)
1571                                                 node->custom1 = 0;
1572                                         else if (node->custom1 > act)
1573                                                 node->custom1--;
1574                                 }
1575                         }
1576                 }
1577         }
1578
1579         return 1;
1580 }
1581
1582 /* render simplification */
1583
1584 int get_render_subsurf_level(RenderData *r, int lvl)
1585 {
1586         if (r->mode & R_SIMPLIFY)
1587                 return min_ii(r->simplify_subsurf, lvl);
1588         else
1589                 return lvl;
1590 }
1591
1592 int get_render_child_particle_number(RenderData *r, int num)
1593 {
1594         if (r->mode & R_SIMPLIFY)
1595                 return (int)(r->simplify_particles * num);
1596         else
1597                 return num;
1598 }
1599
1600 int get_render_shadow_samples(RenderData *r, int samples)
1601 {
1602         if ((r->mode & R_SIMPLIFY) && samples > 0)
1603                 return min_ii(r->simplify_shadowsamples, samples);
1604         else
1605                 return samples;
1606 }
1607
1608 float get_render_aosss_error(RenderData *r, float error)
1609 {
1610         if (r->mode & R_SIMPLIFY)
1611                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
1612         else
1613                 return error;
1614 }
1615
1616 /* helper function for the SETLOOPER macro */
1617 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1618 {
1619         if (base && base->next) {
1620                 /* common case, step to the next */
1621                 return base->next;
1622         }
1623         else if (base == NULL && (*sce_iter)->base.first) {
1624                 /* first time looping, return the scenes first base */
1625                 return (Base *)(*sce_iter)->base.first;
1626         }
1627         else {
1628                 /* reached the end, get the next base in the set */
1629                 while ((*sce_iter = (*sce_iter)->set)) {
1630                         base = (Base *)(*sce_iter)->base.first;
1631                         if (base) {
1632                                 return base;
1633                         }
1634                 }
1635         }
1636
1637         return NULL;
1638 }
1639
1640 int BKE_scene_use_new_shading_nodes(Scene *scene)
1641 {
1642         RenderEngineType *type = RE_engines_find(scene->r.engine);
1643         return (type && type->flag & RE_USE_SHADING_NODES);
1644 }
1645
1646 void BKE_scene_base_flag_to_objects(struct Scene *scene)
1647 {
1648         Base *base = scene->base.first;
1649
1650         while (base) {
1651                 base->object->flag = base->flag;
1652                 base = base->next;
1653         }
1654 }
1655
1656 void BKE_scene_base_flag_from_objects(struct Scene *scene)
1657 {
1658         Base *base = scene->base.first;
1659
1660         while (base) {
1661                 base->flag = base->object->flag;
1662                 base = base->next;
1663         }
1664 }
1665
1666 void BKE_scene_disable_color_management(Scene *scene)
1667 {
1668         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
1669         ColorManagedViewSettings *view_settings = &scene->view_settings;
1670         const char *view;
1671         const char *none_display_name;
1672
1673         none_display_name = IMB_colormanagement_display_get_none_name();
1674
1675         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
1676
1677         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
1678
1679         if (view) {
1680                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
1681         }
1682 }
1683
1684 int BKE_scene_check_color_management_enabled(const Scene *scene)
1685 {
1686         /* TODO(sergey): shouldn't be needed. but we're currently far to close to the release,
1687          *               so better be extra-safe than sorry.
1688          *
1689          *               Will remove the check after the release.
1690          */
1691         if (!scene) {
1692                 BLI_assert(!"Shouldn't happen!");
1693                 return TRUE;
1694         }
1695
1696         return strcmp(scene->display_settings.display_device, "None") != 0;
1697 }
1698
1699 int BKE_scene_check_rigidbody_active(const Scene *scene)
1700 {
1701         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
1702 }
1703
1704 int BKE_render_num_threads(const RenderData *rd)
1705 {
1706         int threads;
1707
1708         /* override set from command line? */
1709         threads = BLI_system_num_threads_override_get();
1710
1711         if (threads > 0)
1712                 return threads;
1713
1714         /* fixed number of threads specified in scene? */
1715         if (rd->mode & R_FIXED_THREADS)
1716                 threads = rd->threads;
1717         else
1718                 threads = BLI_system_thread_count();
1719         
1720         return max_ii(threads, 1);
1721 }
1722
1723 int BKE_scene_num_threads(const Scene *scene)
1724 {
1725         return BKE_render_num_threads(&scene->r);
1726 }
1727