Raytrace modifications from the Render Branch.
[blender-staging.git] / source / blender / blenkernel / intern / scene.c
1 /*  scene.c
2  *  
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <stddef.h>
33 #include <stdio.h>
34 #include <string.h>
35
36 #ifndef WIN32 
37 #include <unistd.h>
38 #else
39 #include <io.h>
40 #endif
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_anim_types.h"
45 #include "DNA_group_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_screen_types.h"
49 #include "DNA_sequence_types.h"
50
51 #include "BLI_math.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_utildefines.h"
54
55 #include "BKE_anim.h"
56 #include "BKE_animsys.h"
57 #include "BKE_depsgraph.h"
58 #include "BKE_global.h"
59 #include "BKE_group.h"
60 #include "BKE_idprop.h"
61 #include "BKE_library.h"
62 #include "BKE_main.h"
63 #include "BKE_node.h"
64 #include "BKE_object.h"
65 #include "BKE_paint.h"
66 #include "BKE_pointcache.h"
67 #include "BKE_scene.h"
68 #include "BKE_sequencer.h"
69 #include "BKE_world.h"
70
71 #include "BKE_sound.h"
72
73 //XXX #include "BIF_previewrender.h"
74 //XXX #include "BIF_editseq.h"
75
76 //XXX #include "nla.h"
77
78 #ifdef WIN32
79 #else
80 #include <sys/time.h>
81 #endif
82
83 void free_avicodecdata(AviCodecData *acd)
84 {
85         if (acd) {
86                 if (acd->lpFormat){
87                         MEM_freeN(acd->lpFormat);
88                         acd->lpFormat = NULL;
89                         acd->cbFormat = 0;
90                 }
91                 if (acd->lpParms){
92                         MEM_freeN(acd->lpParms);
93                         acd->lpParms = NULL;
94                         acd->cbParms = 0;
95                 }
96         }
97 }
98
99 void free_qtcodecdata(QuicktimeCodecData *qcd)
100 {
101         if (qcd) {
102                 if (qcd->cdParms){
103                         MEM_freeN(qcd->cdParms);
104                         qcd->cdParms = NULL;
105                         qcd->cdSize = 0;
106                 }
107         }
108 }
109
110 Scene *copy_scene(Scene *sce, int type)
111 {
112         Scene *scen;
113         ToolSettings *ts;
114         Base *base, *obase;
115         
116         if(type == SCE_COPY_EMPTY) {
117                 ListBase lb;
118                 scen= add_scene(sce->id.name+2);
119                 
120                 lb= scen->r.layers;
121                 scen->r= sce->r;
122                 scen->r.layers= lb;
123         }
124         else {
125                 scen= copy_libblock(sce);
126                 BLI_duplicatelist(&(scen->base), &(sce->base));
127                 
128                 clear_id_newpoins();
129                 
130                 id_us_plus((ID *)scen->world);
131                 id_us_plus((ID *)scen->set);
132                 id_us_plus((ID *)scen->gm.dome.warptext);
133
134                 scen->ed= NULL;
135                 scen->theDag= NULL;
136                 scen->obedit= NULL;
137                 scen->toolsettings= MEM_dupallocN(sce->toolsettings);
138                 scen->stats= NULL;
139                 scen->fps_info= NULL;
140
141                 ts= scen->toolsettings;
142                 if(ts) {
143                         if(ts->vpaint) {
144                                 ts->vpaint= MEM_dupallocN(ts->vpaint);
145                                 ts->vpaint->paintcursor= NULL;
146                                 ts->vpaint->vpaint_prev= NULL;
147                                 ts->vpaint->wpaint_prev= NULL;
148                                 copy_paint(&ts->vpaint->paint, &ts->vpaint->paint);
149                         }
150                         if(ts->wpaint) {
151                                 ts->wpaint= MEM_dupallocN(ts->wpaint);
152                                 ts->wpaint->paintcursor= NULL;
153                                 ts->wpaint->vpaint_prev= NULL;
154                                 ts->wpaint->wpaint_prev= NULL;
155                                 copy_paint(&ts->wpaint->paint, &ts->wpaint->paint);
156                         }
157                         if(ts->sculpt) {
158                                 ts->sculpt= MEM_dupallocN(ts->sculpt);
159                                 copy_paint(&ts->sculpt->paint, &ts->sculpt->paint);
160                         }
161
162                         copy_paint(&ts->imapaint.paint, &ts->imapaint.paint);
163                         ts->imapaint.paintcursor= NULL;
164
165                         ts->particle.paintcursor= NULL;
166                 }
167                 
168                 BLI_duplicatelist(&(scen->markers), &(sce->markers));
169                 BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
170                 BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
171                 BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
172
173                 if(sce->nodetree) {
174                         scen->nodetree= ntreeCopyTree(sce->nodetree, 0); /* copies actions */
175                         ntreeSwitchID(scen->nodetree, &sce->id, &scen->id);
176                 }
177
178                 obase= sce->base.first;
179                 base= scen->base.first;
180                 while(base) {
181                         id_us_plus(&base->object->id);
182                         if(obase==sce->basact) scen->basact= base;
183         
184                         obase= obase->next;
185                         base= base->next;
186                 }
187         }
188         
189         /* make a private copy of the avicodecdata */
190         if(sce->r.avicodecdata) {
191                 scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
192                 scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
193                 scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
194         }
195         
196         /* make a private copy of the qtcodecdata */
197         if(sce->r.qtcodecdata) {
198                 scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
199                 scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
200         }
201         
202         if(sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
203                 scen->r.ffcodecdata.properties= IDP_CopyProperty(sce->r.ffcodecdata.properties);
204         }
205
206         /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
207          * are done outside of blenkernel with ED_objects_single_users! */
208
209         /*  camera */
210         if(type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
211                 ID_NEW(scen->camera);
212         }
213         
214         /* before scene copy */
215         sound_create_scene(scen);
216
217         /* world */
218         if(type == SCE_COPY_FULL) {
219                 BKE_copy_animdata_id_action((ID *)scen);
220                 if(scen->world) {
221                         id_us_plus((ID *)scen->world);
222                         scen->world= copy_world(scen->world);
223                         BKE_copy_animdata_id_action((ID *)scen->world);
224                 }
225
226                 if(sce->ed) {
227                         scen->ed= MEM_callocN( sizeof(Editing), "addseq");
228                         scen->ed->seqbasep= &scen->ed->seqbase;
229                         seqbase_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL);
230                 }
231         }
232
233         return scen;
234 }
235
236 /* do not free scene itself */
237 void free_scene(Scene *sce)
238 {
239         Base *base;
240
241         base= sce->base.first;
242         while(base) {
243                 base->object->id.us--;
244                 base= base->next;
245         }
246         /* do not free objects! */
247         
248         if(sce->gpd) {
249 #if 0   // removed since this can be invalid memory when freeing everything
250                 // since the grease pencil data is free'd before the scene.
251                 // since grease pencil data is not (yet?), shared between objects
252                 // its probably safe not to do this, some save and reload will free this.
253                 sce->gpd->id.us--;
254 #endif
255                 sce->gpd= NULL;
256         }
257
258         BLI_freelistN(&sce->base);
259         seq_free_editing(sce);
260
261         BKE_free_animdata((ID *)sce);
262         BKE_keyingsets_free(&sce->keyingsets);
263         
264         if (sce->r.avicodecdata) {
265                 free_avicodecdata(sce->r.avicodecdata);
266                 MEM_freeN(sce->r.avicodecdata);
267                 sce->r.avicodecdata = NULL;
268         }
269         if (sce->r.qtcodecdata) {
270                 free_qtcodecdata(sce->r.qtcodecdata);
271                 MEM_freeN(sce->r.qtcodecdata);
272                 sce->r.qtcodecdata = NULL;
273         }
274         if (sce->r.ffcodecdata.properties) {
275                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
276                 MEM_freeN(sce->r.ffcodecdata.properties);
277                 sce->r.ffcodecdata.properties = NULL;
278         }
279         
280         BLI_freelistN(&sce->markers);
281         BLI_freelistN(&sce->transform_spaces);
282         BLI_freelistN(&sce->r.layers);
283         
284         if(sce->toolsettings) {
285                 if(sce->toolsettings->vpaint) {
286                         free_paint(&sce->toolsettings->vpaint->paint);
287                         MEM_freeN(sce->toolsettings->vpaint);
288                 }
289                 if(sce->toolsettings->wpaint) {
290                         free_paint(&sce->toolsettings->wpaint->paint);
291                         MEM_freeN(sce->toolsettings->wpaint);
292                 }
293                 if(sce->toolsettings->sculpt) {
294                         free_paint(&sce->toolsettings->sculpt->paint);
295                         MEM_freeN(sce->toolsettings->sculpt);
296                 }
297                 free_paint(&sce->toolsettings->imapaint.paint);
298
299                 MEM_freeN(sce->toolsettings);
300                 sce->toolsettings = NULL;       
301         }
302         
303         if (sce->theDag) {
304                 free_forest(sce->theDag);
305                 MEM_freeN(sce->theDag);
306         }
307         
308         if(sce->nodetree) {
309                 ntreeFreeTree(sce->nodetree);
310                 MEM_freeN(sce->nodetree);
311         }
312
313         if(sce->stats)
314                 MEM_freeN(sce->stats);
315         if(sce->fps_info)
316                 MEM_freeN(sce->fps_info);
317
318         sound_destroy_scene(sce);
319 }
320
321 Scene *add_scene(const char *name)
322 {
323         Main *bmain= G.main;
324         Scene *sce;
325         ParticleEditSettings *pset;
326         int a;
327
328         sce= alloc_libblock(&bmain->scene, ID_SCE, name);
329         sce->lay= sce->layact= 1;
330         
331         sce->r.mode= R_GAMMA|R_OSA|R_SHADOW|R_SSS|R_ENVMAP|R_RAYTRACE;
332         sce->r.cfra= 1;
333         sce->r.sfra= 1;
334         sce->r.efra= 250;
335         sce->r.frame_step= 1;
336         sce->r.xsch= 1920;
337         sce->r.ysch= 1080;
338         sce->r.xasp= 1;
339         sce->r.yasp= 1;
340         sce->r.xparts= 8;
341         sce->r.yparts= 8;
342         sce->r.mblur_samples= 1;
343         sce->r.filtertype= R_FILTER_MITCH;
344         sce->r.size= 50;
345         sce->r.planes= 24;
346         sce->r.imtype= R_PNG;
347         sce->r.quality= 90;
348         sce->r.displaymode= R_OUTPUT_AREA;
349         sce->r.framapto= 100;
350         sce->r.images= 100;
351         sce->r.framelen= 1.0;
352         sce->r.blurfac= 0.5;
353         sce->r.frs_sec= 24;
354         sce->r.frs_sec_base= 1;
355         sce->r.edgeint= 10;
356         sce->r.ocres = 128;
357         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
358         sce->r.gauss= 1.0;
359         
360         /* deprecated but keep for upwards compat */
361         sce->r.postgamma= 1.0;
362         sce->r.posthue= 0.0;
363         sce->r.postsat= 1.0;
364         
365         sce->r.bake_mode= 1;    /* prevent to include render stuff here */
366         sce->r.bake_filter= 2;
367         sce->r.bake_osa= 5;
368         sce->r.bake_flag= R_BAKE_CLEAR;
369         sce->r.bake_normal_space= R_BAKE_SPACE_TANGENT;
370         sce->r.scemode= R_DOCOMP|R_DOSEQ|R_EXTENSION;
371         sce->r.stamp= R_STAMP_TIME|R_STAMP_FRAME|R_STAMP_DATE|R_STAMP_CAMERA|R_STAMP_SCENE|R_STAMP_FILENAME|R_STAMP_RENDERTIME;
372         sce->r.stamp_font_id= 12;
373         sce->r.fg_stamp[0]= sce->r.fg_stamp[1]= sce->r.fg_stamp[2]= 0.8f;
374         sce->r.fg_stamp[3]= 1.0f;
375         sce->r.bg_stamp[0]= sce->r.bg_stamp[1]= sce->r.bg_stamp[2]= 0.0f;
376         sce->r.bg_stamp[3]= 0.25f;
377         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
378
379         sce->r.seq_prev_type= OB_SOLID;
380         sce->r.seq_rend_type= OB_SOLID;
381         sce->r.seq_flag= R_SEQ_GL_PREV;
382
383         sce->r.threads= 1;
384
385         sce->r.simplify_subsurf= 6;
386         sce->r.simplify_particles= 1.0f;
387         sce->r.simplify_shadowsamples= 16;
388         sce->r.simplify_aosss= 1.0f;
389
390         sce->r.cineonblack= 95;
391         sce->r.cineonwhite= 685;
392         sce->r.cineongamma= 1.7f;
393
394         sce->r.border.xmin= 0.0f;
395         sce->r.border.ymin= 0.0f;
396         sce->r.border.xmax= 1.0f;
397         sce->r.border.ymax= 1.0f;
398         
399         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings),"Tool Settings Struct");
400         sce->toolsettings->cornertype=1;
401         sce->toolsettings->degr = 90; 
402         sce->toolsettings->step = 9;
403         sce->toolsettings->turn = 1;                            
404         sce->toolsettings->extr_offs = 1; 
405         sce->toolsettings->doublimit = 0.001;
406         sce->toolsettings->segments = 32;
407         sce->toolsettings->rings = 32;
408         sce->toolsettings->vertices = 32;
409         sce->toolsettings->editbutflag = 1;
410         sce->toolsettings->uvcalc_radius = 1.0f;
411         sce->toolsettings->uvcalc_cubesize = 1.0f;
412         sce->toolsettings->uvcalc_mapdir = 1;
413         sce->toolsettings->uvcalc_mapalign = 1;
414         sce->toolsettings->unwrapper = 1;
415         sce->toolsettings->select_thresh= 0.01f;
416         sce->toolsettings->jointrilimit = 0.8f;
417
418         sce->toolsettings->selectmode= SCE_SELECT_VERTEX;
419         sce->toolsettings->uv_selectmode= UV_SELECT_VERTEX;
420         sce->toolsettings->normalsize= 0.1;
421         sce->toolsettings->autokey_mode= U.autokey_mode;
422
423         sce->toolsettings->skgen_resolution = 100;
424         sce->toolsettings->skgen_threshold_internal     = 0.01f;
425         sce->toolsettings->skgen_threshold_external     = 0.01f;
426         sce->toolsettings->skgen_angle_limit                    = 45.0f;
427         sce->toolsettings->skgen_length_ratio                   = 1.3f;
428         sce->toolsettings->skgen_length_limit                   = 1.5f;
429         sce->toolsettings->skgen_correlation_limit              = 0.98f;
430         sce->toolsettings->skgen_symmetry_limit                 = 0.1f;
431         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
432         sce->toolsettings->skgen_postpro_passes = 1;
433         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL|SKGEN_FILTER_EXTERNAL|SKGEN_FILTER_SMART|SKGEN_HARMONIC|SKGEN_SUB_CORRELATION|SKGEN_STICK_TO_EMBEDDING;
434         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
435         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
436         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
437
438         sce->toolsettings->proportional_size = 1.0f;
439
440         sce->physics_settings.gravity[0] = 0.0f;
441         sce->physics_settings.gravity[1] = 0.0f;
442         sce->physics_settings.gravity[2] = -9.81f;
443         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
444
445         sce->unit.scale_length = 1.0f;
446
447         pset= &sce->toolsettings->particle;
448         pset->flag= PE_KEEP_LENGTHS|PE_LOCK_FIRST|PE_DEFLECT_EMITTER|PE_AUTO_VELOCITY;
449         pset->emitterdist= 0.25f;
450         pset->totrekey= 5;
451         pset->totaddkey= 5;
452         pset->brushtype= PE_BRUSH_NONE;
453         pset->draw_step= 2;
454         pset->fade_frames= 2;
455         pset->selectmode= SCE_SELECT_PATH;
456         for(a=0; a<PE_TOT_BRUSH; a++) {
457                 pset->brush[a].strength= 0.5;
458                 pset->brush[a].size= 50;
459                 pset->brush[a].step= 10;
460                 pset->brush[a].count= 10;
461         }
462         pset->brush[PE_BRUSH_CUT].strength= 100;
463
464         sce->r.ffcodecdata.audio_mixrate = 44100;
465         sce->r.ffcodecdata.audio_volume = 1.0f;
466
467         BLI_strncpy(sce->r.engine, "BLENDER_RENDER", sizeof(sce->r.engine));
468
469         sce->audio.distance_model = 2.0;
470         sce->audio.doppler_factor = 1.0;
471         sce->audio.speed_of_sound = 343.3;
472
473         strcpy(sce->r.backbuf, "//backbuf");
474         strcpy(sce->r.pic, U.renderdir);
475
476         BLI_init_rctf(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
477         sce->r.osa= 8;
478
479         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
480         scene_add_render_layer(sce);
481         
482         /* game data */
483         sce->gm.stereoflag = STEREO_NOSTEREO;
484         sce->gm.stereomode = STEREO_ANAGLYPH;
485         sce->gm.eyeseparation = 0.10;
486
487         sce->gm.dome.angle = 180;
488         sce->gm.dome.mode = DOME_FISHEYE;
489         sce->gm.dome.res = 4;
490         sce->gm.dome.resbuf = 1.0f;
491         sce->gm.dome.tilt = 0;
492
493         sce->gm.xplay= 640;
494         sce->gm.yplay= 480;
495         sce->gm.freqplay= 60;
496         sce->gm.depth= 32;
497
498         sce->gm.gravity= 9.8f;
499         sce->gm.physicsEngine= WOPHY_BULLET;
500         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
501         sce->gm.occlusionRes = 128;
502         sce->gm.ticrate = 60;
503         sce->gm.maxlogicstep = 5;
504         sce->gm.physubstep = 1;
505         sce->gm.maxphystep = 5;
506
507         sce->gm.flag = GAME_DISPLAY_LISTS;
508         sce->gm.matmode = GAME_MAT_MULTITEX;
509
510         sound_create_scene(sce);
511
512         return sce;
513 }
514
515 Base *object_in_scene(Object *ob, Scene *sce)
516 {
517         Base *base;
518         
519         base= sce->base.first;
520         while(base) {
521                 if(base->object == ob) return base;
522                 base= base->next;
523         }
524         return NULL;
525 }
526
527 void set_scene_bg(Main *bmain, Scene *scene)
528 {
529         Scene *sce;
530         Base *base;
531         Object *ob;
532         Group *group;
533         GroupObject *go;
534         int flag;
535         
536         /* check for cyclic sets, for reading old files but also for definite security (py?) */
537         scene_check_setscene(bmain, scene);
538         
539         /* can happen when switching modes in other scenes */
540         if(scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
541                 scene->obedit= NULL;
542
543         /* deselect objects (for dataselect) */
544         for(ob= bmain->object.first; ob; ob= ob->id.next)
545                 ob->flag &= ~(SELECT|OB_FROMGROUP);
546
547         /* group flags again */
548         for(group= bmain->group.first; group; group= group->id.next) {
549                 go= group->gobject.first;
550                 while(go) {
551                         if(go->ob) go->ob->flag |= OB_FROMGROUP;
552                         go= go->next;
553                 }
554         }
555
556         /* sort baselist */
557         DAG_scene_sort(bmain, scene);
558         
559         /* ensure dags are built for sets */
560         for(sce= scene->set; sce; sce= sce->set)
561                 if(sce->theDag==NULL)
562                         DAG_scene_sort(bmain, sce);
563
564         /* copy layers and flags from bases to objects */
565         for(base= scene->base.first; base; base= base->next) {
566                 ob= base->object;
567                 ob->lay= base->lay;
568                 
569                 /* group patch... */
570                 base->flag &= ~(OB_FROMGROUP);
571                 flag= ob->flag & (OB_FROMGROUP);
572                 base->flag |= flag;
573                 
574                 /* not too nice... for recovering objects with lost data */
575                 //if(ob->pose==NULL) base->flag &= ~OB_POSEMODE;
576                 ob->flag= base->flag;
577                 
578                 ob->ctime= -1234567.0;  /* force ipo to be calculated later */
579         }
580         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
581 }
582
583 /* called from creator.c */
584 Scene *set_scene_name(Main *bmain, char *name)
585 {
586         Scene *sce= (Scene *)find_id("SC", name);
587         if(sce) {
588                 set_scene_bg(bmain, sce);
589                 printf("Scene switch: '%s' in file: '%s'\n", name, G.main->name);
590                 return sce;
591         }
592
593         printf("Can't find scene: '%s' in file: '%s'\n", name, G.main->name);
594         return NULL;
595 }
596
597 void unlink_scene(Main *bmain, Scene *sce, Scene *newsce)
598 {
599         Scene *sce1;
600         bScreen *sc;
601
602         /* check all sets */
603         for(sce1= bmain->scene.first; sce1; sce1= sce1->id.next)
604                 if(sce1->set == sce)
605                         sce1->set= NULL;
606         
607         /* check all sequences */
608         clear_scene_in_allseqs(bmain, sce);
609
610         /* check render layer nodes in other scenes */
611         clear_scene_in_nodes(bmain, sce);
612         
613         /* al screens */
614         for(sc= bmain->screen.first; sc; sc= sc->id.next)
615                 if(sc->scene == sce)
616                         sc->scene= newsce;
617
618         free_libblock(&bmain->scene, sce);
619 }
620
621 /* used by metaballs
622  * doesnt return the original duplicated object, only dupli's
623  */
624 int next_object(Scene **scene, int val, Base **base, Object **ob)
625 {
626         static ListBase *duplilist= NULL;
627         static DupliObject *dupob;
628         static int fase= F_START, in_next_object= 0;
629         int run_again=1;
630         
631         /* init */
632         if(val==0) {
633                 fase= F_START;
634                 dupob= NULL;
635                 
636                 /* XXX particle systems with metas+dupligroups call this recursively */
637                 /* see bug #18725 */
638                 if(in_next_object) {
639                         printf("ERROR: MetaBall generation called recursively, not supported\n");
640                         
641                         return F_ERROR;
642                 }
643         }
644         else {
645                 in_next_object= 1;
646                 
647                 /* run_again is set when a duplilist has been ended */
648                 while(run_again) {
649                         run_again= 0;
650
651                         /* the first base */
652                         if(fase==F_START) {
653                                 *base= (*scene)->base.first;
654                                 if(*base) {
655                                         *ob= (*base)->object;
656                                         fase= F_SCENE;
657                                 }
658                                 else {
659                                         /* exception: empty scene */
660                                         while((*scene)->set) {
661                                                 (*scene)= (*scene)->set;
662                                                 if((*scene)->base.first) {
663                                                         *base= (*scene)->base.first;
664                                                         *ob= (*base)->object;
665                                                         fase= F_SCENE;
666                                                         break;
667                                                 }
668                                         }
669                                 }
670                         }
671                         else {
672                                 if(*base && fase!=F_DUPLI) {
673                                         *base= (*base)->next;
674                                         if(*base) *ob= (*base)->object;
675                                         else {
676                                                 if(fase==F_SCENE) {
677                                                         /* (*scene) is finished, now do the set */
678                                                         while((*scene)->set) {
679                                                                 (*scene)= (*scene)->set;
680                                                                 if((*scene)->base.first) {
681                                                                         *base= (*scene)->base.first;
682                                                                         *ob= (*base)->object;
683                                                                         break;
684                                                                 }
685                                                         }
686                                                 }
687                                         }
688                                 }
689                         }
690                         
691                         if(*base == NULL) fase= F_START;
692                         else {
693                                 if(fase!=F_DUPLI) {
694                                         if( (*base)->object->transflag & OB_DUPLI) {
695                                                 /* groups cannot be duplicated for mballs yet, 
696                                                 this enters eternal loop because of 
697                                                 makeDispListMBall getting called inside of group_duplilist */
698                                                 if((*base)->object->dup_group == NULL) {
699                                                         duplilist= object_duplilist((*scene), (*base)->object);
700                                                         
701                                                         dupob= duplilist->first;
702
703                                                         if(!dupob)
704                                                                 free_object_duplilist(duplilist);
705                                                 }
706                                         }
707                                 }
708                                 /* handle dupli's */
709                                 if(dupob) {
710                                         
711                                         copy_m4_m4(dupob->ob->obmat, dupob->mat);
712                                         
713                                         (*base)->flag |= OB_FROMDUPLI;
714                                         *ob= dupob->ob;
715                                         fase= F_DUPLI;
716                                         
717                                         dupob= dupob->next;
718                                 }
719                                 else if(fase==F_DUPLI) {
720                                         fase= F_SCENE;
721                                         (*base)->flag &= ~OB_FROMDUPLI;
722                                         
723                                         for(dupob= duplilist->first; dupob; dupob= dupob->next) {
724                                                 copy_m4_m4(dupob->ob->obmat, dupob->omat);
725                                         }
726                                         
727                                         free_object_duplilist(duplilist);
728                                         duplilist= NULL;
729                                         run_again= 1;
730                                 }
731                         }
732                 }
733         }
734         
735         /* if(ob && *ob) {
736                 printf("Scene: '%s', '%s'\n", (*scene)->id.name+2, (*ob)->id.name+2);
737         } */
738
739         /* reset recursion test */
740         in_next_object= 0;
741         
742         return fase;
743 }
744
745 Object *scene_find_camera(Scene *sc)
746 {
747         Base *base;
748         
749         for (base= sc->base.first; base; base= base->next)
750                 if (base->object->type==OB_CAMERA)
751                         return base->object;
752
753         return NULL;
754 }
755
756 #ifdef DURIAN_CAMERA_SWITCH
757 Object *scene_camera_switch_find(Scene *scene)
758 {
759         TimeMarker *m;
760         int cfra = scene->r.cfra;
761         int frame = -(MAXFRAME + 1);
762         Object *camera= NULL;
763
764         for (m= scene->markers.first; m; m= m->next) {
765                 if(m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER)==0 && (m->frame <= cfra) && (m->frame > frame)) {
766                         camera= m->camera;
767                         frame= m->frame;
768
769                         if(frame == cfra)
770                                 break;
771
772                 }
773         }
774         return camera;
775 }
776 #endif
777
778 int scene_camera_switch_update(Scene *scene)
779 {
780 #ifdef DURIAN_CAMERA_SWITCH
781         Object *camera= scene_camera_switch_find(scene);
782         if(camera) {
783                 scene->camera= camera;
784                 return 1;
785         }
786 #endif
787         return 0;
788 }
789
790 char *scene_find_marker_name(Scene *scene, int frame)
791 {
792         ListBase *markers= &scene->markers;
793         TimeMarker *m1, *m2;
794
795         /* search through markers for match */
796         for (m1=markers->first, m2=markers->last; m1 && m2; m1=m1->next, m2=m2->prev) {
797                 if (m1->frame==frame)
798                         return m1->name;
799
800                 if (m1 == m2)
801                         break;
802
803                 if (m2->frame==frame)
804                         return m2->name;
805         }
806
807         return NULL;
808 }
809
810 /* return the current marker for this frame,
811 we can have more then 1 marker per frame, this just returns the first :/ */
812 char *scene_find_last_marker_name(Scene *scene, int frame)
813 {
814         TimeMarker *marker, *best_marker = NULL;
815         int best_frame = -MAXFRAME*2;
816         for (marker= scene->markers.first; marker; marker= marker->next) {
817                 if (marker->frame==frame) {
818                         return marker->name;
819                 }
820
821                 if ( marker->frame > best_frame && marker->frame < frame) {
822                         best_marker = marker;
823                         best_frame = marker->frame;
824                 }
825         }
826
827         return best_marker ? best_marker->name : NULL;
828 }
829
830 /* markers need transforming from different parts of the code so have
831  * a generic function to do this */
832 int scene_marker_tfm_translate(Scene *scene, int delta, int flag)
833 {
834         TimeMarker *marker;
835         int tot= 0;
836
837         for (marker= scene->markers.first; marker; marker= marker->next) {
838                 if ((marker->flag & flag) == flag) {
839                         marker->frame += delta;
840                         tot++;
841                 }
842         }
843
844         return tot;
845 }
846
847 int scene_marker_tfm_extend(Scene *scene, int delta, int flag, int frame, char side)
848 {
849         TimeMarker *marker;
850         int tot= 0;
851
852         for (marker= scene->markers.first; marker; marker= marker->next) {
853                 if ((marker->flag & flag) == flag) {
854                         if((side=='L' && marker->frame < frame) || (side=='R' && marker->frame >= frame)) {
855                                 marker->frame += delta;
856                                 tot++;
857                         }
858                 }
859         }
860
861         return tot;
862 }
863
864 int scene_marker_tfm_scale(struct Scene *scene, float value, int flag)
865 {
866         TimeMarker *marker;
867         int tot= 0;
868
869         for (marker= scene->markers.first; marker; marker= marker->next) {
870                 if ((marker->flag & flag) == flag) {
871                         marker->frame= CFRA + (int)floorf(((float)(marker->frame - CFRA) * value) + 0.5f);
872                         tot++;
873                 }
874         }
875
876         return tot;
877 }
878
879 Base *scene_add_base(Scene *sce, Object *ob)
880 {
881         Base *b= MEM_callocN(sizeof(*b), "scene_add_base");
882         BLI_addhead(&sce->base, b);
883
884         b->object= ob;
885         b->flag= ob->flag;
886         b->lay= ob->lay;
887
888         return b;
889 }
890
891 void scene_deselect_all(Scene *sce)
892 {
893         Base *b;
894
895         for (b= sce->base.first; b; b= b->next) {
896                 b->flag&= ~SELECT;
897                 b->object->flag= b->flag;
898         }
899 }
900
901 void scene_select_base(Scene *sce, Base *selbase)
902 {
903         scene_deselect_all(sce);
904
905         selbase->flag |= SELECT;
906         selbase->object->flag= selbase->flag;
907
908         sce->basact= selbase;
909 }
910
911 /* checks for cycle, returns 1 if it's all OK */
912 int scene_check_setscene(Main *bmain, Scene *sce)
913 {
914         Scene *scene;
915         int a, totscene;
916         
917         if(sce->set==NULL) return 1;
918         
919         totscene= 0;
920         for(scene= bmain->scene.first; scene; scene= scene->id.next)
921                 totscene++;
922         
923         for(a=0, scene=sce; scene->set; scene=scene->set, a++) {
924                 /* more iterations than scenes means we have a cycle */
925                 if(a > totscene) {
926                         /* the tested scene gets zero'ed, that's typically current scene */
927                         sce->set= NULL;
928                         return 0;
929                 }
930         }
931
932         return 1;
933 }
934
935 /* This function is needed to cope with fractional frames - including two Blender rendering features
936 * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. */
937
938 /* see also bsystem_time in object.c */
939 float BKE_curframe(Scene *scene)
940 {
941         float ctime = scene->r.cfra;
942         ctime+= scene->r.subframe;
943         ctime*= scene->r.framelen;      
944
945         return ctime;
946 }
947
948 static void scene_update_tagged_recursive(Main *bmain, Scene *scene, Scene *scene_parent)
949 {
950         Base *base;
951         scene->customdata_mask= scene_parent->customdata_mask;
952
953         /* sets first, we allow per definition current scene to have
954            dependencies on sets, but not the other way around. */
955         if(scene->set)
956                 scene_update_tagged_recursive(bmain, scene->set, scene_parent);
957
958         for(base= scene->base.first; base; base= base->next) {
959                 Object *ob= base->object;
960
961                 object_handle_update(scene_parent, ob);
962
963                 if(ob->dup_group && (ob->transflag & OB_DUPLIGROUP))
964                         group_handle_recalc_and_update(scene_parent, ob, ob->dup_group);
965                         
966                 /* always update layer, so that animating layers works */
967                 base->lay= ob->lay;
968         }
969 }
970
971 /* this is called in main loop, doing tagged updates before redraw */
972 void scene_update_tagged(Main *bmain, Scene *scene)
973 {
974         DAG_ids_flush_tagged(bmain);
975
976         scene->physics_settings.quick_cache_step= 0;
977
978         /* update all objects: drivers, matrices, displists, etc. flags set
979            by depgraph or manual, no layer check here, gets correct flushed */
980
981         scene_update_tagged_recursive(bmain, scene, scene);
982
983         /* recalc scene animation data here (for sequencer) */
984         {
985                 float ctime = BKE_curframe(scene); 
986                 AnimData *adt= BKE_animdata_from_id(&scene->id);
987
988                 if(adt && (adt->recalc & ADT_RECALC_ANIM))
989                         BKE_animsys_evaluate_animdata(&scene->id, adt, ctime, 0);
990         }
991
992         if(scene->physics_settings.quick_cache_step)
993                 BKE_ptcache_quick_cache_all(bmain, scene);
994
995         /* in the future this should handle updates for all datablocks, not
996            only objects and scenes. - brecht */
997 }
998
999 /* applies changes right away, does all sets too */
1000 void scene_update_for_newframe(Main *bmain, Scene *sce, unsigned int lay)
1001 {
1002         float ctime = BKE_curframe(sce);
1003         Scene *sce_iter;
1004         
1005         /* clear animation overrides */
1006         // XXX TODO...
1007
1008         for(sce_iter= sce; sce_iter; sce_iter= sce_iter->set) {
1009                 if(sce_iter->theDag==NULL)
1010                         DAG_scene_sort(bmain, sce_iter);
1011         }
1012
1013
1014         /* Following 2 functions are recursive
1015          * so dont call within 'scene_update_tagged_recursive' */
1016         DAG_scene_update_flags(bmain, sce, lay, TRUE);   // only stuff that moves or needs display still
1017
1018         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1019          * with an 'local' to 'macro' order of evaluation. This should ensure that
1020          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1021          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1022          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1023          */
1024         BKE_animsys_evaluate_all_animation(bmain, ctime);
1025         /*...done with recusrive funcs */
1026
1027         /* object_handle_update() on all objects, groups and sets */
1028         scene_update_tagged_recursive(bmain, sce, sce);
1029 }
1030
1031 /* return default layer, also used to patch old files */
1032 void scene_add_render_layer(Scene *sce)
1033 {
1034         SceneRenderLayer *srl;
1035 //      int tot= 1 + BLI_countlist(&sce->r.layers);
1036         
1037         srl= MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
1038         strcpy(srl->name, "RenderLayer");
1039         BLI_uniquename(&sce->r.layers, srl, "RenderLayer", '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
1040         BLI_addtail(&sce->r.layers, srl);
1041
1042         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
1043         srl->lay= (1<<20) -1;
1044         srl->layflag= 0x7FFF;   /* solid ztra halo edge strand */
1045         srl->passflag= SCE_PASS_COMBINED|SCE_PASS_Z;
1046 }
1047
1048 /* render simplification */
1049
1050 int get_render_subsurf_level(RenderData *r, int lvl)
1051 {
1052         if(r->mode & R_SIMPLIFY)
1053                 return MIN2(r->simplify_subsurf, lvl);
1054         else
1055                 return lvl;
1056 }
1057
1058 int get_render_child_particle_number(RenderData *r, int num)
1059 {
1060         if(r->mode & R_SIMPLIFY)
1061                 return (int)(r->simplify_particles*num);
1062         else
1063                 return num;
1064 }
1065
1066 int get_render_shadow_samples(RenderData *r, int samples)
1067 {
1068         if((r->mode & R_SIMPLIFY) && samples > 0)
1069                 return MIN2(r->simplify_shadowsamples, samples);
1070         else
1071                 return samples;
1072 }
1073
1074 float get_render_aosss_error(RenderData *r, float error)
1075 {
1076         if(r->mode & R_SIMPLIFY)
1077                 return ((1.0f-r->simplify_aosss)*10.0f + 1.0f)*error;
1078         else
1079                 return error;
1080 }
1081
1082 /* helper function for the SETLOOPER macro */
1083 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
1084 {
1085     if(base && base->next) {
1086         /* common case, step to the next */
1087         return base->next;
1088     }
1089         else if(base==NULL && (*sce_iter)->base.first) {
1090         /* first time looping, return the scenes first base */
1091                 return (Base *)(*sce_iter)->base.first;
1092     }
1093     else {
1094         /* reached the end, get the next base in the set */
1095                 while((*sce_iter= (*sce_iter)->set)) {
1096                         base= (Base *)(*sce_iter)->base.first;
1097             if(base) {
1098                 return base;
1099             }
1100         }
1101     }
1102
1103     return NULL;
1104 }