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