Cleanup: better not split UI strings when possible...
[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 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_linestyle_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_node_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_rigidbody_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_sequence_types.h"
49 #include "DNA_space_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_windowmanager_types.h"
52 #include "DNA_gpencil_types.h"
53
54 #include "BLI_math.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_utildefines.h"
57 #include "BLI_callbacks.h"
58 #include "BLI_string.h"
59 #include "BLI_threads.h"
60 #include "BLI_task.h"
61
62 #include "BLT_translation.h"
63
64 #include "BKE_anim.h"
65 #include "BKE_animsys.h"
66 #include "BKE_action.h"
67 #include "BKE_armature.h"
68 #include "BKE_cachefile.h"
69 #include "BKE_colortools.h"
70 #include "BKE_depsgraph.h"
71 #include "BKE_editmesh.h"
72 #include "BKE_fcurve.h"
73 #include "BKE_freestyle.h"
74 #include "BKE_global.h"
75 #include "BKE_gpencil.h"
76 #include "BKE_group.h"
77 #include "BKE_icons.h"
78 #include "BKE_idprop.h"
79 #include "BKE_image.h"
80 #include "BKE_library.h"
81 #include "BKE_linestyle.h"
82 #include "BKE_main.h"
83 #include "BKE_mask.h"
84 #include "BKE_node.h"
85 #include "BKE_object.h"
86 #include "BKE_paint.h"
87 #include "BKE_rigidbody.h"
88 #include "BKE_scene.h"
89 #include "BKE_screen.h"
90 #include "BKE_sequencer.h"
91 #include "BKE_sound.h"
92 #include "BKE_unit.h"
93 #include "BKE_world.h"
94
95 #include "DEG_depsgraph.h"
96
97 #include "RE_engine.h"
98
99 #include "PIL_time.h"
100
101 #include "IMB_colormanagement.h"
102 #include "IMB_imbuf.h"
103
104 #include "bmesh.h"
105
106 const char *RE_engine_id_BLENDER_RENDER = "BLENDER_RENDER";
107 const char *RE_engine_id_BLENDER_GAME = "BLENDER_GAME";
108 const char *RE_engine_id_CYCLES = "CYCLES";
109
110 void free_avicodecdata(AviCodecData *acd)
111 {
112         if (acd) {
113                 if (acd->lpFormat) {
114                         MEM_freeN(acd->lpFormat);
115                         acd->lpFormat = NULL;
116                         acd->cbFormat = 0;
117                 }
118                 if (acd->lpParms) {
119                         MEM_freeN(acd->lpParms);
120                         acd->lpParms = NULL;
121                         acd->cbParms = 0;
122                 }
123         }
124 }
125
126 void free_qtcodecdata(QuicktimeCodecData *qcd)
127 {
128         if (qcd) {
129                 if (qcd->cdParms) {
130                         MEM_freeN(qcd->cdParms);
131                         qcd->cdParms = NULL;
132                         qcd->cdSize = 0;
133                 }
134         }
135 }
136
137 static void remove_sequencer_fcurves(Scene *sce)
138 {
139         AnimData *adt = BKE_animdata_from_id(&sce->id);
140
141         if (adt && adt->action) {
142                 FCurve *fcu, *nextfcu;
143                 
144                 for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) {
145                         nextfcu = fcu->next;
146                         
147                         if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) {
148                                 action_groups_remove_channel(adt->action, fcu);
149                                 free_fcurve(fcu);
150                         }
151                 }
152         }
153 }
154
155 Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type)
156 {
157         Scene *scen;
158         SceneRenderLayer *srl, *new_srl;
159         FreestyleLineSet *lineset;
160         ToolSettings *ts;
161         Base *base, *obase;
162         
163         if (type == SCE_COPY_EMPTY) {
164                 ListBase rl, rv;
165                 /* XXX. main should become an arg */
166                 scen = BKE_scene_add(bmain, sce->id.name + 2);
167                 
168                 rl = scen->r.layers;
169                 rv = scen->r.views;
170                 curvemapping_free_data(&scen->r.mblur_shutter_curve);
171                 scen->r = sce->r;
172                 scen->r.layers = rl;
173                 scen->r.actlay = 0;
174                 scen->r.views = rv;
175                 scen->unit = sce->unit;
176                 scen->physics_settings = sce->physics_settings;
177                 scen->gm = sce->gm;
178                 scen->audio = sce->audio;
179
180                 if (sce->id.properties)
181                         scen->id.properties = IDP_CopyProperty(sce->id.properties);
182
183                 MEM_freeN(scen->toolsettings);
184                 BKE_sound_destroy_scene(scen);
185         }
186         else {
187                 scen = BKE_libblock_copy(bmain, &sce->id);
188                 BLI_duplicatelist(&(scen->base), &(sce->base));
189                 
190                 BKE_main_id_clear_newpoins(bmain);
191                 
192                 id_us_plus((ID *)scen->world);
193                 id_us_plus((ID *)scen->set);
194                 /* id_us_plus((ID *)scen->gm.dome.warptext); */  /* XXX Not refcounted? see readfile.c */
195
196                 scen->ed = NULL;
197                 scen->theDag = NULL;
198                 scen->depsgraph = NULL;
199                 scen->obedit = NULL;
200                 scen->stats = NULL;
201                 scen->fps_info = NULL;
202
203                 if (sce->rigidbody_world)
204                         scen->rigidbody_world = BKE_rigidbody_world_copy(sce->rigidbody_world);
205
206                 BLI_duplicatelist(&(scen->markers), &(sce->markers));
207                 BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
208                 BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
209                 BLI_duplicatelist(&(scen->r.views), &(sce->r.views));
210                 BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
211
212                 if (sce->nodetree) {
213                         /* ID's are managed on both copy and switch */
214                         scen->nodetree = ntreeCopyTree(bmain, sce->nodetree);
215                         ntreeSwitchID(scen->nodetree, &sce->id, &scen->id);
216                 }
217
218                 obase = sce->base.first;
219                 base = scen->base.first;
220                 while (base) {
221                         id_us_plus(&base->object->id);
222                         if (obase == sce->basact) scen->basact = base;
223         
224                         obase = obase->next;
225                         base = base->next;
226                 }
227
228                 /* copy action and remove animation used by sequencer */
229                 BKE_animdata_copy_id_action(&scen->id);
230
231                 if (type != SCE_COPY_FULL)
232                         remove_sequencer_fcurves(scen);
233
234                 /* copy Freestyle settings */
235                 new_srl = scen->r.layers.first;
236                 for (srl = sce->r.layers.first; srl; srl = srl->next) {
237                         BKE_freestyle_config_copy(&new_srl->freestyleConfig, &srl->freestyleConfig);
238                         if (type == SCE_COPY_FULL) {
239                                 for (lineset = new_srl->freestyleConfig.linesets.first; lineset; lineset = lineset->next) {
240                                         if (lineset->linestyle) {
241                                                 id_us_plus((ID *)lineset->linestyle);
242                                                 lineset->linestyle = BKE_linestyle_copy(bmain, lineset->linestyle);
243                                         }
244                                 }
245                         }
246                         new_srl = new_srl->next;
247                 }
248         }
249
250         /* copy color management settings */
251         BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings);
252         BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings);
253         BKE_color_managed_colorspace_settings_copy(&scen->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings);
254
255         BKE_color_managed_display_settings_copy(&scen->r.im_format.display_settings, &sce->r.im_format.display_settings);
256         BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings);
257
258         BKE_color_managed_display_settings_copy(&scen->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings);
259         BKE_color_managed_view_settings_copy(&scen->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings);
260
261         curvemapping_copy_data(&scen->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
262
263         /* tool settings */
264         scen->toolsettings = MEM_dupallocN(sce->toolsettings);
265
266         ts = scen->toolsettings;
267         if (ts) {
268                 if (ts->vpaint) {
269                         ts->vpaint = MEM_dupallocN(ts->vpaint);
270                         ts->vpaint->paintcursor = NULL;
271                         ts->vpaint->vpaint_prev = NULL;
272                         ts->vpaint->wpaint_prev = NULL;
273                         BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint);
274                 }
275                 if (ts->wpaint) {
276                         ts->wpaint = MEM_dupallocN(ts->wpaint);
277                         ts->wpaint->paintcursor = NULL;
278                         ts->wpaint->vpaint_prev = NULL;
279                         ts->wpaint->wpaint_prev = NULL;
280                         BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint);
281                 }
282                 if (ts->sculpt) {
283                         ts->sculpt = MEM_dupallocN(ts->sculpt);
284                         BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint);
285                 }
286
287                 BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint);
288                 ts->imapaint.paintcursor = NULL;
289                 id_us_plus((ID *)ts->imapaint.stencil);
290                 ts->particle.paintcursor = NULL;
291                 /* duplicate Grease Pencil Drawing Brushes */
292                 BLI_listbase_clear(&ts->gp_brushes);
293                 for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) {
294                         bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
295                         BLI_addtail(&ts->gp_brushes, newbrush);
296                 }
297
298         }
299         
300         /* make a private copy of the avicodecdata */
301         if (sce->r.avicodecdata) {
302                 scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
303                 scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
304                 scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
305         }
306         
307         /* make a private copy of the qtcodecdata */
308         if (sce->r.qtcodecdata) {
309                 scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
310                 scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
311         }
312         
313         if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
314                 scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
315         }
316
317         /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
318          * are done outside of blenkernel with ED_objects_single_users! */
319
320         /*  camera */
321         if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
322                 ID_NEW(scen->camera);
323         }
324         
325         /* before scene copy */
326         BKE_sound_create_scene(scen);
327
328         /* world */
329         if (type == SCE_COPY_FULL) {
330                 if (scen->world) {
331                         id_us_plus((ID *)scen->world);
332                         scen->world = BKE_world_copy(bmain, scen->world);
333                         BKE_animdata_copy_id_action((ID *)scen->world);
334                 }
335
336                 if (sce->ed) {
337                         scen->ed = MEM_callocN(sizeof(Editing), "addseq");
338                         scen->ed->seqbasep = &scen->ed->seqbase;
339                         BKE_sequence_base_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL);
340                 }
341         }
342         
343         /* grease pencil */
344         if (scen->gpd) {
345                 if (type == SCE_COPY_FULL) {
346                         scen->gpd = BKE_gpencil_data_duplicate(bmain, scen->gpd, false);
347                 }
348                 else if (type == SCE_COPY_EMPTY) {
349                         scen->gpd = NULL;
350                 }
351                 else {
352                         id_us_plus((ID *)scen->gpd);
353                 }
354         }
355
356         BKE_previewimg_id_copy(&scen->id, &sce->id);
357
358         return scen;
359 }
360
361 void BKE_scene_groups_relink(Scene *sce)
362 {
363         if (sce->rigidbody_world)
364                 BKE_rigidbody_world_groups_relink(sce->rigidbody_world);
365 }
366
367 void BKE_scene_make_local(Main *bmain, Scene *sce, const bool lib_local)
368 {
369         /* For now should work, may need more work though to support all possible corner cases
370          * (also scene_copy probably needs some love). */
371         BKE_id_make_local_generic(bmain, &sce->id, true, lib_local);
372 }
373
374 /** Free (or release) any data used by this scene (does not free the scene itself). */
375 void BKE_scene_free(Scene *sce)
376 {
377         SceneRenderLayer *srl;
378
379         BKE_animdata_free((ID *)sce, false);
380
381         /* check all sequences */
382         BKE_sequencer_clear_scene_in_allseqs(G.main, sce);
383
384         sce->basact = NULL;
385         BLI_freelistN(&sce->base);
386         BKE_sequencer_editing_free(sce);
387
388         BKE_keyingsets_free(&sce->keyingsets);
389
390         /* is no lib link block, but scene extension */
391         if (sce->nodetree) {
392                 ntreeFreeTree(sce->nodetree);
393                 MEM_freeN(sce->nodetree);
394                 sce->nodetree = NULL;
395         }
396
397         if (sce->rigidbody_world) {
398                 BKE_rigidbody_free_world(sce->rigidbody_world);
399                 sce->rigidbody_world = NULL;
400         }
401
402         if (sce->r.avicodecdata) {
403                 free_avicodecdata(sce->r.avicodecdata);
404                 MEM_freeN(sce->r.avicodecdata);
405                 sce->r.avicodecdata = NULL;
406         }
407         if (sce->r.qtcodecdata) {
408                 free_qtcodecdata(sce->r.qtcodecdata);
409                 MEM_freeN(sce->r.qtcodecdata);
410                 sce->r.qtcodecdata = NULL;
411         }
412         if (sce->r.ffcodecdata.properties) {
413                 IDP_FreeProperty(sce->r.ffcodecdata.properties);
414                 MEM_freeN(sce->r.ffcodecdata.properties);
415                 sce->r.ffcodecdata.properties = NULL;
416         }
417         
418         for (srl = sce->r.layers.first; srl; srl = srl->next) {
419                 BKE_freestyle_config_free(&srl->freestyleConfig);
420         }
421         
422         BLI_freelistN(&sce->markers);
423         BLI_freelistN(&sce->transform_spaces);
424         BLI_freelistN(&sce->r.layers);
425         BLI_freelistN(&sce->r.views);
426         
427         if (sce->toolsettings) {
428                 if (sce->toolsettings->vpaint) {
429                         BKE_paint_free(&sce->toolsettings->vpaint->paint);
430                         MEM_freeN(sce->toolsettings->vpaint);
431                 }
432                 if (sce->toolsettings->wpaint) {
433                         BKE_paint_free(&sce->toolsettings->wpaint->paint);
434                         MEM_freeN(sce->toolsettings->wpaint);
435                 }
436                 if (sce->toolsettings->sculpt) {
437                         BKE_paint_free(&sce->toolsettings->sculpt->paint);
438                         MEM_freeN(sce->toolsettings->sculpt);
439                 }
440                 if (sce->toolsettings->uvsculpt) {
441                         BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
442                         MEM_freeN(sce->toolsettings->uvsculpt);
443                 }
444                 /* free Grease Pencil Drawing Brushes */
445                 BKE_gpencil_free_brushes(&sce->toolsettings->gp_brushes);
446                 BLI_freelistN(&sce->toolsettings->gp_brushes);
447
448                 BKE_paint_free(&sce->toolsettings->imapaint.paint);
449
450                 MEM_freeN(sce->toolsettings);
451                 sce->toolsettings = NULL;
452         }
453         
454         DAG_scene_free(sce);
455         if (sce->depsgraph)
456                 DEG_graph_free(sce->depsgraph);
457         
458         MEM_SAFE_FREE(sce->stats);
459         MEM_SAFE_FREE(sce->fps_info);
460
461         BKE_sound_destroy_scene(sce);
462
463         BKE_color_managed_view_settings_free(&sce->view_settings);
464
465         BKE_previewimg_free(&sce->preview);
466         curvemapping_free_data(&sce->r.mblur_shutter_curve);
467 }
468
469 void BKE_scene_init(Scene *sce)
470 {
471         ParticleEditSettings *pset;
472         int a;
473         const char *colorspace_name;
474         SceneRenderView *srv;
475         CurveMapping *mblur_shutter_curve;
476
477         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(sce, id));
478
479         sce->lay = sce->layact = 1;
480         
481         sce->r.mode = R_GAMMA | R_OSA | R_SHADOW | R_SSS | R_ENVMAP | R_RAYTRACE;
482         sce->r.cfra = 1;
483         sce->r.sfra = 1;
484         sce->r.efra = 250;
485         sce->r.frame_step = 1;
486         sce->r.xsch = 1920;
487         sce->r.ysch = 1080;
488         sce->r.xasp = 1;
489         sce->r.yasp = 1;
490         sce->r.tilex = 256;
491         sce->r.tiley = 256;
492         sce->r.mblur_samples = 1;
493         sce->r.filtertype = R_FILTER_MITCH;
494         sce->r.size = 50;
495
496         sce->r.im_format.planes = R_IMF_PLANES_RGBA;
497         sce->r.im_format.imtype = R_IMF_IMTYPE_PNG;
498         sce->r.im_format.depth = R_IMF_CHAN_DEPTH_8;
499         sce->r.im_format.quality = 90;
500         sce->r.im_format.compress = 15;
501
502         sce->r.displaymode = R_OUTPUT_AREA;
503         sce->r.framapto = 100;
504         sce->r.images = 100;
505         sce->r.framelen = 1.0;
506         sce->r.blurfac = 0.5;
507         sce->r.frs_sec = 24;
508         sce->r.frs_sec_base = 1;
509         sce->r.edgeint = 10;
510         sce->r.ocres = 128;
511
512         /* OCIO_TODO: for forwards compatibility only, so if no tonecurve are used,
513          *            images would look in the same way as in current blender
514          *
515          *            perhaps at some point should be completely deprecated?
516          */
517         sce->r.color_mgt_flag |= R_COLOR_MANAGEMENT;
518
519         sce->r.gauss = 1.0;
520         
521         /* deprecated but keep for upwards compat */
522         sce->r.postgamma = 1.0;
523         sce->r.posthue = 0.0;
524         sce->r.postsat = 1.0;
525
526         sce->r.bake_mode = 1;    /* prevent to include render stuff here */
527         sce->r.bake_filter = 16;
528         sce->r.bake_osa = 5;
529         sce->r.bake_flag = R_BAKE_CLEAR;
530         sce->r.bake_normal_space = R_BAKE_SPACE_TANGENT;
531         sce->r.bake_samples = 256;
532         sce->r.bake_biasdist = 0.001;
533
534         sce->r.bake.flag = R_BAKE_CLEAR;
535         sce->r.bake.pass_filter = R_BAKE_PASS_FILTER_ALL;
536         sce->r.bake.width = 512;
537         sce->r.bake.height = 512;
538         sce->r.bake.margin = 16;
539         sce->r.bake.normal_space = R_BAKE_SPACE_TANGENT;
540         sce->r.bake.normal_swizzle[0] = R_BAKE_POSX;
541         sce->r.bake.normal_swizzle[1] = R_BAKE_POSY;
542         sce->r.bake.normal_swizzle[2] = R_BAKE_POSZ;
543         BLI_strncpy(sce->r.bake.filepath, U.renderdir, sizeof(sce->r.bake.filepath));
544
545         sce->r.bake.im_format.planes = R_IMF_PLANES_RGBA;
546         sce->r.bake.im_format.imtype = R_IMF_IMTYPE_PNG;
547         sce->r.bake.im_format.depth = R_IMF_CHAN_DEPTH_8;
548         sce->r.bake.im_format.quality = 90;
549         sce->r.bake.im_format.compress = 15;
550
551         sce->r.scemode = R_DOCOMP | R_DOSEQ | R_EXTENSION;
552         sce->r.stamp = R_STAMP_TIME | R_STAMP_FRAME | R_STAMP_DATE | R_STAMP_CAMERA | R_STAMP_SCENE | R_STAMP_FILENAME | R_STAMP_RENDERTIME | R_STAMP_MEMORY;
553         sce->r.stamp_font_id = 12;
554         sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
555         sce->r.fg_stamp[3] = 1.0f;
556         sce->r.bg_stamp[0] = sce->r.bg_stamp[1] = sce->r.bg_stamp[2] = 0.0f;
557         sce->r.bg_stamp[3] = 0.25f;
558         sce->r.raytrace_options = R_RAYTRACE_USE_INSTANCES;
559
560         sce->r.seq_prev_type = OB_SOLID;
561         sce->r.seq_rend_type = OB_SOLID;
562         sce->r.seq_flag = R_SEQ_GL_PREV;
563
564         sce->r.threads = 1;
565
566         sce->r.simplify_subsurf = 6;
567         sce->r.simplify_particles = 1.0f;
568         sce->r.simplify_shadowsamples = 16;
569         sce->r.simplify_aosss = 1.0f;
570
571         sce->r.border.xmin = 0.0f;
572         sce->r.border.ymin = 0.0f;
573         sce->r.border.xmax = 1.0f;
574         sce->r.border.ymax = 1.0f;
575
576         sce->r.preview_start_resolution = 64;
577         
578         sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE;
579         sce->r.unit_line_thickness = 1.0f;
580
581         mblur_shutter_curve = &sce->r.mblur_shutter_curve;
582         curvemapping_set_defaults(mblur_shutter_curve, 1, 0.0f, 0.0f, 1.0f, 1.0f);
583         curvemapping_initialize(mblur_shutter_curve);
584         curvemap_reset(mblur_shutter_curve->cm,
585                        &mblur_shutter_curve->clipr,
586                        CURVE_PRESET_MAX,
587                        CURVEMAP_SLOPE_POS_NEG);
588
589         sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct");
590         sce->toolsettings->doublimit = 0.001;
591         sce->toolsettings->vgroup_weight = 1.0f;
592         sce->toolsettings->uvcalc_margin = 0.001f;
593         sce->toolsettings->unwrapper = 1;
594         sce->toolsettings->select_thresh = 0.01f;
595
596         sce->toolsettings->selectmode = SCE_SELECT_VERTEX;
597         sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX;
598         sce->toolsettings->normalsize = 0.1;
599         sce->toolsettings->autokey_mode = U.autokey_mode;
600
601         sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID;
602
603         sce->toolsettings->skgen_resolution = 100;
604         sce->toolsettings->skgen_threshold_internal     = 0.01f;
605         sce->toolsettings->skgen_threshold_external     = 0.01f;
606         sce->toolsettings->skgen_angle_limit            = 45.0f;
607         sce->toolsettings->skgen_length_ratio           = 1.3f;
608         sce->toolsettings->skgen_length_limit           = 1.5f;
609         sce->toolsettings->skgen_correlation_limit      = 0.98f;
610         sce->toolsettings->skgen_symmetry_limit         = 0.1f;
611         sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
612         sce->toolsettings->skgen_postpro_passes = 1;
613         sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL | SKGEN_FILTER_EXTERNAL | SKGEN_FILTER_SMART | SKGEN_HARMONIC | SKGEN_SUB_CORRELATION | SKGEN_STICK_TO_EMBEDDING;
614         sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
615         sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
616         sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
617
618         sce->toolsettings->curve_paint_settings.curve_type = CU_BEZIER;
619         sce->toolsettings->curve_paint_settings.flag |= CURVE_PAINT_FLAG_CORNERS_DETECT;
620         sce->toolsettings->curve_paint_settings.error_threshold = 8;
621         sce->toolsettings->curve_paint_settings.radius_max = 1.0f;
622         sce->toolsettings->curve_paint_settings.corner_angle = DEG2RADF(70.0f);
623
624         sce->toolsettings->statvis.overhang_axis = OB_NEGZ;
625         sce->toolsettings->statvis.overhang_min = 0;
626         sce->toolsettings->statvis.overhang_max = DEG2RADF(45.0f);
627         sce->toolsettings->statvis.thickness_max = 0.1f;
628         sce->toolsettings->statvis.thickness_samples = 1;
629         sce->toolsettings->statvis.distort_min = DEG2RADF(5.0f);
630         sce->toolsettings->statvis.distort_max = DEG2RADF(45.0f);
631
632         sce->toolsettings->statvis.sharp_min = DEG2RADF(90.0f);
633         sce->toolsettings->statvis.sharp_max = DEG2RADF(180.0f);
634
635         sce->toolsettings->proportional_size = 1.0f;
636
637         sce->toolsettings->imapaint.paint.flags |= PAINT_SHOW_BRUSH;
638         sce->toolsettings->imapaint.normal_angle = 80;
639         sce->toolsettings->imapaint.seam_bleed = 2;
640
641         sce->physics_settings.gravity[0] = 0.0f;
642         sce->physics_settings.gravity[1] = 0.0f;
643         sce->physics_settings.gravity[2] = -9.81f;
644         sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
645
646         sce->unit.scale_length = 1.0f;
647
648         pset = &sce->toolsettings->particle;
649         pset->flag = PE_KEEP_LENGTHS | PE_LOCK_FIRST | PE_DEFLECT_EMITTER | PE_AUTO_VELOCITY;
650         pset->emitterdist = 0.25f;
651         pset->totrekey = 5;
652         pset->totaddkey = 5;
653         pset->brushtype = PE_BRUSH_NONE;
654         pset->draw_step = 2;
655         pset->fade_frames = 2;
656         pset->selectmode = SCE_SELECT_PATH;
657         for (a = 0; a < PE_TOT_BRUSH; a++) {
658                 pset->brush[a].strength = 0.5f;
659                 pset->brush[a].size = 50;
660                 pset->brush[a].step = 10;
661                 pset->brush[a].count = 10;
662         }
663         pset->brush[PE_BRUSH_CUT].strength = 1.0f;
664
665         sce->r.ffcodecdata.audio_mixrate = 48000;
666         sce->r.ffcodecdata.audio_volume = 1.0f;
667         sce->r.ffcodecdata.audio_bitrate = 192;
668         sce->r.ffcodecdata.audio_channels = 2;
669
670         BLI_strncpy(sce->r.engine, RE_engine_id_BLENDER_RENDER, sizeof(sce->r.engine));
671
672         sce->audio.distance_model = 2.0f;
673         sce->audio.doppler_factor = 1.0f;
674         sce->audio.speed_of_sound = 343.3f;
675         sce->audio.volume = 1.0f;
676
677         BLI_strncpy(sce->r.pic, U.renderdir, sizeof(sce->r.pic));
678
679         BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f);
680         sce->r.osa = 8;
681
682         /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */
683         BKE_scene_add_render_layer(sce, NULL);
684
685         /* multiview - stereo */
686         BKE_scene_add_render_view(sce, STEREO_LEFT_NAME);
687         srv = sce->r.views.first;
688         BLI_strncpy(srv->suffix, STEREO_LEFT_SUFFIX, sizeof(srv->suffix));
689
690         BKE_scene_add_render_view(sce, STEREO_RIGHT_NAME);
691         srv = sce->r.views.last;
692         BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix));
693
694         /* game data */
695         sce->gm.stereoflag = STEREO_NOSTEREO;
696         sce->gm.stereomode = STEREO_ANAGLYPH;
697         sce->gm.eyeseparation = 0.10;
698
699         sce->gm.dome.angle = 180;
700         sce->gm.dome.mode = DOME_FISHEYE;
701         sce->gm.dome.res = 4;
702         sce->gm.dome.resbuf = 1.0f;
703         sce->gm.dome.tilt = 0;
704
705         sce->gm.xplay = 640;
706         sce->gm.yplay = 480;
707         sce->gm.freqplay = 60;
708         sce->gm.depth = 32;
709
710         sce->gm.gravity = 9.8f;
711         sce->gm.physicsEngine = WOPHY_BULLET;
712         sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling 
713         sce->gm.occlusionRes = 128;
714         sce->gm.ticrate = 60;
715         sce->gm.maxlogicstep = 5;
716         sce->gm.physubstep = 1;
717         sce->gm.maxphystep = 5;
718         sce->gm.lineardeactthreshold = 0.8f;
719         sce->gm.angulardeactthreshold = 1.0f;
720         sce->gm.deactivationtime = 0.0f;
721
722         sce->gm.flag = GAME_DISPLAY_LISTS;
723         sce->gm.matmode = GAME_MAT_MULTITEX;
724
725         sce->gm.obstacleSimulation = OBSTSIMULATION_NONE;
726         sce->gm.levelHeight = 2.f;
727
728         sce->gm.recastData.cellsize = 0.3f;
729         sce->gm.recastData.cellheight = 0.2f;
730         sce->gm.recastData.agentmaxslope = M_PI_4;
731         sce->gm.recastData.agentmaxclimb = 0.9f;
732         sce->gm.recastData.agentheight = 2.0f;
733         sce->gm.recastData.agentradius = 0.6f;
734         sce->gm.recastData.edgemaxlen = 12.0f;
735         sce->gm.recastData.edgemaxerror = 1.3f;
736         sce->gm.recastData.regionminsize = 8.f;
737         sce->gm.recastData.regionmergesize = 20.f;
738         sce->gm.recastData.vertsperpoly = 6;
739         sce->gm.recastData.detailsampledist = 6.0f;
740         sce->gm.recastData.detailsamplemaxerror = 1.0f;
741
742         sce->gm.lodflag = SCE_LOD_USE_HYST;
743         sce->gm.scehysteresis = 10;
744
745         sce->gm.exitkey = 218; // Blender key code for ESC
746
747         BKE_sound_create_scene(sce);
748
749         /* color management */
750         colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER);
751
752         BKE_color_managed_display_settings_init(&sce->display_settings);
753         BKE_color_managed_view_settings_init(&sce->view_settings);
754         BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name,
755                     sizeof(sce->sequencer_colorspace_settings.name));
756
757         /* Safe Areas */
758         copy_v2_fl2(sce->safe_areas.title, 3.5f / 100.0f, 3.5f / 100.0f);
759         copy_v2_fl2(sce->safe_areas.action, 10.0f / 100.0f, 5.0f / 100.0f);
760         copy_v2_fl2(sce->safe_areas.title_center, 17.5f / 100.0f, 5.0f / 100.0f);
761         copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f);
762
763         sce->preview = NULL;
764         
765         /* GP Sculpt brushes */
766         {
767                 GP_BrushEdit_Settings *gset = &sce->toolsettings->gp_sculpt;
768                 GP_EditBrush_Data *gp_brush;
769                 
770                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH];
771                 gp_brush->size = 25;
772                 gp_brush->strength = 0.3f;
773                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE;
774                 
775                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS];
776                 gp_brush->size = 25;
777                 gp_brush->strength = 0.5f;
778                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
779                 
780                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_STRENGTH];
781                 gp_brush->size = 25;
782                 gp_brush->strength = 0.5f;
783                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
784
785                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_GRAB];
786                 gp_brush->size = 50;
787                 gp_brush->strength = 0.3f;
788                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
789                 
790                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH];
791                 gp_brush->size = 25;
792                 gp_brush->strength = 0.3f;
793                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
794                 
795                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST];
796                 gp_brush->size = 50;
797                 gp_brush->strength = 0.3f; // XXX?
798                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
799                 
800                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH];
801                 gp_brush->size = 50;
802                 gp_brush->strength = 0.5f; // XXX?
803                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
804                 
805                 gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE];
806                 gp_brush->size = 25;
807                 gp_brush->strength = 0.5f;
808                 gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF;
809         }
810         
811         /* GP Stroke Placement */
812         sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE;
813         sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE;
814         sce->toolsettings->gpencil_seq_align = GP_PROJECT_VIEWSPACE;
815         sce->toolsettings->gpencil_ima_align = GP_PROJECT_VIEWSPACE;
816 }
817
818 Scene *BKE_scene_add(Main *bmain, const char *name)
819 {
820         Scene *sce;
821
822         sce = BKE_libblock_alloc(bmain, ID_SCE, name);
823
824         BKE_scene_init(sce);
825
826         return sce;
827 }
828
829 Base *BKE_scene_base_find_by_name(struct Scene *scene, const char *name)
830 {
831         Base *base;
832
833         for (base = scene->base.first; base; base = base->next) {
834                 if (STREQ(base->object->id.name + 2, name)) {
835                         break;
836                 }
837         }
838
839         return base;
840 }
841
842 Base *BKE_scene_base_find(Scene *scene, Object *ob)
843 {
844         return BLI_findptr(&scene->base, ob, offsetof(Base, object));
845 }
846
847 /**
848  * Sets the active scene, mainly used when running in background mode (``--scene`` command line argument).
849  * This is also called to set the scene directly, bypassing windowing code.
850  * Otherwise #ED_screen_set_scene is used when changing scenes by the user.
851  */
852 void BKE_scene_set_background(Main *bmain, Scene *scene)
853 {
854         Scene *sce;
855         Base *base;
856         Object *ob;
857         Group *group;
858         GroupObject *go;
859         int flag;
860         
861         /* check for cyclic sets, for reading old files but also for definite security (py?) */
862         BKE_scene_validate_setscene(bmain, scene);
863         
864         /* can happen when switching modes in other scenes */
865         if (scene->obedit && !(scene->obedit->mode & OB_MODE_EDIT))
866                 scene->obedit = NULL;
867
868         /* deselect objects (for dataselect) */
869         for (ob = bmain->object.first; ob; ob = ob->id.next)
870                 ob->flag &= ~(SELECT | OB_FROMGROUP);
871
872         /* group flags again */
873         for (group = bmain->group.first; group; group = group->id.next) {
874                 for (go = group->gobject.first; go; go = go->next) {
875                         if (go->ob) {
876                                 go->ob->flag |= OB_FROMGROUP;
877                         }
878                 }
879         }
880
881         /* sort baselist for scene and sets */
882         for (sce = scene; sce; sce = sce->set)
883                 DAG_scene_relations_rebuild(bmain, sce);
884
885         /* copy layers and flags from bases to objects */
886         for (base = scene->base.first; base; base = base->next) {
887                 ob = base->object;
888                 ob->lay = base->lay;
889                 
890                 /* group patch... */
891                 base->flag &= ~(OB_FROMGROUP);
892                 flag = ob->flag & (OB_FROMGROUP);
893                 base->flag |= flag;
894                 
895                 /* not too nice... for recovering objects with lost data */
896                 //if (ob->pose == NULL) base->flag &= ~OB_POSEMODE;
897                 ob->flag = base->flag;
898         }
899         /* no full animation update, this to enable render code to work (render code calls own animation updates) */
900 }
901
902 /* called from creator_args.c */
903 Scene *BKE_scene_set_name(Main *bmain, const char *name)
904 {
905         Scene *sce = (Scene *)BKE_libblock_find_name_ex(bmain, ID_SCE, name);
906         if (sce) {
907                 BKE_scene_set_background(bmain, sce);
908                 printf("Scene switch: '%s' in file: '%s'\n", name, bmain->name);
909                 return sce;
910         }
911
912         printf("Can't find scene: '%s' in file: '%s'\n", name, bmain->name);
913         return NULL;
914 }
915
916 /* Used by metaballs, return *all* objects (including duplis) existing in the scene (including scene's sets) */
917 int BKE_scene_base_iter_next(EvaluationContext *eval_ctx, SceneBaseIter *iter,
918                              Scene **scene, int val, Base **base, Object **ob)
919 {
920         bool run_again = true;
921         
922         /* init */
923         if (val == 0) {
924                 iter->phase = F_START;
925                 iter->dupob = NULL;
926                 iter->duplilist = NULL;
927                 iter->dupli_refob = NULL;
928         }
929         else {
930                 /* run_again is set when a duplilist has been ended */
931                 while (run_again) {
932                         run_again = false;
933
934                         /* the first base */
935                         if (iter->phase == F_START) {
936                                 *base = (*scene)->base.first;
937                                 if (*base) {
938                                         *ob = (*base)->object;
939                                         iter->phase = F_SCENE;
940                                 }
941                                 else {
942                                         /* exception: empty scene */
943                                         while ((*scene)->set) {
944                                                 (*scene) = (*scene)->set;
945                                                 if ((*scene)->base.first) {
946                                                         *base = (*scene)->base.first;
947                                                         *ob = (*base)->object;
948                                                         iter->phase = F_SCENE;
949                                                         break;
950                                                 }
951                                         }
952                                 }
953                         }
954                         else {
955                                 if (*base && iter->phase != F_DUPLI) {
956                                         *base = (*base)->next;
957                                         if (*base) {
958                                                 *ob = (*base)->object;
959                                         }
960                                         else {
961                                                 if (iter->phase == F_SCENE) {
962                                                         /* (*scene) is finished, now do the set */
963                                                         while ((*scene)->set) {
964                                                                 (*scene) = (*scene)->set;
965                                                                 if ((*scene)->base.first) {
966                                                                         *base = (*scene)->base.first;
967                                                                         *ob = (*base)->object;
968                                                                         break;
969                                                                 }
970                                                         }
971                                                 }
972                                         }
973                                 }
974                         }
975                         
976                         if (*base == NULL) {
977                                 iter->phase = F_START;
978                         }
979                         else {
980                                 if (iter->phase != F_DUPLI) {
981                                         if ( (*base)->object->transflag & OB_DUPLI) {
982                                                 /* groups cannot be duplicated for mballs yet, 
983                                                  * this enters eternal loop because of 
984                                                  * makeDispListMBall getting called inside of group_duplilist */
985                                                 if ((*base)->object->dup_group == NULL) {
986                                                         iter->duplilist = object_duplilist_ex(eval_ctx, (*scene), (*base)->object, false);
987                                                         
988                                                         iter->dupob = iter->duplilist->first;
989
990                                                         if (!iter->dupob) {
991                                                                 free_object_duplilist(iter->duplilist);
992                                                                 iter->duplilist = NULL;
993                                                         }
994                                                         iter->dupli_refob = NULL;
995                                                 }
996                                         }
997                                 }
998                                 /* handle dupli's */
999                                 if (iter->dupob) {
1000                                         (*base)->flag |= OB_FROMDUPLI;
1001                                         *ob = iter->dupob->ob;
1002                                         iter->phase = F_DUPLI;
1003
1004                                         if (iter->dupli_refob != *ob) {
1005                                                 if (iter->dupli_refob) {
1006                                                         /* Restore previous object's real matrix. */
1007                                                         copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1008                                                 }
1009                                                 /* Backup new object's real matrix. */
1010                                                 iter->dupli_refob = *ob;
1011                                                 copy_m4_m4(iter->omat, iter->dupli_refob->obmat);
1012                                         }
1013                                         copy_m4_m4((*ob)->obmat, iter->dupob->mat);
1014
1015                                         iter->dupob = iter->dupob->next;
1016                                 }
1017                                 else if (iter->phase == F_DUPLI) {
1018                                         iter->phase = F_SCENE;
1019                                         (*base)->flag &= ~OB_FROMDUPLI;
1020                                         
1021                                         if (iter->dupli_refob) {
1022                                                 /* Restore last object's real matrix. */
1023                                                 copy_m4_m4(iter->dupli_refob->obmat, iter->omat);
1024                                                 iter->dupli_refob = NULL;
1025                                         }
1026                                         
1027                                         free_object_duplilist(iter->duplilist);
1028                                         iter->duplilist = NULL;
1029                                         run_again = true;
1030                                 }
1031                         }
1032                 }
1033         }
1034
1035 #if 0
1036         if (ob && *ob) {
1037                 printf("Scene: '%s', '%s'\n", (*scene)->id.name + 2, (*ob)->id.name + 2);
1038         }
1039 #endif
1040
1041         return iter->phase;
1042 }
1043
1044 Object *BKE_scene_camera_find(Scene *sc)
1045 {
1046         Base *base;
1047         
1048         for (base = sc->base.first; base; base = base->next)
1049                 if (base->object->type == OB_CAMERA)
1050                         return base->object;
1051
1052         return NULL;
1053 }
1054
1055 #ifdef DURIAN_CAMERA_SWITCH
1056 Object *BKE_scene_camera_switch_find(Scene *scene)
1057 {
1058         TimeMarker *m;
1059         int cfra = scene->r.cfra;
1060         int frame = -(MAXFRAME + 1);
1061         int min_frame = MAXFRAME + 1;
1062         Object *camera = NULL;
1063         Object *first_camera = NULL;
1064
1065         for (m = scene->markers.first; m; m = m->next) {
1066                 if (m->camera && (m->camera->restrictflag & OB_RESTRICT_RENDER) == 0) {
1067                         if ((m->frame <= cfra) && (m->frame > frame)) {
1068                                 camera = m->camera;
1069                                 frame = m->frame;
1070
1071                                 if (frame == cfra)
1072                                         break;
1073                         }
1074
1075                         if (m->frame < min_frame) {
1076                                 first_camera = m->camera;
1077                                 min_frame = m->frame;
1078                         }
1079                 }
1080         }
1081
1082         if (camera == NULL) {
1083                 /* If there's no marker to the left of current frame,
1084                  * use camera from left-most marker to solve all sort
1085                  * of Schrodinger uncertainties.
1086                  */
1087                 return first_camera;
1088         }
1089
1090         return camera;
1091 }
1092 #endif
1093
1094 int BKE_scene_camera_switch_update(Scene *scene)
1095 {
1096 #ifdef DURIAN_CAMERA_SWITCH
1097         Object *camera = BKE_scene_camera_switch_find(scene);
1098         if (camera) {
1099                 scene->camera = camera;
1100                 return 1;
1101         }
1102 #else
1103         (void)scene;
1104 #endif
1105         return 0;
1106 }
1107
1108 char *BKE_scene_find_marker_name(Scene *scene, int frame)
1109 {
1110         ListBase *markers = &scene->markers;
1111         TimeMarker *m1, *m2;
1112
1113         /* search through markers for match */
1114         for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) {
1115                 if (m1->frame == frame)
1116                         return m1->name;
1117
1118                 if (m1 == m2)
1119                         break;
1120
1121                 if (m2->frame == frame)
1122                         return m2->name;
1123         }
1124
1125         return NULL;
1126 }
1127
1128 /* return the current marker for this frame,
1129  * we can have more than 1 marker per frame, this just returns the first :/ */
1130 char *BKE_scene_find_last_marker_name(Scene *scene, int frame)
1131 {
1132         TimeMarker *marker, *best_marker = NULL;
1133         int best_frame = -MAXFRAME * 2;
1134         for (marker = scene->markers.first; marker; marker = marker->next) {
1135                 if (marker->frame == frame) {
1136                         return marker->name;
1137                 }
1138
1139                 if (marker->frame > best_frame && marker->frame < frame) {
1140                         best_marker = marker;
1141                         best_frame = marker->frame;
1142                 }
1143         }
1144
1145         return best_marker ? best_marker->name : NULL;
1146 }
1147
1148
1149 Base *BKE_scene_base_add(Scene *sce, Object *ob)
1150 {
1151         Base *b = MEM_callocN(sizeof(*b), __func__);
1152         BLI_addhead(&sce->base, b);
1153
1154         b->object = ob;
1155         b->flag = ob->flag;
1156         b->lay = ob->lay;
1157
1158         return b;
1159 }
1160
1161 void BKE_scene_base_unlink(Scene *sce, Base *base)
1162 {
1163         /* remove rigid body constraint from world before removing object */
1164         if (base->object->rigidbody_constraint)
1165                 BKE_rigidbody_remove_constraint(sce, base->object);
1166         /* remove rigid body object from world before removing object */
1167         if (base->object->rigidbody_object)
1168                 BKE_rigidbody_remove_object(sce, base->object);
1169         
1170         BLI_remlink(&sce->base, base);
1171         if (sce->basact == base)
1172                 sce->basact = NULL;
1173 }
1174
1175 void BKE_scene_base_deselect_all(Scene *sce)
1176 {
1177         Base *b;
1178
1179         for (b = sce->base.first; b; b = b->next) {
1180                 b->flag &= ~SELECT;
1181                 b->object->flag = b->flag;
1182         }
1183 }
1184
1185 void BKE_scene_base_select(Scene *sce, Base *selbase)
1186 {
1187         selbase->flag |= SELECT;
1188         selbase->object->flag = selbase->flag;
1189
1190         sce->basact = selbase;
1191 }
1192
1193 /* checks for cycle, returns 1 if it's all OK */
1194 bool BKE_scene_validate_setscene(Main *bmain, Scene *sce)
1195 {
1196         Scene *sce_iter;
1197         int a, totscene;
1198
1199         if (sce->set == NULL) return true;
1200         totscene = BLI_listbase_count(&bmain->scene);
1201         
1202         for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) {
1203                 /* more iterations than scenes means we have a cycle */
1204                 if (a > totscene) {
1205                         /* the tested scene gets zero'ed, that's typically current scene */
1206                         sce->set = NULL;
1207                         return false;
1208                 }
1209         }
1210
1211         return true;
1212 }
1213
1214 /* This function is needed to cope with fractional frames - including two Blender rendering features
1215  * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. 
1216  */
1217 float BKE_scene_frame_get(const Scene *scene)
1218 {
1219         return BKE_scene_frame_get_from_ctime(scene, scene->r.cfra);
1220 }
1221
1222 /* This function is used to obtain arbitrary fractional frames */
1223 float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame)
1224 {
1225         float ctime = frame;
1226         ctime += scene->r.subframe;
1227         ctime *= scene->r.framelen;
1228         
1229         return ctime;
1230 }
1231
1232 /**
1233  * Sets the frame int/float components.
1234  */
1235 void BKE_scene_frame_set(struct Scene *scene, double cfra)
1236 {
1237         double intpart;
1238         scene->r.subframe = modf(cfra, &intpart);
1239         scene->r.cfra = (int)intpart;
1240 }
1241
1242 #ifdef WITH_LEGACY_DEPSGRAPH
1243 /* drivers support/hacks 
1244  *  - this method is called from scene_update_tagged_recursive(), so gets included in viewport + render
1245  *      - these are always run since the depsgraph can't handle non-object data
1246  *      - these happen after objects are all done so that we can read in their final transform values,
1247  *        though this means that objects can't refer to scene info for guidance...
1248  */
1249 static void scene_update_drivers(Main *UNUSED(bmain), Scene *scene)
1250 {
1251         SceneRenderLayer *srl;
1252         float ctime = BKE_scene_frame_get(scene);
1253         
1254         /* scene itself */
1255         if (scene->adt && scene->adt->drivers.first) {
1256                 BKE_animsys_evaluate_animdata(scene, &scene->id, scene->adt, ctime, ADT_RECALC_DRIVERS);
1257         }
1258
1259         /* world */
1260         /* TODO: what about world textures? but then those have nodes too... */
1261         if (scene->world) {
1262                 ID *wid = (ID *)scene->world;
1263                 AnimData *adt = BKE_animdata_from_id(wid);
1264                 
1265                 if (adt && adt->drivers.first)
1266                         BKE_animsys_evaluate_animdata(scene, wid, adt, ctime, ADT_RECALC_DRIVERS);
1267         }
1268         
1269         /* nodes */
1270         if (scene->nodetree) {
1271                 ID *nid = (ID *)scene->nodetree;
1272                 AnimData *adt = BKE_animdata_from_id(nid);
1273                 
1274                 if (adt && adt->drivers.first)
1275                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1276         }
1277
1278         /* world nodes */
1279         if (scene->world && scene->world->nodetree) {
1280                 ID *nid = (ID *)scene->world->nodetree;
1281                 AnimData *adt = BKE_animdata_from_id(nid);
1282                 
1283                 if (adt && adt->drivers.first)
1284                         BKE_animsys_evaluate_animdata(scene, nid, adt, ctime, ADT_RECALC_DRIVERS);
1285         }
1286
1287         /* freestyle */
1288         for (srl = scene->r.layers.first; srl; srl = srl->next) {
1289                 FreestyleConfig *config = &srl->freestyleConfig;
1290                 FreestyleLineSet *lineset;
1291
1292                 for (lineset = config->linesets.first; lineset; lineset = lineset->next) {
1293                         if (lineset->linestyle) {
1294                                 ID *lid = &lineset->linestyle->id;
1295                                 AnimData *adt = BKE_animdata_from_id(lid);
1296
1297                                 if (adt && adt->drivers.first)
1298                                         BKE_animsys_evaluate_animdata(scene, lid, adt, ctime, ADT_RECALC_DRIVERS);
1299                         }
1300                 }
1301         }
1302 }
1303
1304 /* deps hack - do extra recalcs at end */
1305 static void scene_depsgraph_hack(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1306 {
1307         Base *base;
1308                 
1309         scene->customdata_mask = scene_parent->customdata_mask;
1310         
1311         /* sets first, we allow per definition current scene to have
1312          * dependencies on sets, but not the other way around. */
1313         if (scene->set)
1314                 scene_depsgraph_hack(eval_ctx, scene->set, scene_parent);
1315         
1316         for (base = scene->base.first; base; base = base->next) {
1317                 Object *ob = base->object;
1318                 
1319                 if (ob->depsflag) {
1320                         int recalc = 0;
1321                         // printf("depshack %s\n", ob->id.name + 2);
1322                         
1323                         if (ob->depsflag & OB_DEPS_EXTRA_OB_RECALC)
1324                                 recalc |= OB_RECALC_OB;
1325                         if (ob->depsflag & OB_DEPS_EXTRA_DATA_RECALC)
1326                                 recalc |= OB_RECALC_DATA;
1327                         
1328                         ob->recalc |= recalc;
1329                         BKE_object_handle_update(eval_ctx, scene_parent, ob);
1330                         
1331                         if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) {
1332                                 GroupObject *go;
1333                                 
1334                                 for (go = ob->dup_group->gobject.first; go; go = go->next) {
1335                                         if (go->ob)
1336                                                 go->ob->recalc |= recalc;
1337                                 }
1338                                 BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, ob, ob->dup_group);
1339                         }
1340                 }
1341         }
1342 }
1343 #endif  /* WITH_LEGACY_DEPSGRAPH */
1344
1345 /* That's like really a bummer, because currently animation data for armatures
1346  * might want to use pose, and pose might be missing on the object.
1347  * This happens when changing visible layers, which leads to situations when
1348  * pose is missing or marked for recalc, animation will change it and then
1349  * object update will restore the pose.
1350  *
1351  * This could be solved by the new dependency graph, but for until then we'll
1352  * do an extra pass on the objects to ensure it's all fine.
1353  */
1354 #define POSE_ANIMATION_WORKAROUND
1355
1356 #ifdef POSE_ANIMATION_WORKAROUND
1357 static void scene_armature_depsgraph_workaround(Main *bmain)
1358 {
1359         Object *ob;
1360         if (BLI_listbase_is_empty(&bmain->armature) || !DAG_id_type_tagged(bmain, ID_OB)) {
1361                 return;
1362         }
1363         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1364                 if (ob->type == OB_ARMATURE && ob->adt && ob->adt->recalc & ADT_RECALC_ANIM) {
1365                         if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
1366                                 BKE_pose_rebuild(ob, ob->data);
1367                         }
1368                 }
1369         }
1370 }
1371 #endif
1372
1373 #ifdef WITH_LEGACY_DEPSGRAPH
1374 static void scene_rebuild_rbw_recursive(Scene *scene, float ctime)
1375 {
1376         if (scene->set)
1377                 scene_rebuild_rbw_recursive(scene->set, ctime);
1378
1379         if (BKE_scene_check_rigidbody_active(scene))
1380                 BKE_rigidbody_rebuild_world(scene, ctime);
1381 }
1382
1383 static void scene_do_rb_simulation_recursive(Scene *scene, float ctime)
1384 {
1385         if (scene->set)
1386                 scene_do_rb_simulation_recursive(scene->set, ctime);
1387
1388         if (BKE_scene_check_rigidbody_active(scene))
1389                 BKE_rigidbody_do_simulation(scene, ctime);
1390 }
1391 #endif
1392
1393 /* Used to visualize CPU threads activity during threaded object update,
1394  * would pollute STDERR with whole bunch of timing information which then
1395  * could be parsed and nicely visualized.
1396  */
1397 #ifdef WITH_LEGACY_DEPSGRAPH
1398 #  undef DETAILED_ANALYSIS_OUTPUT
1399 #else
1400 /* ALWAYS KEEY DISABLED! */
1401 #  undef DETAILED_ANALYSIS_OUTPUT
1402 #endif
1403
1404 /* Mballs evaluation uses BKE_scene_base_iter_next which calls
1405  * duplilist for all objects in the scene. This leads to conflict
1406  * accessing and writing same data from multiple threads.
1407  *
1408  * Ideally Mballs shouldn't do such an iteration and use DAG
1409  * queries instead. For the time being we've got new DAG
1410  * let's keep it simple and update mballs in a single thread.
1411  */
1412 #define MBALL_SINGLETHREAD_HACK
1413
1414 #ifdef WITH_LEGACY_DEPSGRAPH
1415 typedef struct StatisicsEntry {
1416         struct StatisicsEntry *next, *prev;
1417         Object *object;
1418         double start_time;
1419         double duration;
1420 } StatisicsEntry;
1421
1422 typedef struct ThreadedObjectUpdateState {
1423         /* TODO(sergey): We might want this to be per-thread object. */
1424         EvaluationContext *eval_ctx;
1425         Scene *scene;
1426         Scene *scene_parent;
1427         double base_time;
1428
1429 #ifdef MBALL_SINGLETHREAD_HACK
1430         bool has_mballs;
1431 #endif
1432
1433         /* Execution statistics */
1434         bool has_updated_objects;
1435         ListBase *statistics;
1436 } ThreadedObjectUpdateState;
1437
1438 static void scene_update_object_add_task(void *node, void *user_data);
1439
1440 static void scene_update_all_bases(EvaluationContext *eval_ctx, Scene *scene, Scene *scene_parent)
1441 {
1442         Base *base;
1443
1444         for (base = scene->base.first; base; base = base->next) {
1445                 Object *object = base->object;
1446
1447                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, true);
1448
1449                 if (object->dup_group && (object->transflag & OB_DUPLIGROUP))
1450                         BKE_group_handle_recalc_and_update(eval_ctx, scene_parent, object, object->dup_group);
1451
1452                 /* always update layer, so that animating layers works (joshua july 2010) */
1453                 /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes
1454                  * (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */
1455                 // base->lay = ob->lay;
1456         }
1457 }
1458
1459 static void scene_update_object_func(TaskPool * __restrict pool, void *taskdata, int threadid)
1460 {
1461 /* Disable print for now in favor of summary statistics at the end of update. */
1462 #define PRINT if (false) printf
1463
1464         ThreadedObjectUpdateState *state = (ThreadedObjectUpdateState *) BLI_task_pool_userdata(pool);
1465         void *node = taskdata;
1466         Object *object = DAG_get_node_object(node);
1467         EvaluationContext *eval_ctx = state->eval_ctx;
1468         Scene *scene = state->scene;
1469         Scene *scene_parent = state->scene_parent;
1470
1471 #ifdef MBALL_SINGLETHREAD_HACK
1472         if (object && object->type == OB_MBALL) {
1473                 state->has_mballs = true;
1474         }
1475         else
1476 #endif
1477         if (object) {
1478                 double start_time = 0.0;
1479                 bool add_to_stats = false;
1480
1481                 if (G.debug & G_DEBUG_DEPSGRAPH) {
1482                         if (object->recalc & OB_RECALC_ALL) {
1483                                 printf("Thread %d: update object %s\n", threadid, object->id.name);
1484                         }
1485
1486                         start_time = PIL_check_seconds_timer();
1487
1488                         if (object->recalc & OB_RECALC_ALL) {
1489                                 state->has_updated_objects = true;
1490                                 add_to_stats = true;
1491                         }
1492                 }
1493
1494                 /* We only update object itself here, dupli-group will be updated
1495                  * separately from main thread because of we've got no idea about
1496                  * dependencies inside the group.
1497                  */
1498                 BKE_object_handle_update_ex(eval_ctx, scene_parent, object, scene->rigidbody_world, false);
1499
1500                 /* Calculate statistics. */
1501                 if (add_to_stats) {
1502                         StatisicsEntry *entry;
1503
1504                         BLI_assert(threadid < BLI_pool_get_num_threads(pool));
1505
1506                         entry = MEM_mallocN(sizeof(StatisicsEntry), "update thread statistics");
1507                         entry->object = object;
1508                         entry->start_time = start_time;
1509                         entry->duration = PIL_check_seconds_timer() - start_time;
1510
1511                         BLI_addtail(&state->statistics[threadid], entry);
1512                 }
1513         }
1514         else {
1515                 PRINT("Threda %d: update node %s\n", threadid,
1516                       DAG_get_node_name(scene, node));
1517         }
1518
1519         /* Update will decrease child's valency and schedule child with zero valency. */
1520         DAG_threaded_update_handle_node_updated(node, scene_update_object_add_task, pool);
1521
1522 #undef PRINT
1523 }
1524
1525 static void scene_update_object_add_task(void *node, void *user_data)
1526 {
1527         TaskPool *task_pool = user_data;
1528
1529         BLI_task_pool_push(task_pool, scene_update_object_func, node, false, TASK_PRIORITY_LOW);
1530 }
1531
1532 static void print_threads_statistics(ThreadedObjectUpdateState *state)
1533 {
1534         int i, tot_thread;
1535         double finish_time;
1536
1537         if ((G.debug & G_DEBUG_DEPSGRAPH) == 0) {
1538                 return;
1539         }
1540
1541 #ifdef DETAILED_ANALYSIS_OUTPUT
1542         if (state->has_updated_objects) {
1543                 tot_thread = BLI_system_thread_count();
1544
1545                 fprintf(stderr, "objects update base time %f\n", state->base_time);
1546
1547                 for (i = 0; i < tot_thread; i++) {
1548                         StatisicsEntry *entry;
1549                         for (entry = state->statistics[i].first;
1550                              entry;
1551                              entry = entry->next)
1552                         {
1553                                 fprintf(stderr, "thread %d object %s start_time %f duration %f\n",
1554                                         i, entry->object->id.name + 2,
1555                                         entry->start_time, entry->duration);
1556                         }
1557                         BLI_freelistN(&state->statistics[i]);
1558                 }
1559         }
1560 #else
1561         finish_time = PIL_check_seconds_timer();
1562         tot_thread = BLI_system_thread_count();
1563
1564         for (i = 0; i < tot_thread; i++) {
1565                 int total_objects = 0;
1566                 double total_time = 0.0;
1567                 StatisicsEntry *entry;
1568
1569                 if (state->has_updated_objects) {
1570                         /* Don't pollute output if no objects were updated. */
1571                         for (entry = state->statistics[i].first;
1572                              entry;
1573                              entry = entry->next)
1574                         {
1575                                 total_objects++;
1576                                 total_time += entry->duration;
1577                         }
1578
1579                         printf("Thread %d: total %d objects in %f sec.\n", i, total_objects, total_time);
1580
1581                         for (entry = state->statistics[i].first;
1582                              entry;
1583                              entry = entry->next)
1584                         {
1585                                 printf("  %s in %f sec\n", entry->object->id.name + 2, entry->duration);
1586                         }
1587                 }
1588
1589                 BLI_freelistN(&state->statistics[i]);
1590         }
1591         if (state->has_updated_objects) {
1592                 printf("Scene update in %f sec\n", finish_time - state->base_time);
1593         }
1594 #endif
1595 }
1596
1597 static bool scene_need_update_objects(Main *bmain)
1598 {
1599         return
1600                 /* Object datablocks themselves (for OB_RECALC_OB) */
1601                 DAG_id_type_tagged(bmain, ID_OB) ||
1602
1603                 /* Objects data datablocks (for OB_RECALC_DATA) */
1604                 DAG_id_type_tagged(bmain, ID_ME)  ||  /* Mesh */
1605                 DAG_id_type_tagged(bmain, ID_CU)  ||  /* Curve */
1606                 DAG_id_type_tagged(bmain, ID_MB)  ||  /* MetaBall */
1607                 DAG_id_type_tagged(bmain, ID_LA)  ||  /* Lamp */
1608                 DAG_id_type_tagged(bmain, ID_LT)  ||  /* Lattice */
1609                 DAG_id_type_tagged(bmain, ID_CA)  ||  /* Camera */
1610                 DAG_id_type_tagged(bmain, ID_KE)  ||  /* KE */
1611                 DAG_id_type_tagged(bmain, ID_SPK) ||  /* Speaker */
1612                 DAG_id_type_tagged(bmain, ID_AR);     /* Armature */
1613 }
1614
1615 static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1616 {
1617         TaskScheduler *task_scheduler = BLI_task_scheduler_get();
1618         TaskPool *task_pool;
1619         ThreadedObjectUpdateState state;
1620         bool need_singlethread_pass;
1621
1622         /* Early check for whether we need to invoke all the task-based
1623          * things (spawn new ppol, traverse dependency graph and so on).
1624          *
1625          * Basically if there's no ID datablocks tagged for update which
1626          * corresponds to object->recalc flags (which are checked in
1627          * BKE_object_handle_update() then we do nothing here.
1628          */
1629         if (!scene_need_update_objects(bmain)) {
1630                 return;
1631         }
1632
1633         state.eval_ctx = eval_ctx;
1634         state.scene = scene;
1635         state.scene_parent = scene_parent;
1636
1637         /* Those are only needed when blender is run with --debug argument. */
1638         if (G.debug & G_DEBUG_DEPSGRAPH) {
1639                 const int tot_thread = BLI_task_scheduler_num_threads(task_scheduler);
1640                 state.statistics = MEM_callocN(tot_thread * sizeof(*state.statistics),
1641                                                "scene update objects stats");
1642                 state.has_updated_objects = false;
1643                 state.base_time = PIL_check_seconds_timer();
1644         }
1645
1646 #ifdef MBALL_SINGLETHREAD_HACK
1647         state.has_mballs = false;
1648 #endif
1649
1650         task_pool = BLI_task_pool_create(task_scheduler, &state);
1651         if (G.debug & G_DEBUG_DEPSGRAPH_NO_THREADS) {
1652                 BLI_pool_set_num_threads(task_pool, 1);
1653         }
1654
1655         DAG_threaded_update_begin(scene, scene_update_object_add_task, task_pool);
1656         BLI_task_pool_work_and_wait(task_pool);
1657         BLI_task_pool_free(task_pool);
1658
1659         if (G.debug & G_DEBUG_DEPSGRAPH) {
1660                 print_threads_statistics(&state);
1661                 MEM_freeN(state.statistics);
1662         }
1663
1664         /* We do single thread pass to update all the objects which are in cyclic dependency.
1665          * Such objects can not be handled by a generic DAG traverse and it's really tricky
1666          * to detect whether cycle could be solved or not.
1667          *
1668          * In this situation we simply update all remaining objects in a single thread and
1669          * it'll happen in the same exact order as it was in single-threaded DAG.
1670          *
1671          * We couldn't use threaded update for objects which are in cycle because they might
1672          * access data of each other which is being re-evaluated.
1673          *
1674          * Also, as was explained above, for now we also update all the mballs in single thread.
1675          *
1676          *                                                                   - sergey -
1677          */
1678         need_singlethread_pass = DAG_is_acyclic(scene) == false;
1679 #ifdef MBALL_SINGLETHREAD_HACK
1680         need_singlethread_pass |= state.has_mballs;
1681 #endif
1682
1683         if (need_singlethread_pass) {
1684                 scene_update_all_bases(eval_ctx, scene, scene_parent);
1685         }
1686 }
1687
1688 static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
1689 {
1690         scene->customdata_mask = scene_parent->customdata_mask;
1691
1692         /* sets first, we allow per definition current scene to have
1693          * dependencies on sets, but not the other way around. */
1694         if (scene->set)
1695                 scene_update_tagged_recursive(eval_ctx, bmain, scene->set, scene_parent);
1696
1697         /* scene objects */
1698         scene_update_objects(eval_ctx, bmain, scene, scene_parent);
1699
1700         /* scene drivers... */
1701         scene_update_drivers(bmain, scene);
1702
1703         /* update masking curves */
1704         BKE_mask_update_scene(bmain, scene);
1705         
1706 }
1707 #endif  /* WITH_LEGACY_DEPSGRAPH */
1708
1709 static bool check_rendered_viewport_visible(Main *bmain)
1710 {
1711         wmWindowManager *wm = bmain->wm.first;
1712         wmWindow *window;
1713         for (window = wm->windows.first; window != NULL; window = window->next) {
1714                 bScreen *screen = window->screen;
1715                 ScrArea *area;
1716                 for (area = screen->areabase.first; area != NULL; area = area->next) {
1717                         View3D *v3d = area->spacedata.first;
1718                         if (area->spacetype != SPACE_VIEW3D) {
1719                                 continue;
1720                         }
1721                         if (v3d->drawtype == OB_RENDER) {
1722                                 return true;
1723                         }
1724                 }
1725         }
1726         return false;
1727 }
1728
1729 static void prepare_mesh_for_viewport_render(Main *bmain, Scene *scene)
1730 {
1731         /* This is needed to prepare mesh to be used by the render
1732          * engine from the viewport rendering. We do loading here
1733          * so all the objects which shares the same mesh datablock
1734          * are nicely tagged for update and updated.
1735          *
1736          * This makes it so viewport render engine doesn't need to
1737          * call loading of the edit data for the mesh objects.
1738          */
1739
1740         Object *obedit = scene->obedit;
1741         if (obedit) {
1742                 Mesh *mesh = obedit->data;
1743                 if ((obedit->type == OB_MESH) &&
1744                     ((obedit->id.tag & LIB_TAG_ID_RECALC_ALL) ||
1745                      (mesh->id.tag & LIB_TAG_ID_RECALC_ALL)))
1746                 {
1747                         if (check_rendered_viewport_visible(bmain)) {
1748                                 BMesh *bm = mesh->edit_btmesh->bm;
1749                                 BM_mesh_bm_to_me(bm, mesh, (&(struct BMeshToMeshParams){0}));
1750                                 DAG_id_tag_update(&mesh->id, 0);
1751                         }
1752                 }
1753         }
1754 }
1755
1756 void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *scene)
1757 {
1758         Scene *sce_iter;
1759 #ifdef WITH_LEGACY_DEPSGRAPH
1760         bool use_new_eval = !DEG_depsgraph_use_legacy();
1761 #endif
1762
1763         /* keep this first */
1764         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1765
1766         /* (re-)build dependency graph if needed */
1767         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set) {
1768                 DAG_scene_relations_update(bmain, sce_iter);
1769                 /* Uncomment this to check if graph was properly tagged for update. */
1770 #if 0
1771 #ifdef WITH_LEGACY_DEPSGRAPH
1772                 if (use_new_eval)
1773 #endif
1774                 {
1775                         DAG_scene_relations_validate(bmain, sce_iter);
1776                 }
1777 #endif
1778         }
1779
1780         /* flush editing data if needed */
1781         prepare_mesh_for_viewport_render(bmain, scene);
1782
1783         /* flush recalc flags to dependencies */
1784         DAG_ids_flush_tagged(bmain);
1785
1786         /* removed calls to quick_cache, see pointcache.c */
1787         
1788         /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later
1789          * when trying to find materials with drivers that need evaluating [#32017] 
1790          */
1791         BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false);
1792         BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false);
1793
1794         /* update all objects: drivers, matrices, displists, etc. flags set
1795          * by depgraph or manual, no layer check here, gets correct flushed
1796          *
1797          * in the future this should handle updates for all datablocks, not
1798          * only objects and scenes. - brecht */
1799 #ifdef WITH_LEGACY_DEPSGRAPH
1800         if (!use_new_eval) {
1801                 scene_update_tagged_recursive(eval_ctx, bmain, scene, scene);
1802         }
1803         else
1804 #endif
1805         {
1806                 DEG_evaluate_on_refresh(eval_ctx, scene->depsgraph, scene);
1807                 /* TODO(sergey): This is to beocme a node in new depsgraph. */
1808                 BKE_mask_update_scene(bmain, scene);
1809         }
1810
1811         /* update sound system animation (TODO, move to depsgraph) */
1812         BKE_sound_update_scene(bmain, scene);
1813
1814         /* extra call here to recalc scene animation (for sequencer) */
1815         {
1816                 AnimData *adt = BKE_animdata_from_id(&scene->id);
1817                 float ctime = BKE_scene_frame_get(scene);
1818                 
1819                 if (adt && (adt->recalc & ADT_RECALC_ANIM))
1820                         BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0);
1821         }
1822
1823         /* Extra call here to recalc material animation.
1824          *
1825          * Need to do this so changing material settings from the graph/dopesheet
1826          * will update stuff in the viewport.
1827          */
1828 #ifdef WITH_LEGACY_DEPSGRAPH
1829         if (!use_new_eval && DAG_id_type_tagged(bmain, ID_MA)) {
1830                 Material *material;
1831                 float ctime = BKE_scene_frame_get(scene);
1832
1833                 for (material = bmain->mat.first;
1834                      material;
1835                      material = material->id.next)
1836                 {
1837                         AnimData *adt = BKE_animdata_from_id(&material->id);
1838                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1839                                 BKE_animsys_evaluate_animdata(scene, &material->id, adt, ctime, 0);
1840                 }
1841         }
1842
1843         /* Also do the same for node trees. */
1844         if (!use_new_eval && DAG_id_type_tagged(bmain, ID_NT)) {
1845                 float ctime = BKE_scene_frame_get(scene);
1846
1847                 FOREACH_NODETREE(bmain, ntree, id)
1848                 {
1849                         AnimData *adt = BKE_animdata_from_id(&ntree->id);
1850                         if (adt && (adt->recalc & ADT_RECALC_ANIM))
1851                                 BKE_animsys_evaluate_animdata(scene, &ntree->id, adt, ctime, 0);
1852                 }
1853                 FOREACH_NODETREE_END
1854         }
1855 #endif
1856
1857         /* notify editors and python about recalc */
1858         BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1859
1860         /* Inform editors about possible changes. */
1861         DAG_ids_check_recalc(bmain, scene, false);
1862
1863         /* clear recalc flags */
1864         DAG_ids_clear_recalc(bmain);
1865 }
1866
1867 /* applies changes right away, does all sets too */
1868 void BKE_scene_update_for_newframe(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay)
1869 {
1870         BKE_scene_update_for_newframe_ex(eval_ctx, bmain, sce, lay, false);
1871 }
1872
1873 void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain, Scene *sce, unsigned int lay, bool do_invisible_flush)
1874 {
1875         float ctime = BKE_scene_frame_get(sce);
1876         Scene *sce_iter;
1877 #ifdef DETAILED_ANALYSIS_OUTPUT
1878         double start_time = PIL_check_seconds_timer();
1879 #endif
1880 #ifdef WITH_LEGACY_DEPSGRAPH
1881         bool use_new_eval = !DEG_depsgraph_use_legacy();
1882 #else
1883         /* TODO(sergey): Pass to evaluation routines instead of storing layer in the graph? */
1884         (void) do_invisible_flush;
1885 #endif
1886
1887         DAG_editors_update_pre(bmain, sce, true);
1888
1889         /* keep this first */
1890         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_PRE);
1891         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_PRE);
1892
1893         /* update animated image textures for particles, modifiers, gpu, etc,
1894          * call this at the start so modifiers with textures don't lag 1 frame */
1895         BKE_image_update_frame(bmain, sce->r.cfra);
1896         
1897 #ifdef WITH_LEGACY_DEPSGRAPH
1898         /* rebuild rigid body worlds before doing the actual frame update
1899          * this needs to be done on start frame but animation playback usually starts one frame later
1900          * we need to do it here to avoid rebuilding the world on every simulation change, which can be very expensive
1901          */
1902         if (!use_new_eval) {
1903                 scene_rebuild_rbw_recursive(sce, ctime);
1904         }
1905 #endif
1906         
1907         BKE_sound_set_cfra(sce->r.cfra);
1908         
1909         /* clear animation overrides */
1910         /* XXX TODO... */
1911
1912         for (sce_iter = sce; sce_iter; sce_iter = sce_iter->set)
1913                 DAG_scene_relations_update(bmain, sce_iter);
1914
1915 #ifdef WITH_LEGACY_DEPSGRAPH
1916         if (!use_new_eval) {
1917                 /* flush recalc flags to dependencies, if we were only changing a frame
1918                  * this would not be necessary, but if a user or a script has modified
1919                  * some datablock before BKE_scene_update_tagged was called, we need the flush */
1920                 DAG_ids_flush_tagged(bmain);
1921
1922                 /* Following 2 functions are recursive
1923                  * so don't call within 'scene_update_tagged_recursive' */
1924                 DAG_scene_update_flags(bmain, sce, lay, true, do_invisible_flush);   // only stuff that moves or needs display still
1925         }
1926 #endif
1927
1928         BKE_mask_evaluate_all_masks(bmain, ctime, true);
1929
1930         /* Update animated cache files for modifiers. */
1931         BKE_cachefile_update_frame(bmain, sce, ctime, (((double)sce->r.frs_sec) / (double)sce->r.frs_sec_base));
1932
1933 #ifdef POSE_ANIMATION_WORKAROUND
1934         scene_armature_depsgraph_workaround(bmain);
1935 #endif
1936
1937         /* All 'standard' (i.e. without any dependencies) animation is handled here,
1938          * with an 'local' to 'macro' order of evaluation. This should ensure that
1939          * settings stored nestled within a hierarchy (i.e. settings in a Texture block
1940          * can be overridden by settings from Scene, which owns the Texture through a hierarchy
1941          * such as Scene->World->MTex/Texture) can still get correctly overridden.
1942          */
1943 #ifdef WITH_LEGACY_DEPSGRAPH
1944         if (!use_new_eval) {
1945                 BKE_animsys_evaluate_all_animation(bmain, sce, ctime);
1946                 /*...done with recursive funcs */
1947         }
1948 #endif
1949
1950         /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later
1951          * when trying to find materials with drivers that need evaluating [#32017] 
1952          */
1953         BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false);
1954         BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false);
1955
1956         /* run rigidbody sim */
1957         /* NOTE: current position is so that rigidbody sim affects other objects, might change in the future */
1958 #ifdef WITH_LEGACY_DEPSGRAPH
1959         if (!use_new_eval) {
1960                 scene_do_rb_simulation_recursive(sce, ctime);
1961         }
1962 #endif
1963         
1964         /* BKE_object_handle_update() on all objects, groups and sets */
1965 #ifdef WITH_LEGACY_DEPSGRAPH
1966         if (use_new_eval) {
1967                 DEG_evaluate_on_framechange(eval_ctx, bmain, sce->depsgraph, ctime, lay);
1968         }
1969         else {
1970                 scene_update_tagged_recursive(eval_ctx, bmain, sce, sce);
1971         }
1972 #else
1973         DEG_evaluate_on_framechange(eval_ctx, bmain, sce->depsgraph, ctime, lay);
1974 #endif
1975
1976         /* update sound system animation (TODO, move to depsgraph) */
1977         BKE_sound_update_scene(bmain, sce);
1978
1979 #ifdef WITH_LEGACY_DEPSGRAPH
1980         if (!use_new_eval) {
1981                 scene_depsgraph_hack(eval_ctx, sce, sce);
1982         }
1983 #endif
1984
1985         /* notify editors and python about recalc */
1986         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_SCENE_UPDATE_POST);
1987         BLI_callback_exec(bmain, &sce->id, BLI_CB_EVT_FRAME_CHANGE_POST);
1988
1989         /* Inform editors about possible changes. */
1990         DAG_ids_check_recalc(bmain, sce, true);
1991
1992         /* clear recalc flags */
1993         DAG_ids_clear_recalc(bmain);
1994
1995 #ifdef DETAILED_ANALYSIS_OUTPUT
1996         fprintf(stderr, "frame update start_time %f duration %f\n", start_time, PIL_check_seconds_timer() - start_time);
1997 #endif
1998 }
1999
2000 /* return default layer, also used to patch old files */
2001 SceneRenderLayer *BKE_scene_add_render_layer(Scene *sce, const char *name)
2002 {
2003         SceneRenderLayer *srl;
2004
2005         if (!name)
2006                 name = DATA_("RenderLayer");
2007
2008         srl = MEM_callocN(sizeof(SceneRenderLayer), "new render layer");
2009         BLI_strncpy(srl->name, name, sizeof(srl->name));
2010         BLI_uniquename(&sce->r.layers, srl, DATA_("RenderLayer"), '.', offsetof(SceneRenderLayer, name), sizeof(srl->name));
2011         BLI_addtail(&sce->r.layers, srl);
2012
2013         /* note, this is also in render, pipeline.c, to make layer when scenedata doesnt have it */
2014         srl->lay = (1 << 20) - 1;
2015         srl->layflag = 0x7FFF;   /* solid ztra halo edge strand */
2016         srl->passflag = SCE_PASS_COMBINED | SCE_PASS_Z;
2017         srl->pass_alpha_threshold = 0.5f;
2018         BKE_freestyle_config_init(&srl->freestyleConfig);
2019
2020         return srl;
2021 }
2022
2023 bool BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *srl)
2024 {
2025         const int act = BLI_findindex(&scene->r.layers, srl);
2026         Scene *sce;
2027
2028         if (act == -1) {
2029                 return false;
2030         }
2031         else if ( (scene->r.layers.first == scene->r.layers.last) &&
2032                   (scene->r.layers.first == srl))
2033         {
2034                 /* ensure 1 layer is kept */
2035                 return false;
2036         }
2037
2038         BLI_remlink(&scene->r.layers, srl);
2039         MEM_freeN(srl);
2040
2041         scene->r.actlay = 0;
2042
2043         for (sce = bmain->scene.first; sce; sce = sce->id.next) {
2044                 if (sce->nodetree) {
2045                         bNode *node;
2046                         for (node = sce->nodetree->nodes.first; node; node = node->next) {
2047                                 if (node->type == CMP_NODE_R_LAYERS && (Scene *)node->id == scene) {
2048                                         if (node->custom1 == act)
2049                                                 node->custom1 = 0;
2050                                         else if (node->custom1 > act)
2051                                                 node->custom1--;
2052                                 }
2053                         }
2054                 }
2055         }
2056
2057         return true;
2058 }
2059
2060 /* return default view */
2061 SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name)
2062 {
2063         SceneRenderView *srv;
2064
2065         if (!name)
2066                 name = DATA_("RenderView");
2067
2068         srv = MEM_callocN(sizeof(SceneRenderView), "new render view");
2069         BLI_strncpy(srv->name, name, sizeof(srv->name));
2070         BLI_uniquename(&sce->r.views, srv, DATA_("RenderView"), '.', offsetof(SceneRenderView, name), sizeof(srv->name));
2071         BLI_addtail(&sce->r.views, srv);
2072
2073         return srv;
2074 }
2075
2076 bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
2077 {
2078         const int act = BLI_findindex(&scene->r.views, srv);
2079
2080         if (act == -1) {
2081                 return false;
2082         }
2083         else if (scene->r.views.first == scene->r.views.last) {
2084                 /* ensure 1 view is kept */
2085                 return false;
2086         }
2087
2088         BLI_remlink(&scene->r.views, srv);
2089         MEM_freeN(srv);
2090
2091         scene->r.actview = 0;
2092
2093         return true;
2094 }
2095
2096 /* render simplification */
2097
2098 int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
2099 {
2100         if (r->mode & R_SIMPLIFY)  {
2101                 if (for_render)
2102                         return min_ii(r->simplify_subsurf_render, lvl);
2103                 else
2104                         return min_ii(r->simplify_subsurf, lvl);
2105         }
2106         else {
2107                 return lvl;
2108         }
2109 }
2110
2111 int get_render_child_particle_number(const RenderData *r, int num, bool for_render)
2112 {
2113         if (r->mode & R_SIMPLIFY) {
2114                 if (for_render)
2115                         return (int)(r->simplify_particles_render * num);
2116                 else
2117                         return (int)(r->simplify_particles * num);
2118         }
2119         else {
2120                 return num;
2121         }
2122 }
2123
2124 int get_render_shadow_samples(const RenderData *r, int samples)
2125 {
2126         if ((r->mode & R_SIMPLIFY) && samples > 0)
2127                 return min_ii(r->simplify_shadowsamples, samples);
2128         else
2129                 return samples;
2130 }
2131
2132 float get_render_aosss_error(const RenderData *r, float error)
2133 {
2134         if (r->mode & R_SIMPLIFY)
2135                 return ((1.0f - r->simplify_aosss) * 10.0f + 1.0f) * error;
2136         else
2137                 return error;
2138 }
2139
2140 /* helper function for the SETLOOPER macro */
2141 Base *_setlooper_base_step(Scene **sce_iter, Base *base)
2142 {
2143         if (base && base->next) {
2144                 /* common case, step to the next */
2145                 return base->next;
2146         }
2147         else if (base == NULL && (*sce_iter)->base.first) {
2148                 /* first time looping, return the scenes first base */
2149                 return (Base *)(*sce_iter)->base.first;
2150         }
2151         else {
2152                 /* reached the end, get the next base in the set */
2153                 while ((*sce_iter = (*sce_iter)->set)) {
2154                         base = (Base *)(*sce_iter)->base.first;
2155                         if (base) {
2156                                 return base;
2157                         }
2158                 }
2159         }
2160
2161         return NULL;
2162 }
2163
2164 bool BKE_scene_use_new_shading_nodes(const Scene *scene)
2165 {
2166         const RenderEngineType *type = RE_engines_find(scene->r.engine);
2167         return (type && type->flag & RE_USE_SHADING_NODES);
2168 }
2169
2170 bool BKE_scene_use_shading_nodes_custom(Scene *scene)
2171 {
2172         RenderEngineType *type = RE_engines_find(scene->r.engine);
2173         return (type && type->flag & RE_USE_SHADING_NODES_CUSTOM);
2174 }
2175
2176 bool BKE_scene_use_world_space_shading(Scene *scene)
2177 {
2178         const RenderEngineType *type = RE_engines_find(scene->r.engine);
2179         return ((scene->r.mode & R_USE_WS_SHADING) ||
2180                 (type && (type->flag & RE_USE_SHADING_NODES)));
2181 }
2182
2183 bool BKE_scene_use_spherical_stereo(Scene *scene)
2184 {
2185         RenderEngineType *type = RE_engines_find(scene->r.engine);
2186         return (type && type->flag & RE_USE_SPHERICAL_STEREO);
2187 }
2188
2189 bool BKE_scene_uses_blender_internal(const  Scene *scene)
2190 {
2191         return STREQ(scene->r.engine, RE_engine_id_BLENDER_RENDER);
2192 }
2193
2194 bool BKE_scene_uses_blender_game(const Scene *scene)
2195 {
2196         return STREQ(scene->r.engine, RE_engine_id_BLENDER_GAME);
2197 }
2198
2199 void BKE_scene_base_flag_to_objects(struct Scene *scene)
2200 {
2201         Base *base = scene->base.first;
2202
2203         while (base) {
2204                 base->object->flag = base->flag;
2205                 base = base->next;
2206         }
2207 }
2208
2209 void BKE_scene_base_flag_from_objects(struct Scene *scene)
2210 {
2211         Base *base = scene->base.first;
2212
2213         while (base) {
2214                 base->flag = base->object->flag;
2215                 base = base->next;
2216         }
2217 }
2218
2219 void BKE_scene_disable_color_management(Scene *scene)
2220 {
2221         ColorManagedDisplaySettings *display_settings = &scene->display_settings;
2222         ColorManagedViewSettings *view_settings = &scene->view_settings;
2223         const char *view;
2224         const char *none_display_name;
2225
2226         none_display_name = IMB_colormanagement_display_get_none_name();
2227
2228         BLI_strncpy(display_settings->display_device, none_display_name, sizeof(display_settings->display_device));
2229
2230         view = IMB_colormanagement_view_get_default_name(display_settings->display_device);
2231
2232         if (view) {
2233                 BLI_strncpy(view_settings->view_transform, view, sizeof(view_settings->view_transform));
2234         }
2235 }
2236
2237 bool BKE_scene_check_color_management_enabled(const Scene *scene)
2238 {
2239         return !STREQ(scene->display_settings.display_device, "None");
2240 }
2241
2242 bool BKE_scene_check_rigidbody_active(const Scene *scene)
2243 {
2244         return scene && scene->rigidbody_world && scene->rigidbody_world->group && !(scene->rigidbody_world->flag & RBW_FLAG_MUTED);
2245 }
2246
2247 int BKE_render_num_threads(const RenderData *rd)
2248 {
2249         int threads;
2250
2251         /* override set from command line? */
2252         threads = BLI_system_num_threads_override_get();
2253
2254         if (threads > 0)
2255                 return threads;
2256
2257         /* fixed number of threads specified in scene? */
2258         if (rd->mode & R_FIXED_THREADS)
2259                 threads = rd->threads;
2260         else
2261                 threads = BLI_system_thread_count();
2262         
2263         return max_ii(threads, 1);
2264 }
2265
2266 int BKE_scene_num_threads(const Scene *scene)
2267 {
2268         return BKE_render_num_threads(&scene->r);
2269 }
2270
2271 /* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently)
2272  * and unit->scale_length.
2273  */
2274 double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value)
2275 {
2276         if (unit->system == USER_UNIT_NONE) {
2277                 /* Never apply scale_length when not using a unit setting! */
2278                 return value;
2279         }
2280
2281         switch (unit_type) {
2282                 case B_UNIT_LENGTH:
2283                         return value * (double)unit->scale_length;
2284                 case B_UNIT_AREA:
2285                         return value * pow(unit->scale_length, 2);
2286                 case B_UNIT_VOLUME:
2287                         return value * pow(unit->scale_length, 3);
2288                 case B_UNIT_MASS:
2289                         return value * pow(unit->scale_length, 3);
2290                 case B_UNIT_CAMERA:  /* *Do not* use scene's unit scale for camera focal lens! See T42026. */
2291                 default:
2292                         return value;
2293         }
2294 }
2295
2296 /******************** multiview *************************/
2297
2298 int BKE_scene_multiview_num_views_get(const RenderData *rd)
2299 {
2300         SceneRenderView *srv;
2301         int totviews = 0;
2302
2303         if ((rd->scemode & R_MULTIVIEW) == 0)
2304                 return 1;
2305
2306         if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
2307                 srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
2308                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2309                         totviews++;
2310                 }
2311
2312                 srv = BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
2313                 if ((srv && srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2314                         totviews++;
2315                 }
2316         }
2317         else {
2318                 for (srv = rd->views.first; srv; srv = srv->next) {
2319                         if ((srv->viewflag & SCE_VIEW_DISABLE) == 0) {
2320                                 totviews++;
2321                         }
2322                 }
2323         }
2324         return totviews;
2325 }
2326
2327 bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
2328 {
2329         SceneRenderView *srv[2];
2330
2331         if ((rd->scemode & R_MULTIVIEW) == 0)
2332                 return false;
2333
2334         srv[0] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name));
2335         srv[1] = (SceneRenderView *)BLI_findstring(&rd->views, STEREO_RIGHT_NAME, offsetof(SceneRenderView, name));
2336
2337         return (srv[0] && ((srv[0]->viewflag & SCE_VIEW_DISABLE) == 0) &&
2338                 srv[1] && ((srv[1]->viewflag & SCE_VIEW_DISABLE) == 0));
2339 }
2340
2341 /* return whether to render this SceneRenderView */
2342 bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv)
2343 {
2344         if (srv == NULL)
2345                 return false;
2346
2347         if ((rd->scemode & R_MULTIVIEW) == 0)
2348                 return false;
2349
2350         if ((srv->viewflag & SCE_VIEW_DISABLE))
2351                 return false;
2352
2353         if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW)
2354                 return true;
2355
2356         /* SCE_VIEWS_SETUP_BASIC */
2357         if (STREQ(srv->name, STEREO_LEFT_NAME) ||
2358             STREQ(srv->name, STEREO_RIGHT_NAME))
2359         {
2360                 return true;
2361         }
2362
2363         return false;
2364 }
2365
2366 /* return true if viewname is the first or if the name is NULL or not found */
2367 bool BKE_scene_multiview_is_render_view_first(const RenderData *rd, const char *viewname)
2368 {
2369         SceneRenderView *srv;
2370
2371         if ((rd->scemode & R_MULTIVIEW) == 0)
2372                 return true;
2373
2374         if ((!viewname) || (!viewname[0]))
2375                 return true;
2376
2377         for (srv = rd->views.first; srv; srv = srv->next) {
2378                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2379                         return STREQ(viewname, srv->name);
2380                 }
2381         }
2382
2383         return true;
2384 }
2385
2386 /* return true if viewname is the last or if the name is NULL or not found */
2387 bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *viewname)
2388 {
2389         SceneRenderView *srv;
2390
2391         if ((rd->scemode & R_MULTIVIEW) == 0)
2392                 return true;
2393
2394         if ((!viewname) || (!viewname[0]))
2395                 return true;
2396
2397         for (srv = rd->views.last; srv; srv = srv->prev) {
2398                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2399                         return STREQ(viewname, srv->name);
2400                 }
2401         }
2402
2403         return true;
2404 }
2405
2406 SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, const int view_id)
2407 {
2408         SceneRenderView *srv;
2409         size_t nr;
2410
2411         if ((rd->scemode & R_MULTIVIEW) == 0)
2412                 return NULL;
2413
2414         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2415                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2416                         if (nr++ == view_id)
2417                                 return srv;
2418                 }
2419         }
2420         return srv;
2421 }
2422
2423 const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const int view_id)
2424 {
2425         SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id);
2426
2427         if (srv)
2428                 return srv->name;
2429         else
2430                 return "";
2431 }
2432
2433 int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname)
2434 {
2435         SceneRenderView *srv;
2436         size_t nr;
2437
2438         if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0))
2439                 return 0;
2440
2441         if ((!viewname) || (!viewname[0]))
2442                 return 0;
2443
2444         for (srv = rd->views.first, nr = 0; srv; srv = srv->next) {
2445                 if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
2446                         if (STREQ(viewname, srv->name)) {
2447                                 return nr;
2448                         }
2449                         else {
2450                                 nr += 1;
2451                         }
2452                 }
2453         }
2454
2455         return 0;
2456 }
2457
2458 void BKE_scene_multiview_filepath_get(
2459         SceneRenderView *srv, const char *filepath,
2460         char *r_filepath)
2461 {
2462         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2463         BLI_path_suffix(r_filepath, FILE_MAX, srv->suffix, "");
2464 }
2465
2466 /**
2467  * When multiview is not used the filepath is as usual (e.g., ``Image.jpg``).
2468  * When multiview is on, even if only one view is enabled the view is incorporated
2469  * into the file name (e.g., ``Image_L.jpg``). That allows for the user to re-render
2470  * individual views.
2471  */
2472 void BKE_scene_multiview_view_filepath_get(
2473         const RenderData *rd, const char *filepath, const char *viewname,
2474         char *r_filepath)
2475 {
2476         SceneRenderView *srv;
2477         char suffix[FILE_MAX];
2478
2479         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2480         if (srv)
2481                 BLI_strncpy(suffix, srv->suffix, sizeof(suffix));
2482         else
2483                 BLI_strncpy(suffix, viewname, sizeof(suffix));
2484
2485         BLI_strncpy(r_filepath, filepath, FILE_MAX);
2486         BLI_path_suffix(r_filepath, FILE_MAX, suffix, "");
2487 }
2488
2489 const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char *viewname)
2490 {
2491         SceneRenderView *srv;
2492
2493         if ((viewname == NULL) || (viewname[0] == '\0'))
2494                 return viewname;
2495
2496         srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name));
2497         if (srv)
2498                 return srv->suffix;
2499         else
2500                 return viewname;
2501 }
2502
2503 const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id)
2504 {
2505         if ((rd->scemode & R_MULTIVIEW) == 0) {
2506                 return "";
2507         }
2508         else {
2509                 const char *viewname = BKE_scene_multiview_render_view_name_get(rd, view_id);
2510                 return BKE_scene_multiview_view_suffix_get(rd, viewname);
2511         }
2512 }
2513
2514 void BKE_scene_multiview_view_prefix_get(Scene *scene, const char *name, char *rprefix, const char **rext)
2515 {
2516         SceneRenderView *srv;
2517         size_t index_act;
2518         const char *suf_act;
2519         const char delims[] = {'.', '\0'};
2520
2521         rprefix[0] = '\0';
2522
2523         /* begin of extension */
2524         index_act = BLI_str_rpartition(name, delims, rext, &suf_act);
2525         if (*rext == NULL)
2526                 return;
2527         BLI_assert(index_act > 0);
2528         UNUSED_VARS_NDEBUG(index_act);
2529
2530         for (srv = scene->r.views.first; srv; srv = srv->next) {
2531                 if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
2532                         size_t len = strlen(srv->suffix);
2533                         if (strlen(*rext) >= len && STREQLEN(*rext - len, srv->suffix, len)) {
2534                                 BLI_strncpy(rprefix, name, strlen(name) - strlen(*rext) - len + 1);
2535                                 break;
2536                         }
2537                 }
2538         }
2539 }
2540
2541 void BKE_scene_multiview_videos_dimensions_get(
2542         const RenderData *rd, const size_t width, const size_t height,
2543         size_t *r_width, size_t *r_height)
2544 {
2545         if ((rd->scemode & R_MULTIVIEW) &&
2546             rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D)
2547         {
2548                 IMB_stereo3d_write_dimensions(
2549                         rd->im_format.stereo3d_format.display_mode,
2550                         (rd->im_format.stereo3d_format.flag & S3D_SQUEEZED_FRAME) != 0,
2551                         width, height,
2552                         r_width, r_height);
2553         }
2554         else {
2555                 *r_width = width;
2556                 *r_height = height;
2557         }
2558 }
2559
2560 int BKE_scene_multiview_num_videos_get(const RenderData *rd)
2561 {
2562         if (BKE_imtype_is_movie(rd->im_format.imtype) == false)
2563                 return 0;
2564
2565         if ((rd->scemode & R_MULTIVIEW) == 0)
2566                 return 1;
2567
2568         if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
2569                 return 1;
2570         }
2571         else {
2572                 /* R_IMF_VIEWS_INDIVIDUAL */
2573                 return BKE_scene_multiview_num_views_get(rd);
2574         }
2575 }