Merged changes in the trunk up to revision 48893.
[blender-staging.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_scene_types.h"
50 #include "DNA_screen_types.h"
51 #include "DNA_sequence_types.h"
52
53 #include "BLI_math.h"
54 #include "BLI_blenlib.h"
55 #include "BLI_utildefines.h"
56 #include "BLI_callbacks.h"
57
58 #include "BKE_anim.h"
59 #include "BKE_animsys.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_global.h"
62 #include "BKE_group.h"
63 #include "BKE_idprop.h"
64 #include "BKE_library.h"
65 #include "BKE_main.h"
66 #include "BKE_mask.h"
67 #include "BKE_node.h"
68 #include "BKE_object.h"
69 #include "BKE_paint.h"
70 #include "BKE_pointcache.h"
71 #include "BKE_scene.h"
72 #include "BKE_sequencer.h"
73 #include "BKE_world.h"
74
75 #include "BKE_sound.h"
76
77 #include "RE_engine.h"
78
79 //XXX #include "BIF_previewrender.h"
80 //XXX #include "BIF_editseq.h"
81
82 #include "FRS_freestyle_config.h"
83
84 #ifdef WIN32
85 #else
86 #include <sys/time.h>
87 #endif
88
89 void free_avicodecdata(AviCodecData *acd)
90 {
91         if (acd) {
92                 if (acd->lpFormat) {
93                         MEM_freeN(acd->lpFormat);
94                         acd->lpFormat = NULL;
95                         acd->cbFormat = 0;
96                 }
97                 if (acd->lpParms) {
98                         MEM_freeN(acd->lpParms);
99                         acd->lpParms = NULL;
100                         acd->cbParms = 0;
101                 }
102         }
103 }
104
105 void free_qtcodecdata(QuicktimeCodecData *qcd)
106 {
107         if (qcd) {
108                 if (qcd->cdParms) {
109                         MEM_freeN(qcd->cdParms);
110                         qcd->cdParms = NULL;
111                         qcd->cdSize = 0;
112                 }
113         }
114 }
115
116 Scene *BKE_scene_copy(Scene *sce, int type)
117 {
118         Scene *scen;
119         ToolSettings *ts;
120         Base *base, *obase;
121         
122         if (type == SCE_COPY_EMPTY) {
123                 ListBase lb;
124                 scen = BKE_scene_add(sce->id.name + 2);
125                 
126                 lb = scen->r.layers;
127                 scen->r = sce->r;
128                 scen->r.layers = lb;
129                 scen->unit = sce->unit;
130                 scen->physics_settings = sce->physics_settings;
131                 scen->gm = sce->gm;
132                 scen->audio = sce->audio;
133
134                 MEM_freeN(scen->toolsettings);
135         }
136         else {
137                 scen = BKE_libblock_copy(&sce->id);
138                 BLI_duplicatelist(&(scen->base), &(sce->base));
139                 
140                 clear_id_newpoins();
141                 
142                 id_us_plus((ID *)scen->world);
143                 id_us_plus((ID *)scen->set);
144                 id_us_plus((ID *)scen->gm.dome.warptext);
145
146                 scen->ed = NULL;
147                 scen->theDag = NULL;
148                 scen->obedit = NULL;
149                 scen->stats = NULL;
150                 scen->fps_info = NULL;
151
152                 BLI_duplicatelist(&(scen->markers), &(sce->markers));
153                 BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
154                 BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
155                 BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
156
157                 if (sce->nodetree) {
158                         scen->nodetree = ntreeCopyTree(sce->nodetree); /* copies actions */
159                         ntreeSwitchID(scen->nodetree, &sce->id, &scen->id);
160                 }
161
162                 obase = sce->base.first;
163                 base = scen->base.first;
164                 while (base) {
165                         id_us_plus(&base->object->id);
166                         if (obase == sce->basact) scen->basact = base;
167         
168                         obase = obase->next;
169                         base = base->next;
170                 }
171         }
172
173         /* tool settings */
174         scen->toolsettings = MEM_dupallocN(sce->toolsettings);
175
176         ts = scen->toolsettings;
177         if (ts) {
178                 if (ts->vpaint) {
179                         ts->vpaint = MEM_dupallocN(ts->vpaint);
180                         ts->vpaint->paintcursor = NULL;
181                         ts->vpaint->vpaint_prev = NULL;
182                         ts->vpaint->wpaint_prev = NULL;
183                         copy_paint(&ts->vpaint->paint, &ts->vpaint->paint);
184                 }
185                 if (ts->wpaint) {
186                         ts->wpaint = MEM_dupallocN(ts->wpaint);
187                         ts->wpaint->paintcursor = NULL;
188                         ts->wpaint->vpaint_prev = NULL;
189                         ts->wpaint->wpaint_prev = NULL;
190                         copy_paint(&ts->wpaint->paint, &ts->wpaint->paint);
191                 }
192                 if (ts->sculpt) {
193                         ts->sculpt = MEM_dupallocN(ts->sculpt);
194                         copy_paint(&ts->sculpt->paint, &ts->sculpt->paint);
195                 }
196
197                 copy_paint(&ts->imapaint.paint, &ts->imapaint.paint);
198                 ts->imapaint.paintcursor = NULL;
199                 ts->particle.paintcursor = NULL;
200         }
201         
202         /* make a private copy of the avicodecdata */
203         if (sce->r.avicodecdata) {
204                 scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
205                 scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
206                 scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
207         }
208         
209         /* make a private copy of the qtcodecdata */
210         if (sce->r.qtcodecdata) {
211                 scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
212                 scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
213         }
214         
215         if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
216                 scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
217         }
218
219         /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
220          * are done outside of blenkernel with ED_objects_single_users! */
221
222         /*  camera */
223         if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
224                 ID_NEW(scen->camera);
225         }
226         
227         /* before scene copy */
228         sound_create_scene(scen);
229
230         /* world */
231         if (type == SCE_COPY_FULL) {
232                 BKE_copy_animdata_id_action((ID *)scen);
233                 if (scen->world) {
234                         id_us_plus((ID *)scen->world);
235                         scen->world = BKE_world_copy(scen->world);
236                         BKE_copy_animdata_id_action((ID *)scen->world);
237                 }
238
239                 if (sce->ed) {
240                         scen->ed = MEM_callocN(sizeof(Editing), "addseq");
241                         scen->ed->seqbasep = &scen->ed->seqbase;
242                         seqbase_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL);
243                 }
244         }
245
246         return scen;
247 }
248
249 /* do not free scene itself */
250 void BKE_scene_free(Scene *sce)
251 {
252         Base *base;
253         SceneRenderLayer *srl;
254         
255         base = sce->base.first;
256         while (base) {
257                 base->object->id.us--;
258                 base = base->next;
259         }
260         /* do not free objects! */
261         
262         if (sce->gpd) {
263 #if 0   /* removed since this can be invalid memory when freeing everything */
264                 /* since the grease pencil data is freed before the scene.
265                  * since grease pencil data is not (yet?), shared between objects
266                  * its probably safe not to do this, some save and reload will free this. */
267                 sce->gpd->id.us--;
268 #endif
269                 sce->gpd = NULL;
270         }
271
272         BLI_freelistN(&sce->base);
273         BKE_sequencer_editing_free(sce);
274
275         BKE_free_animdata((ID *)sce);
276         BKE_keyingsets_free(&sce->keyingsets);
277         
278         if (sce->r.avicodecdata) {
279                 free_avicodecdata(sce->r.avicodecdata);
280                 MEM_freeN(sce->r.avicodecdata);
281                 sce->r.avicodecdata = NULL;
282         }
283         if (sce->r.qtcodecdata) {
284                 free_qtcodecdata(sce->r.qtcodecdata);
285                 MEM_freeN(sce->r.qtcodecdata);
286                 sce->r.qtcodecdata = NULL;
287         }
288         if (sce->r.ffcodecdata.properties) {
289                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
290                 MEM_freeN(sce->r.ffcodecdata.properties);
291                 sce->r.ffcodecdata.properties = NULL;
292         }
293         
294         for(srl= sce->r.layers.first; srl; srl= srl->next) {
295                 FRS_free_freestyle_config(srl);
296         }
297         
298         BLI_freelistN(&sce->markers);
299         BLI_freelistN(&sce->transform_spaces);
300         BLI_freelistN(&sce->r.layers);
301         
302         if (sce->toolsettings) {
303                 if (sce->toolsettings->vpaint) {
304                         free_paint(&sce->toolsettings->vpaint->paint);
305                         MEM_freeN(sce->toolsettings->vpaint);
306                 }
307                 if (sce->toolsettings->wpaint) {
308                         free_paint(&sce->toolsettings->wpaint->paint);
309                         MEM_freeN(sce->toolsettings->wpaint);
310                 }
311                 if (sce->toolsettings->sculpt) {
312                         free_paint(&sce->toolsettings->sculpt->paint);
313                         MEM_freeN(sce->toolsettings->sculpt);
314                 }
315                 if (sce->toolsettings->uvsculpt) {
316                         free_paint(&sce->toolsettings->uvsculpt->paint);
317                         MEM_freeN(sce->toolsettings->uvsculpt);
318                 }
319                 free_paint(&sce->toolsettings->imapaint.paint);
320
321                 MEM_freeN(sce->toolsettings);
322                 sce->toolsettings = NULL;       
323         }
324         
325         if (sce->theDag) {
326                 free_forest(sce->theDag);
327                 MEM_freeN(sce->theDag);
328         }
329         
330         if (sce->nodetree) {
331                 ntreeFreeTree(sce->nodetree);
332                 MEM_freeN(sce->nodetree);
333         }
334
335         if (sce->stats)
336                 MEM_freeN(sce->stats);
337         if (sce->fps_info)
338                 MEM_freeN(sce->fps_info);
339
340         sound_destroy_scene(sce);
341 }
342
343 Scene *BKE_scene_add(const char *name)
344 {
345         Main *bmain = G.main;
346         Scene *sce;
347         ParticleEditSettings *pset;
348         int a;
349
350         sce = BKE_libblock_alloc(&bmain->scene, ID_SCE, name);
351         sce->lay = sce->layact = 1;
352         
353         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
354         sce->r.cfra = 1;
355         sce->r.sfra = 1;
356         sce->r.efra = 250;
357         sce->r.frame_step = 1;
358         sce->r.xsch = 1920;
359         sce->r.ysch = 1080;
360         sce->r.xasp = 1;
361         sce->r.yasp = 1;
362         sce->r.xparts = 8;
363         sce->r.yparts = 8;
364         sce->r.mblur_samples = 1;
365         sce->r.filtertype = R_FILTER_MITCH;
366         sce->r.size = 50;
367
368         sce->r.im_format.planes = R_IMF_PLANES_RGB;
369         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
370         sce->r.im_format.quality = 90;
371
372         sce->r.displaymode = R_OUTPUT_AREA;
373         sce->r.framapto = 100;
374         sce->r.images = 100;
375         sce->r.framelen = 1.0;
376         sce->r.blurfac = 0.5;
377         sce->r.frs_sec = 24;
378         sce->r.frs_sec_base = 1;
379         sce->r.edgeint = 10;
380         sce->r.ocres = 128;
381         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
382         sce->r.gauss = 1.0;
383         
384         /* deprecated but keep for upwards compat */
385         sce->r.postgamma = 1.0;
386         sce->r.posthue = 0.0;
387         sce->r.postsat = 1.0;
388
389         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
390         sce->r.bake_filter = 2;
391         sce->r.bake_osa = 5;
392         sce->r.bake_flag = R_BAKE_CLEAR;
393         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
394         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
395         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME;
396         sce->r.stamp_font_id = 12;
397         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
398         sce->r.fg_stamp[3] = 1.0f;
399         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
400         sce->r.bg_stamp[3] = 0.25f;
401         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
402
403         sce->r.seq_prev_type = OB_SOLID;
404         sce->r.seq_rend_type = OB_SOLID;
405         sce->r.seq_flag = R_SEQ_GL_PREV;
406
407         sce->r.threads = 1;
408
409         sce->r.simplify_subsurf = 6;
410         sce->r.simplify_particles = 1.0f;
411         sce->r.simplify_shadowsamples = 16;
412         sce->r.simplify_aosss = 1.0f;
413
414         sce->r.border.xmin = 0.0f;
415         sce->r.border.ymin = 0.0f;
416         sce->r.border.xmax = 1.0f;
417         sce->r.border.ymax = 1.0f;
418         
419         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
420         sce->toolsettings->cornertype = 1;
421         sce->toolsettings->degr = 90; 
422         sce->toolsettings->step = 9;
423         sce->toolsettings->turn = 1;                            
424         sce->toolsettings->extr_offs = 1; 
425         sce->toolsettings->doublimit = 0.001;
426         sce->toolsettings->segments = 32;
427         sce->toolsettings->rings = 32;
428         sce->toolsettings->vertices = 32;
429         sce->toolsettings->uvcalc_radius = 1.0f;
430         sce->toolsettings->uvcalc_cubesize = 1.0f;
431         sce->toolsettings->uvcalc_mapdir = 1;
432         sce->toolsettings->uvcalc_mapalign = 1;
433         sce->toolsettings->unwrapper = 1;
434         sce->toolsettings->select_thresh = 0.01f;
435         sce->toolsettings->jointrilimit = 0.8f;
436
437         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
438         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
439         sce->toolsettings->normalsize = 0.1;
440         sce->toolsettings->autokey_mode = U.autokey_mode;
441
442         sce->toolsettings->skgen_resolution = 100;
443         sce->toolsettings->skgen_threshold_internal     = 0.01f;
444         sce->toolsettings->skgen_threshold_external     = 0.01f;
445         sce->toolsettings->skgen_angle_limit            = 45.0f;
446         sce->toolsettings->skgen_length_ratio           = 1.3f;
447         sce->toolsettings->skgen_length_limit           = 1.5f;
448         sce->toolsettings->skgen_correlation_limit      = 0.98f;
449         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
450         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
451         sce->toolsettings->skgen_postpro_passes = 1;
452         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
453         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
454         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
455         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
456
457         sce->toolsettings->proportional_size = 1.0f;
458
459         sce->physics_settings.gravity[0] = 0.0f;
460         sce->physics_settings.gravity[1] = 0.0f;
461         sce->physics_settings.gravity[2] = -9.81f;
462         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
463
464         sce->unit.scale_length = 1.0f;
465
466         pset = &sce->toolsettings->particle;
467         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
468         pset->emitterdist = 0.25f;
469         pset->totrekey = 5;
470         pset->totaddkey = 5;
471         pset->brushtype = PE_BRUSH_NONE;
472         pset->draw_step = 2;
473         pset->fade_frames = 2;
474         pset->selectmode = SCE_SELECT_PATH;
475         for (a = 0; a < PE_TOT_BRUSH; a++) {
476                 pset->brush[a].strength = 0.5;
477                 pset->brush[a].size = 50;
478                 pset->brush[a].step = 10;
479                 pset->brush[a].count = 10;
480         }
481         pset->brush[PE_BRUSH_CUT].strength = 100;
482
483         sce->r.ffcodecdata.audio_mixrate = 44100;
484         sce->r.ffcodecdata.audio_volume = 1.0f;
485         sce->r.ffcodecdata.audio_bitrate = 192;
486         sce->r.ffcodecdata.audio_channels = 2;
487
488         BLI_strncpy(sce->r.engine, "BLENDER_RENDER", sizeof(sce->r.engine));
489
490         sce->audio.distance_model = 2.0f;
491         sce->audio.doppler_factor = 1.0f;
492         sce->audio.speed_of_sound = 343.3f;
493         sce->audio.volume = 1.0f;
494
495         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
496
497         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
498         sce->r.osa = 8;
499
500         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
501         BKE_scene_add_render_layer(sce, NULL);
502         
503         /* game data */
504         sce->gm.stereoflag = STEREO_NOSTEREO;
505         sce->gm.stereomode = STEREO_ANAGLYPH;
506         sce->gm.eyeseparation = 0.10;
507
508         sce->gm.dome.angle = 180;
509         sce->gm.dome.mode = DOME_FISHEYE;
510         sce->gm.dome.res = 4;
511         sce->gm.dome.resbuf = 1.0f;
512         sce->gm.dome.tilt = 0;
513
514         sce->gm.xplay = 640;
515         sce->gm.yplay = 480;
516         sce->gm.freqplay = 60;
517         sce->gm.depth = 32;
518
519         sce->gm.gravity = 9.8f;
520         sce->gm.physicsEngine = WOPHY_BULLET;
521         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
522         sce->gm.occlusionRes = 128;
523         sce->gm.ticrate = 60;
524         sce->gm.maxlogicstep = 5;
525         sce->gm.physubstep = 1;
526         sce->gm.maxphystep = 5;
527         sce->gm.lineardeactthreshold = 0.8f;
528         sce->gm.angulardeactthreshold = 1.0f;
529         sce->gm.deactivationtime = 0.0f;
530
531         sce->gm.flag = GAME_DISPLAY_LISTS;
532         sce->gm.matmode = GAME_MAT_MULTITEX;
533
534         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
535         sce->gm.levelHeight = 2.f;
536
537         sce->gm.recastData.cellsize = 0.3f;
538         sce->gm.recastData.cellheight = 0.2f;
539         sce->gm.recastData.agentmaxslope = M_PI / 2;
540         sce->gm.recastData.agentmaxclimb = 0.9f;
541         sce->gm.recastData.agentheight = 2.0f;
542         sce->gm.recastData.agentradius = 0.6f;
543         sce->gm.recastData.edgemaxlen = 12.0f;
544         sce->gm.recastData.edgemaxerror = 1.3f;
545         sce->gm.recastData.regionminsize = 8.f;
546         sce->gm.recastData.regionmergesize = 20.f;
547         sce->gm.recastData.vertsperpoly = 6;
548         sce->gm.recastData.detailsampledist = 6.0f;
549         sce->gm.recastData.detailsamplemaxerror = 1.0f;
550
551         sce->gm.exitkey = 218; // Blender key code for ESC
552
553         sound_create_scene(sce);
554
555         return sce;
556 }
557
558 Base *BKE_scene_base_find(Scene *scene, Object *ob)
559 {
560         Base *base;
561         
562         base = scene->base.first;
563         while (base) {
564                 if (base->object == ob) return base;
565                 base = base->next;
566         }
567         return NULL;
568 }
569
570 void BKE_scene_set_background(Main *bmain, Scene *scene)
571 {
572         Scene *sce;
573         Base *base;
574         Object *ob;
575         Group *group;
576         GroupObject *go;
577         int flag;
578         
579         /* check for cyclic sets, for reading old files but also for definite security (py?) */
580         BKE_scene_validate_setscene(bmain, scene);
581         
582         /* can happen when switching modes in other scenes */
583         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
584                 scene->obedit = NULL;
585
586         /* deselect objects (for dataselect) */
587         for (ob = bmain->object.first; ob; ob = ob->id.next)
588                 ob->flag &= ~(SELECT | OB_FROMGROUP);
589
590         /* group flags again */
591         for (group = bmain->group.first; group; group = group->id.next) {
592                 go = group->gobject.first;
593                 while (go) {
594                         if (go->ob) go->ob->flag |= OB_FROMGROUP;
595                         go = go->next;
596                 }
597         }
598
599         /* sort baselist */
600         DAG_scene_sort(bmain, scene);
601         
602         /* ensure dags are built for sets */
603         for (sce = scene->set; sce; sce = sce->set)
604                 if (sce->theDag == NULL)
605                         DAG_scene_sort(bmain, sce);
606
607         /* copy layers and flags from bases to objects */
608         for (base = scene->base.first; base; base = base->next) {
609                 ob = base->object;
610                 ob->lay = base->lay;
611                 
612                 /* group patch... */
613                 base->flag &= ~(OB_FROMGROUP);
614                 flag = ob->flag & (OB_FROMGROUP);
615                 base->flag |= flag;
616                 
617                 /* not too nice... for recovering objects with lost data */
618                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
619                 ob->flag = base->flag;
620         }
621         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
622 }
623
624 /* called from creator.c */
625 Scene *BKE_scene_set_name(Main *bmain, const char *name)
626 {
627         Scene *sce = (Scene *)BKE_libblock_find_name(ID_SCE, name);
628         if (sce) {
629                 BKE_scene_set_background(bmain, sce);
630                 printf("Scene switch: '%s' in file: '%s'\n", name, G.main->name);
631                 return sce;
632         }
633
634         printf("Can't find scene: '%s' in file: '%s'\n", name, G.main->name);
635         return NULL;
636 }
637
638 void BKE_scene_unlink(Main *bmain, Scene *sce, Scene *newsce)
639 {
640         Scene *sce1;
641         bScreen *sc;
642
643         /* check all sets */
644         for (sce1 = bmain->scene.first; sce1; sce1 = sce1->id.next)
645                 if (sce1->set == sce)
646                         sce1->set = NULL;
647         
648         /* check all sequences */
649         clear_scene_in_allseqs(bmain, sce);
650
651         /* check render layer nodes in other scenes */
652         clear_scene_in_nodes(bmain, sce);
653         
654         /* al screens */
655         for (sc = bmain->screen.first; sc; sc = sc->id.next)
656                 if (sc->scene == sce)
657                         sc->scene = newsce;
658
659         BKE_libblock_free(&bmain->scene, sce);
660 }
661
662 /* used by metaballs
663  * doesnt return the original duplicated object, only dupli's
664  */
665 int BKE_scene_base_iter_next(Scene **scene, int val, Base **base, Object **ob)
666 {
667         static ListBase *duplilist = NULL;
668         static DupliObject *dupob;
669         static int fase = F_START, in_next_object = 0;
670         int run_again = 1;
671         
672         /* init */
673         if (val == 0) {
674                 fase = F_START;
675                 dupob = NULL;
676                 
677                 /* XXX particle systems with metas+dupligroups call this recursively */
678                 /* see bug #18725 */
679                 if (in_next_object) {
680                         printf("ERROR: Metaball generation called recursively, not supported\n");
681                         
682                         return F_ERROR;
683                 }
684         }
685         else {
686                 in_next_object = 1;
687                 
688                 /* run_again is set when a duplilist has been ended */
689                 while (run_again) {
690                         run_again = 0;
691
692                         /* the first base */
693                         if (fase == F_START) {
694                                 *base = (*scene)->base.first;
695                                 if (*base) {
696                                         *ob = (*base)->object;
697                                         fase = F_SCENE;
698                                 }
699                                 else {
700                                         /* exception: empty scene */
701                                         while ((*scene)->set) {
702                                                 (*scene) = (*scene)->set;
703                                                 if ((*scene)->base.first) {
704                                                         *base = (*scene)->base.first;
705                                                         *ob = (*base)->object;
706                                                         fase = F_SCENE;
707                                                         break;
708                                                 }
709                                         }
710                                 }
711                         }
712                         else {
713                                 if (*base && fase != F_DUPLI) {
714                                         *base = (*base)->next;
715                                         if (*base) *ob = (*base)->object;
716                                         else {
717                                                 if (fase == F_SCENE) {
718                                                         /* (*scene) is finished, now do the set */
719                                                         while ((*scene)->set) {
720                                                                 (*scene) = (*scene)->set;
721                                                                 if ((*scene)->base.first) {
722                                                                         *base = (*scene)->base.first;
723                                                                         *ob = (*base)->object;
724                                                                         break;
725                                                                 }
726                                                         }
727                                                 }
728                                         }
729                                 }
730                         }
731                         
732                         if (*base == NULL) fase = F_START;
733                         else {
734                                 if (fase != F_DUPLI) {
735                                         if ( (*base)->object->transflag & OB_DUPLI) {
736                                                 /* groups cannot be duplicated for mballs yet, 
737                                                  * this enters eternal loop because of 
738                                                  * makeDispListMBall getting called inside of group_duplilist */
739                                                 if ((*base)->object->dup_group == NULL) {
740                                                         duplilist = object_duplilist((*scene), (*base)->object);
741                                                         
742                                                         dupob = duplilist->first;
743
744                                                         if (!dupob)
745                                                                 free_object_duplilist(duplilist);
746                                                 }
747                                         }
748                                 }
749                                 /* handle dupli's */
750                                 if (dupob) {
751                                         
752                                         copy_m4_m4(dupob->ob->obmat, dupob->mat);
753                                         
754                                         (*base)->flag |= OB_FROMDUPLI;
755                                         *ob = dupob->ob;
756                                         fase = F_DUPLI;
757                                         
758                                         dupob = dupob->next;
759                                 }
760                                 else if (fase == F_DUPLI) {
761                                         fase = F_SCENE;
762                                         (*base)->flag &= ~OB_FROMDUPLI;
763                                         
764                                         for (dupob = duplilist->first; dupob; dupob = dupob->next) {
765                                                 copy_m4_m4(dupob->ob->obmat, dupob->omat);
766                                         }
767                                         
768                                         free_object_duplilist(duplilist);
769                                         duplilist = NULL;
770                                         run_again = 1;
771                                 }
772                         }
773                 }
774         }
775
776 #if 0
777         if (ob && *ob) {
778                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
779         }
780 #endif
781
782         /* reset recursion test */
783         in_next_object = 0;
784         
785         return fase;
786 }
787
788 Object *BKE_scene_camera_find(Scene *sc)
789 {
790         Base *base;
791         
792         for (base = sc->base.first; base; base = base->next)
793                 if (base->object->type == OB_CAMERA)
794                         return base->object;
795
796         return NULL;
797 }
798
799 #ifdef DURIAN_CAMERA_SWITCH
800 Object *BKE_scene_camera_switch_find(Scene *scene)
801 {
802         TimeMarker *m;
803         int cfra = scene->r.cfra;
804         int frame = -(MAXFRAME + 1);
805         Object *camera = NULL;
806
807         for (m = scene->markers.first; m; m = m->next) {
808                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0 && (m->frame <= cfra) && (m->frame > frame)) {
809                         camera = m->camera;
810                         frame = m->frame;
811
812                         if (frame == cfra)
813                                 break;
814
815                 }
816         }
817         return camera;
818 }
819 #endif
820
821 int BKE_scene_camera_switch_update(Scene *scene)
822 {
823 #ifdef DURIAN_CAMERA_SWITCH
824         Object *camera = BKE_scene_camera_switch_find(scene);
825         if (camera) {
826                 scene->camera = camera;
827                 return 1;
828         }
829 #else
830         (void)scene;
831 #endif
832         return 0;
833 }
834
835 char *BKE_scene_find_marker_name(Scene *scene, int frame)
836 {
837         ListBase *markers = &scene->markers;
838         TimeMarker *m1, *m2;
839
840         /* search through markers for match */
841         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
842                 if (m1->frame == frame)
843                         return m1->name;
844
845                 if (m1 == m2)
846                         break;
847
848                 if (m2->frame == frame)
849                         return m2->name;
850         }
851
852         return NULL;
853 }
854
855 /* return the current marker for this frame,
856  * we can have more then 1 marker per frame, this just returns the first :/ */
857 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
858 {
859         TimeMarker *marker, *best_marker = NULL;
860         int best_frame = -MAXFRAME * 2;
861         for (marker = scene->markers.first; marker; marker = marker->next) {
862                 if (marker->frame == frame) {
863                         return marker->name;
864                 }
865
866                 if (marker->frame > best_frame && marker->frame < frame) {
867                         best_marker = marker;
868                         best_frame = marker->frame;
869                 }
870         }
871
872         return best_marker ? best_marker->name : NULL;
873 }
874
875
876 Base *BKE_scene_base_add(Scene *sce, Object *ob)
877 {
878         Base *b = MEM_callocN(sizeof(*b), "BKE_scene_base_add");
879         BLI_addhead(&sce->base, b);
880
881         b->object = ob;
882         b->flag = ob->flag;
883         b->lay = ob->lay;
884
885         return b;
886 }
887
888 void BKE_scene_base_deselect_all(Scene *sce)
889 {
890         Base *b;
891
892         for (b = sce->base.first; b; b = b->next) {
893                 b->flag &= ~SELECT;
894                 b->object->flag = b->flag;
895         }
896 }
897
898 void BKE_scene_base_select(Scene *sce, Base *selbase)
899 {
900         selbase->flag |= SELECT;
901         selbase->object->flag = selbase->flag;
902
903         sce->basact = selbase;
904 }
905
906 /* checks for cycle, returns 1 if it's all OK */
907 int BKE_scene_validate_setscene(Main *bmain, Scene *sce)
908 {
909         Scene *scene;
910         int a, totscene;
911         
912         if (sce->set == NULL) return 1;
913         
914         totscene = 0;
915         for (scene = bmain->scene.first; scene; scene = scene->id.next)
916                 totscene++;
917         
918         for (a = 0, scene = sce; scene->set; scene = scene->set, a++) {
919                 /* more iterations than scenes means we have a cycle */
920                 if (a > totscene) {
921                         /* the tested scene gets zero'ed, that's typically current scene */
922                         sce->set = NULL;
923                         return 0;
924                 }
925         }
926
927         return 1;
928 }
929
930 /* This function is needed to cope with fractional frames - including two Blender rendering features
931  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
932  */
933 float BKE_scene_frame_get(Scene *scene)
934 {
935         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
936 }
937
938 /* This function is used to obtain arbitrary fractional frames */
939 float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame)
940 {
941         float ctime = frame;
942         ctime += scene->r.subframe;
943         ctime *= scene->r.framelen;     
944         
945         return ctime;
946 }
947
948 /* drivers support/hacks 
949  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
950  *      - these are always run since the depsgraph can't handle non-object data
951  *      - these happen after objects are all done so that we can read in their final transform values,
952  *        though this means that objects can't refer to scene info for guidance...
953  */
954 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
955 {
956         float ctime = BKE_scene_frame_get(scene);
957         
958         /* scene itself */
959         if (scene->adt && scene->adt->drivers.first) {
960                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
961         }
962
963         /* world */
964         /* TODO: what about world textures? but then those have nodes too... */
965         if (scene->world) {
966                 ID *wid = (ID *)scene->world;
967                 AnimData *adt = BKE_animdata_from_id(wid);
968                 
969                 if (adt && adt->drivers.first)
970                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
971         }
972         
973         /* nodes */
974         if (scene->nodetree) {
975                 ID *nid = (ID *)scene->nodetree;
976                 AnimData *adt = BKE_animdata_from_id(nid);
977                 
978                 if (adt && adt->drivers.first)
979                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
980         }
981 }
982
983 static void scene_update_tagged_recursive(Main *bmain, Scene *scene, Scene *scene_parent)
984 {
985         Base *base;
986         
987         
988         scene->customdata_mask = scene_parent->customdata_mask;
989
990         /* sets first, we allow per definition current scene to have
991          * dependencies on sets, but not the other way around. */
992         if (scene->set)
993                 scene_update_tagged_recursive(bmain, scene->set, scene_parent);
994         
995         /* scene objects */
996         for (base = scene->base.first; base; base = base->next) {
997                 Object *ob = base->object;
998                 
999                 BKE_object_handle_update(scene_parent, ob);
1000                 
1001                 if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP))
1002                         group_handle_recalc_and_update(scene_parent, ob, ob->dup_group);
1003                         
1004                 /* always update layer, so that animating layers works */
1005                 base->lay = ob->lay;
1006         }
1007         
1008         /* scene drivers... */
1009         scene_update_drivers(bmain, scene);
1010
1011         /* update sound system animation */
1012         sound_update_scene(scene);
1013
1014         /* update masking curves */
1015         BKE_mask_update_scene(bmain, scene, FALSE);
1016 }
1017
1018 /* this is called in main loop, doing tagged updates before redraw */
1019 void BKE_scene_update_tagged(Main *bmain, Scene *scene)
1020 {
1021         /* keep this first */
1022         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1023
1024         /* flush recalc flags to dependencies */
1025         DAG_ids_flush_tagged(bmain);
1026
1027         scene->physics_settings.quick_cache_step = 0;
1028
1029         /* update all objects: drivers, matrices, displists, etc. flags set
1030          * by depgraph or manual, no layer check here, gets correct flushed
1031          *
1032          * in the future this should handle updates for all datablocks, not
1033          * only objects and scenes. - brecht */
1034         scene_update_tagged_recursive(bmain, scene, scene);
1035
1036         /* extra call here to recalc scene animation (for sequencer) */
1037         {
1038                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1039                 float ctime = BKE_scene_frame_get(scene);
1040                 
1041                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1042                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1043         }
1044         
1045         /* quick point cache updates */
1046         if (scene->physics_settings.quick_cache_step)
1047                 BKE_ptcache_quick_cache_all(bmain, scene);
1048
1049         /* notify editors and python about recalc */
1050         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1051         DAG_ids_check_recalc(bmain, scene, FALSE);
1052
1053         /* clear recalc flags */
1054         DAG_ids_clear_recalc(bmain);
1055 }
1056
1057 /* applies changes right away, does all sets too */
1058 void BKE_scene_update_for_newframe(Main *bmain, Scene *sce, unsigned int lay)
1059 {
1060         float ctime = BKE_scene_frame_get(sce);
1061         Scene *sce_iter;
1062
1063         /* keep this first */
1064         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1065         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1066
1067         sound_set_cfra(sce->r.cfra);
1068         
1069         /* clear animation overrides */
1070         /* XXX TODO... */
1071
1072         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set) {
1073                 if (sce_iter->theDag == NULL)
1074                         DAG_scene_sort(bmain, sce_iter);
1075         }
1076
1077         /* flush recalc flags to dependencies, if we were only changing a frame
1078          * this would not be necessary, but if a user or a script has modified
1079          * some datablock before BKE_scene_update_tagged was called, we need the flush */
1080         DAG_ids_flush_tagged(bmain);
1081
1082         /* Following 2 functions are recursive
1083          * so don't call within 'scene_update_tagged_recursive' */
1084         DAG_scene_update_flags(bmain, sce, lay, TRUE);   // only stuff that moves or needs display still
1085
1086         BKE_mask_evaluate_all_masks(bmain, ctime, TRUE);
1087
1088         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1089          * with an 'local' to 'macro' order of evaluation. This should ensure that
1090          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1091          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1092          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1093          */
1094         BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1095         /*...done with recusrive funcs */
1096
1097         /* BKE_object_handle_update() on all objects, groups and sets */
1098         scene_update_tagged_recursive(bmain, sce, sce);
1099
1100         /* notify editors and python about recalc */
1101         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1102         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1103
1104         DAG_ids_check_recalc(bmain, sce, TRUE);
1105
1106         /* clear recalc flags */
1107         DAG_ids_clear_recalc(bmain);
1108 }
1109
1110 /* return default layer, also used to patch old files */
1111 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
1112 {
1113         SceneRenderLayer *srl;
1114
1115         if (!name)
1116                 name = "RenderLayer";
1117
1118         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1119         BLI_strncpy(srl->name, name, sizeof(srl->name));
1120         BLI_uniquename(&sce->r.layers, srl, "RenderLayer", '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1121         BLI_addtail(&sce->r.layers, srl);
1122
1123         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1124         srl->lay = (1 << 20) - 1;
1125         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
1126         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
1127         FRS_add_freestyle_config( srl );
1128
1129         return srl;
1130 }
1131
1132 int BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
1133 {
1134         const int act = BLI_findindex(&scene->r.layers, srl);
1135         Scene *sce;
1136
1137         if (act == -1) {
1138                 return 0;
1139         }
1140         else if ( (scene->r.layers.first == scene->r.layers.last) &&
1141                   (scene->r.layers.first == srl))
1142         {
1143                 /* ensure 1 layer is kept */
1144                 return 0;
1145         }
1146
1147         BLI_remlink(&scene->r.layers, srl);
1148         MEM_freeN(srl);
1149
1150         scene->r.actlay = 0;
1151
1152         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
1153                 if (sce->nodetree) {
1154                         bNode *node;
1155                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1156                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
1157                                         if (node->custom1 == act)
1158                                                 node->custom1 = 0;
1159                                         else if (node->custom1 > act)
1160                                                 node->custom1--;
1161                                 }
1162                         }
1163                 }
1164         }
1165
1166         return 1;
1167 }
1168
1169 /* render simplification */
1170
1171 int get_render_subsurf_level(RenderData *r, int lvl)
1172 {
1173         if (r->mode & R_SIMPLIFY)
1174                 return MIN2(r->simplify_subsurf, lvl);
1175         else
1176                 return lvl;
1177 }
1178
1179 int get_render_child_particle_number(RenderData *r, int num)
1180 {
1181         if (r->mode & R_SIMPLIFY)
1182                 return (int)(r->simplify_particles * num);
1183         else
1184                 return num;
1185 }
1186
1187 int get_render_shadow_samples(RenderData *r, int samples)
1188 {
1189         if ((r->mode & R_SIMPLIFY) && samples > 0)
1190                 return MIN2(r->simplify_shadowsamples, samples);
1191         else
1192                 return samples;
1193 }
1194
1195 float get_render_aosss_error(RenderData *r, float error)
1196 {
1197         if (r->mode & R_SIMPLIFY)
1198                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
1199         else
1200                 return error;
1201 }
1202
1203 /* helper function for the SETLOOPER macro */
1204 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1205 {
1206         if (base && base->next) {
1207                 /* common case, step to the next */
1208                 return base->next;
1209         }
1210         else if (base == NULL && (*sce_iter)->base.first) {
1211                 /* first time looping, return the scenes first base */
1212                 return (Base *)(*sce_iter)->base.first;
1213         }
1214         else {
1215                 /* reached the end, get the next base in the set */
1216                 while ((*sce_iter = (*sce_iter)->set)) {
1217                         base = (Base *)(*sce_iter)->base.first;
1218                         if (base) {
1219                                 return base;
1220                         }
1221                 }
1222         }
1223
1224         return NULL;
1225 }
1226
1227 int BKE_scene_use_new_shading_nodes(Scene *scene)
1228 {
1229         RenderEngineType *type = RE_engines_find(scene->r.engine);
1230         return (type && type->flag & RE_USE_SHADING_NODES);
1231 }
1232
1233 void BKE_scene_base_flag_to_objects(struct Scene *scene)
1234 {
1235         Base *base = scene->base.first;
1236
1237         while (base) {
1238                 base->object->flag = base->flag;
1239                 base = base->next;
1240         }
1241 }
1242
1243 void BKE_scene_base_flag_from_objects(struct Scene *scene)
1244 {
1245         Base *base = scene->base.first;
1246
1247         while (base) {
1248                 base->flag = base->object->flag;
1249                 base = base->next;
1250         }
1251 }