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