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