GP: Back Stroke projection mode
[blender.git] / intern / cycles / blender / blender_sync.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "render/background.h"
18 #include "render/camera.h"
19 #include "render/film.h"
20 #include "render/graph.h"
21 #include "render/integrator.h"
22 #include "render/light.h"
23 #include "render/mesh.h"
24 #include "render/nodes.h"
25 #include "render/object.h"
26 #include "render/scene.h"
27 #include "render/shader.h"
28 #include "render/curves.h"
29
30 #include "device/device.h"
31
32 #include "blender/blender_sync.h"
33 #include "blender/blender_session.h"
34 #include "blender/blender_util.h"
35
36 #include "util/util_debug.h"
37 #include "util/util_foreach.h"
38 #include "util/util_opengl.h"
39 #include "util/util_hash.h"
40
41 CCL_NAMESPACE_BEGIN
42
43 static const char *cryptomatte_prefix = "Crypto";
44
45 /* Constructor */
46
47 BlenderSync::BlenderSync(BL::RenderEngine& b_engine,
48                          BL::BlendData& b_data,
49                          BL::Scene& b_scene,
50                          Scene *scene,
51                          bool preview,
52                          Progress &progress)
53 : b_engine(b_engine),
54   b_data(b_data),
55   b_scene(b_scene),
56   shader_map(&scene->shaders),
57   object_map(&scene->objects),
58   mesh_map(&scene->meshes),
59   light_map(&scene->lights),
60   particle_system_map(&scene->particle_systems),
61   world_map(NULL),
62   world_recalc(false),
63   scene(scene),
64   preview(preview),
65   experimental(false),
66   dicing_rate(1.0f),
67   max_subdivisions(12),
68   progress(progress)
69 {
70         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
71         dicing_rate = preview ? RNA_float_get(&cscene, "preview_dicing_rate") : RNA_float_get(&cscene, "dicing_rate");
72         max_subdivisions = RNA_int_get(&cscene, "max_subdivisions");
73 }
74
75 BlenderSync::~BlenderSync()
76 {
77 }
78
79 /* Sync */
80
81 void BlenderSync::sync_recalc(BL::Depsgraph& b_depsgraph)
82 {
83         /* Sync recalc flags from blender to cycles. Actual update is done separate,
84          * so we can do it later on if doing it immediate is not suitable. */
85
86         bool has_updated_objects = b_depsgraph.id_type_updated(BL::DriverTarget::id_type_OBJECT);
87         bool dicing_prop_changed = false;
88
89         if(experimental) {
90                 PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
91
92                 float updated_dicing_rate = preview ? RNA_float_get(&cscene, "preview_dicing_rate")
93                                                     : RNA_float_get(&cscene, "dicing_rate");
94
95                 if(dicing_rate != updated_dicing_rate) {
96                         dicing_rate = updated_dicing_rate;
97                         dicing_prop_changed = true;
98                 }
99
100                 int updated_max_subdivisions = RNA_int_get(&cscene, "max_subdivisions");
101
102                 if(max_subdivisions != updated_max_subdivisions) {
103                         max_subdivisions = updated_max_subdivisions;
104                         dicing_prop_changed = true;
105                 }
106         }
107
108         /* Iterate over all IDs in this depsgraph. */
109         BL::Depsgraph::updates_iterator b_update;
110         for(b_depsgraph.updates.begin(b_update); b_update != b_depsgraph.updates.end(); ++b_update) {
111                 BL::ID b_id(b_update->id());
112
113                 /* Material */
114                 if (b_id.is_a(&RNA_Material)) {
115                         BL::Material b_mat(b_id);
116                         shader_map.set_recalc(b_mat);
117                 }
118                 /* Light */
119                 else if (b_id.is_a(&RNA_Light)) {
120                         BL::Light b_light(b_id);
121                         shader_map.set_recalc(b_light);
122                 }
123                 /* Object */
124                 else if (b_id.is_a(&RNA_Object)) {
125                         BL::Object b_ob(b_id);
126                         const bool updated_geometry = !b_update->is_dirty_geometry();
127
128                         if (!b_update->is_dirty_transform()) {
129                                 object_map.set_recalc(b_ob);
130                                 light_map.set_recalc(b_ob);
131                         }
132
133                         if(object_is_mesh(b_ob)) {
134                                 if(updated_geometry ||
135                                    (dicing_prop_changed && object_subdivision_type(b_ob, preview, experimental) != Mesh::SUBDIVISION_NONE))
136                                 {
137                                         BL::ID key = BKE_object_is_modified(b_ob)? b_ob: b_ob.data();
138                                         mesh_map.set_recalc(key);
139                                 }
140                         }
141                         else if(object_is_light(b_ob)) {
142                                 if(updated_geometry) {
143                                         light_map.set_recalc(b_ob);
144                                 }
145                         }
146
147                         if(updated_geometry) {
148                                 BL::Object::particle_systems_iterator b_psys;
149                                 for(b_ob.particle_systems.begin(b_psys); b_psys != b_ob.particle_systems.end(); ++b_psys)
150                                         particle_system_map.set_recalc(b_ob);
151                         }
152                 }
153                 /* Mesh */
154                 else if (b_id.is_a(&RNA_Mesh)) {
155                         BL::Mesh b_mesh(b_id);
156                         mesh_map.set_recalc(b_mesh);
157                 }
158                 /* World */
159                 else if (b_id.is_a(&RNA_World)) {
160                         BL::World b_world(b_id);
161                         if(world_map == b_world.ptr.data) {
162                                 world_recalc = true;
163                         }
164                 }
165         }
166
167         /* Updates shader with object dependency if objects changed. */
168         if (has_updated_objects) {
169                 if(scene->default_background->has_object_dependency) {
170                         world_recalc = true;
171                 }
172
173                 foreach(Shader *shader, scene->shaders) {
174                         if (shader->has_object_dependency) {
175                                 shader->need_sync_object = true;
176                         }
177                 }
178         }
179 }
180
181 void BlenderSync::sync_data(BL::RenderSettings& b_render,
182                             BL::Depsgraph& b_depsgraph,
183                             BL::SpaceView3D& b_v3d,
184                             BL::Object& b_override,
185                             int width, int height,
186                             void **python_thread_state)
187 {
188         BL::ViewLayer b_view_layer = b_depsgraph.view_layer_eval();
189
190         sync_view_layer(b_v3d, b_view_layer);
191         sync_integrator();
192         sync_film();
193         sync_shaders(b_depsgraph);
194         sync_images();
195         sync_curve_settings();
196
197         mesh_synced.clear(); /* use for objects and motion sync */
198
199         if(scene->need_motion() == Scene::MOTION_PASS ||
200            scene->need_motion() == Scene::MOTION_NONE ||
201            scene->camera->motion_position == Camera::MOTION_POSITION_CENTER)
202         {
203                 sync_objects(b_depsgraph);
204         }
205         sync_motion(b_render,
206                     b_depsgraph,
207                     b_override,
208                     width, height,
209                     python_thread_state);
210
211         mesh_synced.clear();
212
213         free_data_after_sync(b_depsgraph);
214 }
215
216 /* Integrator */
217
218 void BlenderSync::sync_integrator()
219 {
220         BL::RenderSettings r = b_scene.render();
221         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
222
223         experimental = (get_enum(cscene, "feature_set") != 0);
224
225         Integrator *integrator = scene->integrator;
226         Integrator previntegrator = *integrator;
227
228         integrator->max_bounce = get_int(cscene, "max_bounces");
229
230         integrator->max_diffuse_bounce = get_int(cscene, "diffuse_bounces");
231         integrator->max_glossy_bounce = get_int(cscene, "glossy_bounces");
232         integrator->max_transmission_bounce = get_int(cscene, "transmission_bounces");
233         integrator->max_volume_bounce = get_int(cscene, "volume_bounces");
234
235         integrator->transparent_max_bounce = get_int(cscene, "transparent_max_bounces");
236
237         integrator->volume_max_steps = get_int(cscene, "volume_max_steps");
238         integrator->volume_step_size = get_float(cscene, "volume_step_size");
239
240         integrator->caustics_reflective = get_boolean(cscene, "caustics_reflective");
241         integrator->caustics_refractive = get_boolean(cscene, "caustics_refractive");
242         integrator->filter_glossy = get_float(cscene, "blur_glossy");
243
244         integrator->seed = get_int(cscene, "seed");
245         if(get_boolean(cscene, "use_animated_seed")) {
246                 integrator->seed = hash_int_2d(b_scene.frame_current(),
247                                                get_int(cscene, "seed"));
248                 if(b_scene.frame_subframe() != 0.0f) {
249                         /* TODO(sergey): Ideally should be some sort of hash_merge,
250                          * but this is good enough for now.
251                          */
252                         integrator->seed += hash_int_2d((int)(b_scene.frame_subframe() * (float)INT_MAX),
253                                                         get_int(cscene, "seed"));
254                 }
255         }
256
257         integrator->sampling_pattern = (SamplingPattern)get_enum(
258                 cscene,
259                 "sampling_pattern",
260                 SAMPLING_NUM_PATTERNS,
261                 SAMPLING_PATTERN_SOBOL);
262
263         integrator->sample_clamp_direct = get_float(cscene, "sample_clamp_direct");
264         integrator->sample_clamp_indirect = get_float(cscene, "sample_clamp_indirect");
265         if(!preview) {
266                 if(integrator->motion_blur != r.use_motion_blur()) {
267                         scene->object_manager->tag_update(scene);
268                         scene->camera->tag_update();
269                 }
270
271                 integrator->motion_blur = r.use_motion_blur();
272         }
273
274         integrator->method = (Integrator::Method)get_enum(cscene,
275                                                           "progressive",
276                                                           Integrator::NUM_METHODS,
277                                                           Integrator::PATH);
278
279         integrator->sample_all_lights_direct = get_boolean(cscene, "sample_all_lights_direct");
280         integrator->sample_all_lights_indirect = get_boolean(cscene, "sample_all_lights_indirect");
281         integrator->light_sampling_threshold = get_float(cscene, "light_sampling_threshold");
282
283         int diffuse_samples = get_int(cscene, "diffuse_samples");
284         int glossy_samples = get_int(cscene, "glossy_samples");
285         int transmission_samples = get_int(cscene, "transmission_samples");
286         int ao_samples = get_int(cscene, "ao_samples");
287         int mesh_light_samples = get_int(cscene, "mesh_light_samples");
288         int subsurface_samples = get_int(cscene, "subsurface_samples");
289         int volume_samples = get_int(cscene, "volume_samples");
290
291         if(get_boolean(cscene, "use_square_samples")) {
292                 integrator->diffuse_samples = diffuse_samples * diffuse_samples;
293                 integrator->glossy_samples = glossy_samples * glossy_samples;
294                 integrator->transmission_samples = transmission_samples * transmission_samples;
295                 integrator->ao_samples = ao_samples * ao_samples;
296                 integrator->mesh_light_samples = mesh_light_samples * mesh_light_samples;
297                 integrator->subsurface_samples = subsurface_samples * subsurface_samples;
298                 integrator->volume_samples = volume_samples * volume_samples;
299         }
300         else {
301                 integrator->diffuse_samples = diffuse_samples;
302                 integrator->glossy_samples = glossy_samples;
303                 integrator->transmission_samples = transmission_samples;
304                 integrator->ao_samples = ao_samples;
305                 integrator->mesh_light_samples = mesh_light_samples;
306                 integrator->subsurface_samples = subsurface_samples;
307                 integrator->volume_samples = volume_samples;
308         }
309
310         if(b_scene.render().use_simplify()) {
311                 if(preview) {
312                         integrator->ao_bounces = get_int(cscene, "ao_bounces");
313                 }
314                 else {
315                         integrator->ao_bounces = get_int(cscene, "ao_bounces_render");
316                 }
317         }
318         else {
319                 integrator->ao_bounces = 0;
320         }
321
322         if(integrator->modified(previntegrator))
323                 integrator->tag_update(scene);
324 }
325
326 /* Film */
327
328 void BlenderSync::sync_film()
329 {
330         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
331
332         Film *film = scene->film;
333         Film prevfilm = *film;
334
335         film->exposure = get_float(cscene, "film_exposure");
336         film->filter_type = (FilterType)get_enum(cscene,
337                                                  "pixel_filter_type",
338                                                  FILTER_NUM_TYPES,
339                                                  FILTER_BLACKMAN_HARRIS);
340         film->filter_width = (film->filter_type == FILTER_BOX)? 1.0f: get_float(cscene, "filter_width");
341
342         if(b_scene.world()) {
343                 BL::WorldMistSettings b_mist = b_scene.world().mist_settings();
344
345                 film->mist_start = b_mist.start();
346                 film->mist_depth = b_mist.depth();
347
348                 switch(b_mist.falloff()) {
349                         case BL::WorldMistSettings::falloff_QUADRATIC:
350                                 film->mist_falloff = 2.0f;
351                                 break;
352                         case BL::WorldMistSettings::falloff_LINEAR:
353                                 film->mist_falloff = 1.0f;
354                                 break;
355                         case BL::WorldMistSettings::falloff_INVERSE_QUADRATIC:
356                                 film->mist_falloff = 0.5f;
357                                 break;
358                 }
359         }
360
361         if(film->modified(prevfilm))
362                 film->tag_update(scene);
363 }
364
365 /* Render Layer */
366
367 void BlenderSync::sync_view_layer(BL::SpaceView3D& /*b_v3d*/, BL::ViewLayer& b_view_layer)
368 {
369         /* render layer */
370         view_layer.name = b_view_layer.name();
371         view_layer.use_background_shader = b_view_layer.use_sky();
372         view_layer.use_background_ao = b_view_layer.use_ao();
373         view_layer.use_surfaces = b_view_layer.use_solid();
374         view_layer.use_hair = b_view_layer.use_strand();
375 }
376
377 /* Images */
378 void BlenderSync::sync_images()
379 {
380         /* Sync is a convention for this API, but currently it frees unused buffers. */
381
382         const bool is_interface_locked = b_engine.render() &&
383                                          b_engine.render().use_lock_interface();
384         if(is_interface_locked == false && BlenderSession::headless == false) {
385                 /* If interface is not locked, it's possible image is needed for
386                  * the display.
387                  */
388                 return;
389         }
390         /* Free buffers used by images which are not needed for render. */
391         BL::BlendData::images_iterator b_image;
392         for(b_data.images.begin(b_image);
393             b_image != b_data.images.end();
394             ++b_image)
395         {
396                 /* TODO(sergey): Consider making it an utility function to check
397                  * whether image is considered builtin.
398                  */
399                 const bool is_builtin = b_image->packed_file() ||
400                                         b_image->source() == BL::Image::source_GENERATED ||
401                                         b_image->source() == BL::Image::source_MOVIE ||
402                                         b_engine.is_preview();
403                 if(is_builtin == false) {
404                         b_image->buffers_free();
405                 }
406                 /* TODO(sergey): Free builtin images not used by any shader. */
407         }
408 }
409
410 /* Passes */
411 PassType BlenderSync::get_pass_type(BL::RenderPass& b_pass)
412 {
413         string name = b_pass.name();
414 #define MAP_PASS(passname, passtype) if(name == passname) return passtype;
415         /* NOTE: Keep in sync with defined names from DNA_scene_types.h */
416         MAP_PASS("Combined", PASS_COMBINED);
417         MAP_PASS("Depth", PASS_DEPTH);
418         MAP_PASS("Mist", PASS_MIST);
419         MAP_PASS("Normal", PASS_NORMAL);
420         MAP_PASS("IndexOB", PASS_OBJECT_ID);
421         MAP_PASS("UV", PASS_UV);
422         MAP_PASS("Vector", PASS_MOTION);
423         MAP_PASS("IndexMA", PASS_MATERIAL_ID);
424
425         MAP_PASS("DiffDir", PASS_DIFFUSE_DIRECT);
426         MAP_PASS("GlossDir", PASS_GLOSSY_DIRECT);
427         MAP_PASS("TransDir", PASS_TRANSMISSION_DIRECT);
428         MAP_PASS("SubsurfaceDir", PASS_SUBSURFACE_DIRECT);
429         MAP_PASS("VolumeDir", PASS_VOLUME_DIRECT);
430
431         MAP_PASS("DiffInd", PASS_DIFFUSE_INDIRECT);
432         MAP_PASS("GlossInd", PASS_GLOSSY_INDIRECT);
433         MAP_PASS("TransInd", PASS_TRANSMISSION_INDIRECT);
434         MAP_PASS("SubsurfaceInd", PASS_SUBSURFACE_INDIRECT);
435         MAP_PASS("VolumeInd", PASS_VOLUME_INDIRECT);
436
437         MAP_PASS("DiffCol", PASS_DIFFUSE_COLOR);
438         MAP_PASS("GlossCol", PASS_GLOSSY_COLOR);
439         MAP_PASS("TransCol", PASS_TRANSMISSION_COLOR);
440         MAP_PASS("SubsurfaceCol", PASS_SUBSURFACE_COLOR);
441
442         MAP_PASS("Emit", PASS_EMISSION);
443         MAP_PASS("Env", PASS_BACKGROUND);
444         MAP_PASS("AO", PASS_AO);
445         MAP_PASS("Shadow", PASS_SHADOW);
446
447 #ifdef __KERNEL_DEBUG__
448         MAP_PASS("Debug BVH Traversed Nodes", PASS_BVH_TRAVERSED_NODES);
449         MAP_PASS("Debug BVH Traversed Instances", PASS_BVH_TRAVERSED_INSTANCES);
450         MAP_PASS("Debug BVH Intersections", PASS_BVH_INTERSECTIONS);
451         MAP_PASS("Debug Ray Bounces", PASS_RAY_BOUNCES);
452 #endif
453         MAP_PASS("Debug Render Time", PASS_RENDER_TIME);
454         if(string_startswith(name, cryptomatte_prefix)) {
455                 return PASS_CRYPTOMATTE;
456         }
457 #undef MAP_PASS
458
459         return PASS_NONE;
460 }
461
462 int BlenderSync::get_denoising_pass(BL::RenderPass& b_pass)
463 {
464         string name = b_pass.name();
465
466         if(name == "Noisy Image") return DENOISING_PASS_COLOR;
467
468         if(name.substr(0, 10) != "Denoising ") {
469                 return -1;
470         }
471         name = name.substr(10);
472
473 #define MAP_PASS(passname, offset) if(name == passname) return offset;
474         MAP_PASS("Normal", DENOISING_PASS_NORMAL);
475         MAP_PASS("Normal Variance", DENOISING_PASS_NORMAL_VAR);
476         MAP_PASS("Albedo", DENOISING_PASS_ALBEDO);
477         MAP_PASS("Albedo Variance", DENOISING_PASS_ALBEDO_VAR);
478         MAP_PASS("Depth", DENOISING_PASS_DEPTH);
479         MAP_PASS("Depth Variance", DENOISING_PASS_DEPTH_VAR);
480         MAP_PASS("Shadow A", DENOISING_PASS_SHADOW_A);
481         MAP_PASS("Shadow B", DENOISING_PASS_SHADOW_B);
482         MAP_PASS("Image Variance", DENOISING_PASS_COLOR_VAR);
483         MAP_PASS("Clean", DENOISING_PASS_CLEAN);
484 #undef MAP_PASS
485
486         return -1;
487 }
488
489 vector<Pass> BlenderSync::sync_render_passes(BL::RenderLayer& b_rlay,
490                                              BL::ViewLayer& b_view_layer,
491                                              const SessionParams &session_params)
492 {
493         vector<Pass> passes;
494         Pass::add(PASS_COMBINED, passes);
495
496         if(!session_params.device.advanced_shading) {
497                 return passes;
498         }
499
500         /* loop over passes */
501         BL::RenderLayer::passes_iterator b_pass_iter;
502
503         for(b_rlay.passes.begin(b_pass_iter); b_pass_iter != b_rlay.passes.end(); ++b_pass_iter) {
504                 BL::RenderPass b_pass(*b_pass_iter);
505                 PassType pass_type = get_pass_type(b_pass);
506
507                 if(pass_type == PASS_MOTION && scene->integrator->motion_blur)
508                         continue;
509                 if(pass_type != PASS_NONE)
510                         Pass::add(pass_type, passes);
511         }
512
513         scene->film->denoising_flags = 0;
514         PointerRNA crp = RNA_pointer_get(&b_view_layer.ptr, "cycles");
515         if(get_boolean(crp, "use_denoising")) {
516 #define MAP_OPTION(name, flag) if(!get_boolean(crp, name)) scene->film->denoising_flags |= flag;
517                 MAP_OPTION("denoising_diffuse_direct",        DENOISING_CLEAN_DIFFUSE_DIR);
518                 MAP_OPTION("denoising_diffuse_indirect",      DENOISING_CLEAN_DIFFUSE_IND);
519                 MAP_OPTION("denoising_glossy_direct",         DENOISING_CLEAN_GLOSSY_DIR);
520                 MAP_OPTION("denoising_glossy_indirect",       DENOISING_CLEAN_GLOSSY_IND);
521                 MAP_OPTION("denoising_transmission_direct",   DENOISING_CLEAN_TRANSMISSION_DIR);
522                 MAP_OPTION("denoising_transmission_indirect", DENOISING_CLEAN_TRANSMISSION_IND);
523                 MAP_OPTION("denoising_subsurface_direct",     DENOISING_CLEAN_SUBSURFACE_DIR);
524                 MAP_OPTION("denoising_subsurface_indirect",   DENOISING_CLEAN_SUBSURFACE_IND);
525 #undef MAP_OPTION
526
527                 b_engine.add_pass("Noisy Image", 4, "RGBA", b_view_layer.name().c_str());
528                 if(get_boolean(crp, "denoising_store_passes")) {
529                         b_engine.add_pass("Denoising Normal",          3, "XYZ", b_view_layer.name().c_str());
530                         b_engine.add_pass("Denoising Normal Variance", 3, "XYZ", b_view_layer.name().c_str());
531                         b_engine.add_pass("Denoising Albedo",          3, "RGB", b_view_layer.name().c_str());
532                         b_engine.add_pass("Denoising Albedo Variance", 3, "RGB", b_view_layer.name().c_str());
533                         b_engine.add_pass("Denoising Depth",           1, "Z",   b_view_layer.name().c_str());
534                         b_engine.add_pass("Denoising Depth Variance",  1, "Z",   b_view_layer.name().c_str());
535                         b_engine.add_pass("Denoising Shadow A",        3, "XYV", b_view_layer.name().c_str());
536                         b_engine.add_pass("Denoising Shadow B",        3, "XYV", b_view_layer.name().c_str());
537                         b_engine.add_pass("Denoising Image Variance",  3, "RGB", b_view_layer.name().c_str());
538
539                         if(scene->film->denoising_flags & DENOISING_CLEAN_ALL_PASSES) {
540                                 b_engine.add_pass("Denoising Clean",   3, "RGB", b_view_layer.name().c_str());
541                         }
542                 }
543         }
544 #ifdef __KERNEL_DEBUG__
545         if(get_boolean(crp, "pass_debug_bvh_traversed_nodes")) {
546                 b_engine.add_pass("Debug BVH Traversed Nodes", 1, "X", b_view_layer.name().c_str());
547                 Pass::add(PASS_BVH_TRAVERSED_NODES, passes);
548         }
549         if(get_boolean(crp, "pass_debug_bvh_traversed_instances")) {
550                 b_engine.add_pass("Debug BVH Traversed Instances", 1, "X", b_view_layer.name().c_str());
551                 Pass::add(PASS_BVH_TRAVERSED_INSTANCES, passes);
552         }
553         if(get_boolean(crp, "pass_debug_bvh_intersections")) {
554                 b_engine.add_pass("Debug BVH Intersections", 1, "X", b_view_layer.name().c_str());
555                 Pass::add(PASS_BVH_INTERSECTIONS, passes);
556         }
557         if(get_boolean(crp, "pass_debug_ray_bounces")) {
558                 b_engine.add_pass("Debug Ray Bounces", 1, "X", b_view_layer.name().c_str());
559                 Pass::add(PASS_RAY_BOUNCES, passes);
560         }
561 #endif
562         if(get_boolean(crp, "pass_debug_render_time")) {
563                 b_engine.add_pass("Debug Render Time", 1, "X", b_view_layer.name().c_str());
564                 Pass::add(PASS_RENDER_TIME, passes);
565         }
566         if(get_boolean(crp, "use_pass_volume_direct")) {
567                 b_engine.add_pass("VolumeDir", 3, "RGB", b_view_layer.name().c_str());
568                 Pass::add(PASS_VOLUME_DIRECT, passes);
569         }
570         if(get_boolean(crp, "use_pass_volume_indirect")) {
571                 b_engine.add_pass("VolumeInd", 3, "RGB", b_view_layer.name().c_str());
572                 Pass::add(PASS_VOLUME_INDIRECT, passes);
573         }
574
575         /* Cryptomatte stores two ID/weight pairs per RGBA layer.
576          * User facing paramter is the number of pairs. */
577         int crypto_depth = min(16, get_int(crp, "pass_crypto_depth")) / 2;
578         scene->film->cryptomatte_depth = crypto_depth;
579         scene->film->cryptomatte_passes = CRYPT_NONE;
580         if(get_boolean(crp, "use_pass_crypto_object")) {
581                 for(int i = 0; i < crypto_depth; ++i) {
582                         string passname = cryptomatte_prefix + string_printf("Object%02d", i);
583                         b_engine.add_pass(passname.c_str(), 4, "RGBA", b_view_layer.name().c_str());
584                         Pass::add(PASS_CRYPTOMATTE, passes, passname.c_str());
585                 }
586                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_OBJECT);
587         }
588         if(get_boolean(crp, "use_pass_crypto_material")) {
589                 for(int i = 0; i < crypto_depth; ++i) {
590                         string passname = cryptomatte_prefix + string_printf("Material%02d", i);
591                         b_engine.add_pass(passname.c_str(), 4, "RGBA", b_view_layer.name().c_str());
592                         Pass::add(PASS_CRYPTOMATTE, passes, passname.c_str());
593                 }
594                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_MATERIAL);
595         }
596         if(get_boolean(crp, "use_pass_crypto_asset")) {
597                 for(int i = 0; i < crypto_depth; ++i) {
598                         string passname = cryptomatte_prefix + string_printf("Asset%02d", i);
599                         b_engine.add_pass(passname.c_str(), 4, "RGBA", b_view_layer.name().c_str());
600                         Pass::add(PASS_CRYPTOMATTE, passes, passname.c_str());
601                 }
602                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_ASSET);
603         }
604         if(get_boolean(crp, "pass_crypto_accurate") && scene->film->cryptomatte_passes != CRYPT_NONE) {
605                 scene->film->cryptomatte_passes = (CryptomatteType)(scene->film->cryptomatte_passes | CRYPT_ACCURATE);
606         }
607
608         return passes;
609 }
610
611 void BlenderSync::free_data_after_sync(BL::Depsgraph& b_depsgraph)
612 {
613         /* When viewport display is not needed during render we can force some
614          * caches to be releases from blender side in order to reduce peak memory
615          * footprint during synchronization process.
616          */
617         const bool is_interface_locked = b_engine.render() &&
618                                          b_engine.render().use_lock_interface();
619         const bool can_free_caches = BlenderSession::headless || is_interface_locked;
620         if (!can_free_caches) {
621                 return;
622         }
623         /* TODO(sergey): We can actually remove the whole dependency graph,
624          * but that will need some API support first.
625          */
626         BL::Depsgraph::objects_iterator b_ob;
627         for(b_depsgraph.objects.begin(b_ob);
628             b_ob != b_depsgraph.objects.end();
629             ++b_ob)
630         {
631                 b_ob->cache_release();
632         }
633 }
634
635 /* Scene Parameters */
636
637 SceneParams BlenderSync::get_scene_params(BL::Scene& b_scene,
638                                           bool background)
639 {
640         BL::RenderSettings r = b_scene.render();
641         SceneParams params;
642         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
643         const bool shadingsystem = RNA_boolean_get(&cscene, "shading_system");
644
645         if(shadingsystem == 0)
646                 params.shadingsystem = SHADINGSYSTEM_SVM;
647         else if(shadingsystem == 1)
648                 params.shadingsystem = SHADINGSYSTEM_OSL;
649
650         if(background || DebugFlags().viewport_static_bvh)
651                 params.bvh_type = SceneParams::BVH_STATIC;
652         else
653                 params.bvh_type = SceneParams::BVH_DYNAMIC;
654
655         params.use_bvh_spatial_split = RNA_boolean_get(&cscene, "debug_use_spatial_splits");
656         params.use_bvh_unaligned_nodes = RNA_boolean_get(&cscene, "debug_use_hair_bvh");
657         params.num_bvh_time_steps = RNA_int_get(&cscene, "debug_bvh_time_steps");
658
659         if(background && params.shadingsystem != SHADINGSYSTEM_OSL)
660                 params.persistent_data = r.use_persistent_data();
661         else
662                 params.persistent_data = false;
663
664         int texture_limit;
665         if(background) {
666                 texture_limit = RNA_enum_get(&cscene, "texture_limit_render");
667         }
668         else {
669                 texture_limit = RNA_enum_get(&cscene, "texture_limit");
670         }
671         if(texture_limit > 0 && b_scene.render().use_simplify()) {
672                 params.texture_limit = 1 << (texture_limit + 6);
673         }
674         else {
675                 params.texture_limit = 0;
676         }
677
678         /* TODO(sergey): Once OSL supports per-microarchitecture optimization get
679          * rid of this.
680          */
681         if(params.shadingsystem == SHADINGSYSTEM_OSL) {
682                 params.bvh_layout = BVH_LAYOUT_BVH4;
683         }
684         else {
685                 params.bvh_layout = DebugFlags().cpu.bvh_layout;
686         }
687
688         return params;
689 }
690
691 /* Session Parameters */
692
693 bool BlenderSync::get_session_pause(BL::Scene& b_scene, bool background)
694 {
695         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
696         return (background)? false: get_boolean(cscene, "preview_pause");
697 }
698
699 SessionParams BlenderSync::get_session_params(BL::RenderEngine& b_engine,
700                                               BL::UserPreferences& b_userpref,
701                                               BL::Scene& b_scene,
702                                               bool background)
703 {
704         SessionParams params;
705         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
706
707         /* feature set */
708         params.experimental = (get_enum(cscene, "feature_set") != 0);
709
710         /* threads */
711         BL::RenderSettings b_r = b_scene.render();
712         if(b_r.threads_mode() == BL::RenderSettings::threads_mode_FIXED)
713                 params.threads = b_r.threads();
714         else
715                 params.threads = 0;
716
717         /* Background */
718         params.background = background;
719
720         /* device type */
721         vector<DeviceInfo>& devices = Device::available_devices();
722
723         /* device default CPU */
724         foreach(DeviceInfo& device, devices) {
725                 if(device.type == DEVICE_CPU) {
726                         params.device = device;
727                         break;
728                 }
729         }
730
731         if(get_enum(cscene, "device") == 2) {
732                 /* find network device */
733                 foreach(DeviceInfo& info, devices)
734                         if(info.type == DEVICE_NETWORK)
735                                 params.device = info;
736         }
737         else if(get_enum(cscene, "device") == 1) {
738                 PointerRNA b_preferences;
739
740                 BL::UserPreferences::addons_iterator b_addon_iter;
741                 for(b_userpref.addons.begin(b_addon_iter); b_addon_iter != b_userpref.addons.end(); ++b_addon_iter) {
742                         if(b_addon_iter->module() == "cycles") {
743                                 b_preferences = b_addon_iter->preferences().ptr;
744                                 break;
745                         }
746                 }
747
748                 enum ComputeDevice {
749                         COMPUTE_DEVICE_CPU = 0,
750                         COMPUTE_DEVICE_CUDA = 1,
751                         COMPUTE_DEVICE_OPENCL = 2,
752                         COMPUTE_DEVICE_NUM = 3,
753                 };
754
755                 ComputeDevice compute_device = (ComputeDevice)get_enum(b_preferences,
756                                                                        "compute_device_type",
757                                                                        COMPUTE_DEVICE_NUM,
758                                                                        COMPUTE_DEVICE_CPU);
759
760                 if(compute_device != COMPUTE_DEVICE_CPU) {
761                         vector<DeviceInfo> used_devices;
762                         RNA_BEGIN(&b_preferences, device, "devices") {
763                                 ComputeDevice device_type = (ComputeDevice)get_enum(device,
764                                                                                     "type",
765                                                                                     COMPUTE_DEVICE_NUM,
766                                                                                     COMPUTE_DEVICE_CPU);
767
768                                 if(get_boolean(device, "use") &&
769                                    (device_type == compute_device || device_type == COMPUTE_DEVICE_CPU)) {
770                                         string id = get_string(device, "id");
771                                         foreach(DeviceInfo& info, devices) {
772                                                 if(info.id == id) {
773                                                         used_devices.push_back(info);
774                                                         break;
775                                                 }
776                                         }
777                                 }
778                         } RNA_END
779
780                         if(used_devices.size() == 1) {
781                                 params.device = used_devices[0];
782                         }
783                         else if(used_devices.size() > 1) {
784                                 params.device = Device::get_multi_device(used_devices,
785                                                                          params.threads,
786                                                                          params.background);
787                         }
788                         /* Else keep using the CPU device that was set before. */
789                 }
790         }
791
792         /* samples */
793         int samples = get_int(cscene, "samples");
794         int aa_samples = get_int(cscene, "aa_samples");
795         int preview_samples = get_int(cscene, "preview_samples");
796         int preview_aa_samples = get_int(cscene, "preview_aa_samples");
797
798         if(get_boolean(cscene, "use_square_samples")) {
799                 aa_samples = aa_samples * aa_samples;
800                 preview_aa_samples = preview_aa_samples * preview_aa_samples;
801
802                 samples = samples * samples;
803                 preview_samples = preview_samples * preview_samples;
804         }
805
806         if(get_enum(cscene, "progressive") == 0) {
807                 if(background) {
808                         params.samples = aa_samples;
809                 }
810                 else {
811                         params.samples = preview_aa_samples;
812                         if(params.samples == 0)
813                                 params.samples = INT_MAX;
814                 }
815         }
816         else {
817                 if(background) {
818                         params.samples = samples;
819                 }
820                 else {
821                         params.samples = preview_samples;
822                         if(params.samples == 0)
823                                 params.samples = INT_MAX;
824                 }
825         }
826
827         /* tiles */
828         if(params.device.type != DEVICE_CPU && !background) {
829                 /* currently GPU could be much slower than CPU when using tiles,
830                  * still need to be investigated, but meanwhile make it possible
831                  * to work in viewport smoothly
832                  */
833                 int debug_tile_size = get_int(cscene, "debug_tile_size");
834
835                 params.tile_size = make_int2(debug_tile_size, debug_tile_size);
836         }
837         else {
838                 int tile_x = b_engine.tile_x();
839                 int tile_y = b_engine.tile_y();
840
841                 params.tile_size = make_int2(tile_x, tile_y);
842         }
843
844         if((BlenderSession::headless == false) && background) {
845                 params.tile_order = (TileOrder)get_enum(cscene, "tile_order");
846         }
847         else {
848                 params.tile_order = TILE_BOTTOM_TO_TOP;
849         }
850
851         /* other parameters */
852         params.start_resolution = get_int(cscene, "preview_start_resolution");
853         params.pixel_size = b_engine.get_preview_pixel_size(b_scene);
854
855         /* other parameters */
856         params.cancel_timeout = (double)get_float(cscene, "debug_cancel_timeout");
857         params.reset_timeout = (double)get_float(cscene, "debug_reset_timeout");
858         params.text_timeout = (double)get_float(cscene, "debug_text_timeout");
859
860         /* progressive refine */
861         params.progressive_refine = (b_engine.is_preview() ||
862                                      get_boolean(cscene, "use_progressive_refine")) &&
863                                     !b_r.use_save_buffers();
864
865         if(params.progressive_refine) {
866                 BL::Scene::view_layers_iterator b_view_layer;
867                 for(b_scene.view_layers.begin(b_view_layer); b_view_layer != b_scene.view_layers.end(); ++b_view_layer) {
868                         PointerRNA crl = RNA_pointer_get(&b_view_layer->ptr, "cycles");
869                         if(get_boolean(crl, "use_denoising")) {
870                                 params.progressive_refine = false;
871                         }
872                 }
873         }
874
875         if(background) {
876                 if(params.progressive_refine)
877                         params.progressive = true;
878                 else
879                         params.progressive = false;
880
881                 params.start_resolution = INT_MAX;
882                 params.pixel_size = 1;
883         }
884         else
885                 params.progressive = true;
886
887         /* shading system - scene level needs full refresh */
888         const bool shadingsystem = RNA_boolean_get(&cscene, "shading_system");
889
890         if(shadingsystem == 0)
891                 params.shadingsystem = SHADINGSYSTEM_SVM;
892         else if(shadingsystem == 1)
893                 params.shadingsystem = SHADINGSYSTEM_OSL;
894
895         /* color managagement */
896         params.display_buffer_linear = b_engine.support_display_space_shader(b_scene);
897
898         if(b_engine.is_preview()) {
899                 /* For preview rendering we're using same timeout as
900                  * blender's job update.
901                  */
902                 params.progressive_update_timeout = 0.1;
903         }
904
905         return params;
906 }
907
908 CCL_NAMESPACE_END