Cleanup: split user preferences out of wm.py
[blender.git] / intern / cycles / blender / blender_session.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 <stdlib.h>
18
19 #include "render/background.h"
20 #include "render/buffers.h"
21 #include "render/camera.h"
22 #include "device/device.h"
23 #include "render/integrator.h"
24 #include "render/film.h"
25 #include "render/light.h"
26 #include "render/mesh.h"
27 #include "render/object.h"
28 #include "render/scene.h"
29 #include "render/session.h"
30 #include "render/shader.h"
31 #include "render/stats.h"
32
33 #include "util/util_algorithm.h"
34 #include "util/util_color.h"
35 #include "util/util_foreach.h"
36 #include "util/util_function.h"
37 #include "util/util_hash.h"
38 #include "util/util_logging.h"
39 #include "util/util_murmurhash.h"
40 #include "util/util_progress.h"
41 #include "util/util_time.h"
42
43 #include "blender/blender_sync.h"
44 #include "blender/blender_session.h"
45 #include "blender/blender_util.h"
46
47 CCL_NAMESPACE_BEGIN
48
49 bool BlenderSession::headless = false;
50 int BlenderSession::num_resumable_chunks = 0;
51 int BlenderSession::current_resumable_chunk = 0;
52 int BlenderSession::start_resumable_chunk = 0;
53 int BlenderSession::end_resumable_chunk = 0;
54 bool BlenderSession::print_render_stats = false;
55
56 BlenderSession::BlenderSession(BL::RenderEngine& b_engine,
57                                BL::Preferences& b_userpref,
58                                BL::BlendData& b_data,
59                                bool preview_osl)
60 : session(NULL),
61   sync(NULL),
62   b_engine(b_engine),
63   b_userpref(b_userpref),
64   b_data(b_data),
65   b_render(b_engine.render()),
66   b_depsgraph(PointerRNA_NULL),
67   b_scene(PointerRNA_NULL),
68   b_v3d(PointerRNA_NULL),
69   b_rv3d(PointerRNA_NULL),
70   width(0),
71   height(0),
72   preview_osl(preview_osl),
73   python_thread_state(NULL)
74 {
75         /* offline render */
76         background = true;
77         last_redraw_time = 0.0;
78         start_resize_time = 0.0;
79         last_status_time = 0.0;
80 }
81
82 BlenderSession::BlenderSession(BL::RenderEngine& b_engine,
83                                BL::Preferences& b_userpref,
84                                BL::BlendData& b_data,
85                                BL::SpaceView3D& b_v3d,
86                                BL::RegionView3D& b_rv3d,
87                                int width, int height)
88 : session(NULL),
89   sync(NULL),
90   b_engine(b_engine),
91   b_userpref(b_userpref),
92   b_data(b_data),
93   b_render(b_engine.render()),
94   b_depsgraph(PointerRNA_NULL),
95   b_scene(PointerRNA_NULL),
96   b_v3d(b_v3d),
97   b_rv3d(b_rv3d),
98   width(width),
99   height(height),
100   preview_osl(false),
101   python_thread_state(NULL)
102 {
103         /* 3d view render */
104         background = false;
105         last_redraw_time = 0.0;
106         start_resize_time = 0.0;
107         last_status_time = 0.0;
108 }
109
110 BlenderSession::~BlenderSession()
111 {
112         free_session();
113 }
114
115 void BlenderSession::create()
116 {
117         create_session();
118 }
119
120 void BlenderSession::create_session()
121 {
122         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
123         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
124         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
125
126         /* reset status/progress */
127         last_status = "";
128         last_error = "";
129         last_progress = -1.0f;
130         start_resize_time = 0.0;
131
132         /* create session */
133         session = new Session(session_params);
134         session->scene = scene;
135         session->progress.set_update_callback(function_bind(&BlenderSession::tag_redraw, this));
136         session->progress.set_cancel_callback(function_bind(&BlenderSession::test_cancel, this));
137         session->set_pause(session_pause);
138
139         /* create scene */
140         scene = new Scene(scene_params, session->device);
141         scene->name = b_scene.name();
142
143         /* setup callbacks for builtin image support */
144         scene->image_manager->builtin_image_info_cb = function_bind(&BlenderSession::builtin_image_info, this, _1, _2, _3);
145         scene->image_manager->builtin_image_pixels_cb = function_bind(&BlenderSession::builtin_image_pixels, this, _1, _2, _3, _4, _5);
146         scene->image_manager->builtin_image_float_pixels_cb = function_bind(&BlenderSession::builtin_image_float_pixels, this, _1, _2, _3, _4, _5);
147
148         session->scene = scene;
149
150         /* There is no single depsgraph to use for the entire render.
151          * So we need to handle this differently.
152          *
153          * We could loop over the final render result render layers in pipeline and keep Cycles unaware of multiple layers,
154          * or perhaps move syncing further down in the pipeline.
155          */
156         /* create sync */
157         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress);
158         BL::Object b_camera_override(b_engine.camera_override());
159         if(b_v3d) {
160                 sync->sync_view(b_v3d, b_rv3d, width, height);
161         }
162         else {
163                 sync->sync_camera(b_render, b_camera_override, width, height, "");
164         }
165
166         /* set buffer parameters */
167         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
168         session->reset(buffer_params, session_params.samples);
169
170         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
171
172         update_resumable_tile_manager(session_params.samples);
173 }
174
175 void BlenderSession::reset_session(BL::BlendData& b_data, BL::Depsgraph& b_depsgraph)
176 {
177         this->b_data = b_data;
178         this->b_depsgraph = b_depsgraph;
179         this->b_scene = b_depsgraph.scene_eval();
180
181         if(preview_osl) {
182                 PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
183                 RNA_boolean_set(&cscene, "shading_system", preview_osl);
184         }
185
186         if(b_v3d) {
187                 this->b_render = b_scene.render();
188         }
189         else {
190                 this->b_render = b_engine.render();
191                 width = render_resolution_x(b_render);
192                 height = render_resolution_y(b_render);
193         }
194
195         if(session == NULL) {
196                 create();
197         }
198
199         if(b_v3d) {
200                 /* NOTE: We need to create session, but all the code from below
201                  * will make viewport render to stuck on initialization.
202                  */
203                 return;
204         }
205
206         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
207         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
208
209         if(scene->params.modified(scene_params) ||
210            session->params.modified(session_params) ||
211            !scene_params.persistent_data)
212         {
213                 /* if scene or session parameters changed, it's easier to simply re-create
214                  * them rather than trying to distinguish which settings need to be updated
215                  */
216                 free_session();
217                 create_session();
218                 return;
219         }
220
221         session->progress.reset();
222         scene->reset();
223
224         session->tile_manager.set_tile_order(session_params.tile_order);
225
226         /* peak memory usage should show current render peak, not peak for all renders
227          * made by this render session
228          */
229         session->stats.mem_peak = session->stats.mem_used;
230
231         /* There is no single depsgraph to use for the entire render.
232          * See note on create_session().
233          */
234         /* sync object should be re-created */
235         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress);
236
237         BL::SpaceView3D b_null_space_view3d(PointerRNA_NULL);
238         BL::RegionView3D b_null_region_view3d(PointerRNA_NULL);
239         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render,
240                                                                     b_null_space_view3d,
241                                                                     b_null_region_view3d,
242                                                                     scene->camera,
243                                                                     width, height);
244         session->reset(buffer_params, session_params.samples);
245
246         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
247
248         /* reset time */
249         start_resize_time = 0.0;
250 }
251
252 void BlenderSession::free_session()
253 {
254         if(sync)
255                 delete sync;
256
257         delete session;
258 }
259
260 static ShaderEvalType get_shader_type(const string& pass_type)
261 {
262         const char *shader_type = pass_type.c_str();
263
264         /* data passes */
265         if(strcmp(shader_type, "NORMAL")==0)
266                 return SHADER_EVAL_NORMAL;
267         else if(strcmp(shader_type, "UV")==0)
268                 return SHADER_EVAL_UV;
269         else if(strcmp(shader_type, "ROUGHNESS")==0)
270                 return SHADER_EVAL_ROUGHNESS;
271         else if(strcmp(shader_type, "DIFFUSE_COLOR")==0)
272                 return SHADER_EVAL_DIFFUSE_COLOR;
273         else if(strcmp(shader_type, "GLOSSY_COLOR")==0)
274                 return SHADER_EVAL_GLOSSY_COLOR;
275         else if(strcmp(shader_type, "TRANSMISSION_COLOR")==0)
276                 return SHADER_EVAL_TRANSMISSION_COLOR;
277         else if(strcmp(shader_type, "SUBSURFACE_COLOR")==0)
278                 return SHADER_EVAL_SUBSURFACE_COLOR;
279         else if(strcmp(shader_type, "EMIT")==0)
280                 return SHADER_EVAL_EMISSION;
281
282         /* light passes */
283         else if(strcmp(shader_type, "AO")==0)
284                 return SHADER_EVAL_AO;
285         else if(strcmp(shader_type, "COMBINED")==0)
286                 return SHADER_EVAL_COMBINED;
287         else if(strcmp(shader_type, "SHADOW")==0)
288                 return SHADER_EVAL_SHADOW;
289         else if(strcmp(shader_type, "DIFFUSE")==0)
290                 return SHADER_EVAL_DIFFUSE;
291         else if(strcmp(shader_type, "GLOSSY")==0)
292                 return SHADER_EVAL_GLOSSY;
293         else if(strcmp(shader_type, "TRANSMISSION")==0)
294                 return SHADER_EVAL_TRANSMISSION;
295         else if(strcmp(shader_type, "SUBSURFACE")==0)
296                 return SHADER_EVAL_SUBSURFACE;
297
298         /* extra */
299         else if(strcmp(shader_type, "ENVIRONMENT")==0)
300                 return SHADER_EVAL_ENVIRONMENT;
301
302         else
303                 return SHADER_EVAL_BAKE;
304 }
305
306 static BL::RenderResult begin_render_result(BL::RenderEngine& b_engine,
307                                             int x, int y,
308                                             int w, int h,
309                                             const char *layername,
310                                             const char *viewname)
311 {
312         return b_engine.begin_result(x, y, w, h, layername, viewname);
313 }
314
315 static void end_render_result(BL::RenderEngine& b_engine,
316                               BL::RenderResult& b_rr,
317                               bool cancel,
318                               bool highlight,
319                               bool do_merge_results)
320 {
321         b_engine.end_result(b_rr, (int)cancel, (int) highlight, (int)do_merge_results);
322 }
323
324 void BlenderSession::do_write_update_render_tile(RenderTile& rtile, bool do_update_only, bool highlight)
325 {
326         int x = rtile.x - session->tile_manager.params.full_x;
327         int y = rtile.y - session->tile_manager.params.full_y;
328         int w = rtile.w;
329         int h = rtile.h;
330
331         /* get render result */
332         BL::RenderResult b_rr = begin_render_result(b_engine, x, y, w, h, b_rlay_name.c_str(), b_rview_name.c_str());
333
334         /* can happen if the intersected rectangle gives 0 width or height */
335         if(b_rr.ptr.data == NULL) {
336                 return;
337         }
338
339         BL::RenderResult::layers_iterator b_single_rlay;
340         b_rr.layers.begin(b_single_rlay);
341
342         /* layer will be missing if it was disabled in the UI */
343         if(b_single_rlay == b_rr.layers.end())
344                 return;
345
346         BL::RenderLayer b_rlay = *b_single_rlay;
347
348         if(do_update_only) {
349                 /* Sample would be zero at initial tile update, which is only needed
350                  * to tag tile form blender side as IN PROGRESS for proper highlight
351                  * no buffers should be sent to blender yet. For denoise we also
352                  * keep showing the noisy buffers until denoise is done. */
353                 bool merge = (rtile.sample != 0) && (rtile.task != RenderTile::DENOISE);
354
355                 if(merge) {
356                         update_render_result(b_rr, b_rlay, rtile);
357                 }
358
359                 end_render_result(b_engine, b_rr, true, highlight, merge);
360         }
361         else {
362                 /* Write final render result. */
363                 write_render_result(b_rr, b_rlay, rtile);
364                 end_render_result(b_engine, b_rr, false, false, true);
365         }
366 }
367
368 void BlenderSession::write_render_tile(RenderTile& rtile)
369 {
370         do_write_update_render_tile(rtile, false, false);
371 }
372
373 void BlenderSession::update_render_tile(RenderTile& rtile, bool highlight)
374 {
375         /* use final write for preview renders, otherwise render result wouldn't be
376          * be updated in blender side
377          * would need to be investigated a bit further, but for now shall be fine
378          */
379         if(!b_engine.is_preview())
380                 do_write_update_render_tile(rtile, true, highlight);
381         else
382                 do_write_update_render_tile(rtile, false, false);
383 }
384
385 static void add_cryptomatte_layer(BL::RenderResult& b_rr, string name, string manifest)
386 {
387         string identifier = string_printf("%08x", util_murmur_hash3(name.c_str(), name.length(), 0));
388         string prefix = "cryptomatte/" + identifier.substr(0, 7) + "/";
389
390         render_add_metadata(b_rr, prefix+"name", name);
391         render_add_metadata(b_rr, prefix+"hash", "MurmurHash3_32");
392         render_add_metadata(b_rr, prefix+"conversion", "uint32_to_float32");
393         render_add_metadata(b_rr, prefix+"manifest", manifest);
394 }
395
396 void BlenderSession::stamp_view_layer_metadata_do(const string& prefix)
397 {
398         BL::RenderResult b_rr = b_engine.get_result();
399         /* Configured number of samples for the view layer. */
400         b_rr.stamp_data_add_field((prefix + "samples").c_str(),
401                                   to_string(session->params.samples).c_str());
402         /* Store ranged samples information. */
403         if(session->tile_manager.range_num_samples != -1) {
404                 b_rr.stamp_data_add_field(
405                         (prefix + "range_start_sample").c_str(),
406                         to_string(session->tile_manager.range_start_sample).c_str());
407                 b_rr.stamp_data_add_field(
408                         (prefix + "range_num_samples").c_str(),
409                         to_string(session->tile_manager.range_num_samples).c_str());
410         }
411 }
412
413 void BlenderSession::stamp_view_layer_metadata(const string& view_layer_name)
414 {
415         stamp_view_layer_metadata_do("cycles." + view_layer_name + ".");
416 }
417
418 void BlenderSession::render(BL::Depsgraph& b_depsgraph_)
419 {
420         b_depsgraph = b_depsgraph_;
421
422         /* set callback to write out render results */
423         session->write_render_tile_cb = function_bind(&BlenderSession::write_render_tile, this, _1);
424         session->update_render_tile_cb = function_bind(&BlenderSession::update_render_tile, this, _1, _2);
425
426         /* get buffer parameters */
427         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
428         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
429
430         /* render each layer */
431         BL::ViewLayer b_view_layer = b_depsgraph.view_layer_eval();
432
433         /* temporary render result to find needed passes and views */
434         BL::RenderResult b_rr = begin_render_result(b_engine, 0, 0, 1, 1, b_view_layer.name().c_str(), NULL);
435         BL::RenderResult::layers_iterator b_single_rlay;
436         b_rr.layers.begin(b_single_rlay);
437         BL::RenderLayer b_rlay = *b_single_rlay;
438         b_rlay_name = b_view_layer.name();
439
440         /* add passes */
441         vector<Pass> passes = sync->sync_render_passes(b_rlay, b_view_layer, session_params);
442         buffer_params.passes = passes;
443
444         PointerRNA crl = RNA_pointer_get(&b_view_layer.ptr, "cycles");
445         bool full_denoising = get_boolean(crl, "use_denoising");
446         bool write_denoising_passes = get_boolean(crl, "denoising_store_passes");
447
448         bool run_denoising = full_denoising || write_denoising_passes;
449
450         session->tile_manager.schedule_denoising = run_denoising;
451         buffer_params.denoising_data_pass = run_denoising;
452         buffer_params.denoising_clean_pass = (scene->film->denoising_flags & DENOISING_CLEAN_ALL_PASSES);
453         buffer_params.denoising_prefiltered_pass = write_denoising_passes;
454
455         session->params.run_denoising = run_denoising;
456         session->params.full_denoising = full_denoising;
457         session->params.write_denoising_passes = write_denoising_passes;
458         session->params.denoising_radius = get_int(crl, "denoising_radius");
459         session->params.denoising_strength = get_float(crl, "denoising_strength");
460         session->params.denoising_feature_strength = get_float(crl, "denoising_feature_strength");
461         session->params.denoising_relative_pca = get_boolean(crl, "denoising_relative_pca");
462
463         scene->film->denoising_data_pass = buffer_params.denoising_data_pass;
464         scene->film->denoising_clean_pass = buffer_params.denoising_clean_pass;
465         scene->film->denoising_prefiltered_pass = buffer_params.denoising_prefiltered_pass;
466         session->params.denoising_radius = get_int(crl, "denoising_radius");
467         session->params.denoising_strength = get_float(crl, "denoising_strength");
468         session->params.denoising_feature_strength = get_float(crl, "denoising_feature_strength");
469         session->params.denoising_relative_pca = get_boolean(crl, "denoising_relative_pca");
470
471         scene->film->pass_alpha_threshold = b_view_layer.pass_alpha_threshold();
472         scene->film->tag_passes_update(scene, passes);
473         scene->film->tag_update(scene);
474         scene->integrator->tag_update(scene);
475
476         BL::RenderResult::views_iterator b_view_iter;
477
478         int num_views = 0;
479         for(b_rr.views.begin(b_view_iter); b_view_iter != b_rr.views.end(); ++b_view_iter) {
480                 num_views++;
481         }
482
483         int view_index = 0;
484         for(b_rr.views.begin(b_view_iter); b_view_iter != b_rr.views.end(); ++b_view_iter, ++view_index) {
485                 b_rview_name = b_view_iter->name();
486
487                 /* set the current view */
488                 b_engine.active_view_set(b_rview_name.c_str());
489
490                 /* update scene */
491                 BL::Object b_camera_override(b_engine.camera_override());
492                 sync->sync_camera(b_render, b_camera_override, width, height, b_rview_name.c_str());
493                 sync->sync_data(b_render,
494                                 b_depsgraph,
495                                 b_v3d,
496                                 b_camera_override,
497                                 width, height,
498                                 &python_thread_state);
499                 builtin_images_load();
500
501                 /* Attempt to free all data which is held by Blender side, since at this
502                  * point we knwo that we've got everything to render current view layer.
503                  */
504                 /* At the moment we only free if we are not doing multi-view (or if we are rendering the last view).
505                  * See T58142/D4239 for discussion.
506                  */
507                 if(view_index == num_views - 1) {
508                         free_blender_memory_if_possible();
509                 }
510
511                 /* Make sure all views have different noise patterns. - hardcoded value just to make it random */
512                 if(view_index != 0) {
513                         scene->integrator->seed += hash_int_2d(scene->integrator->seed, hash_int(view_index * 0xdeadbeef));
514                         scene->integrator->tag_update(scene);
515                 }
516
517                 /* Update number of samples per layer. */
518                 int samples = sync->get_layer_samples();
519                 bool bound_samples = sync->get_layer_bound_samples();
520                 int effective_layer_samples;
521
522                 if(samples != 0 && (!bound_samples || (samples < session_params.samples)))
523                         effective_layer_samples = samples;
524                 else
525                         effective_layer_samples = session_params.samples;
526
527                 /* Update tile manager if we're doing resumable render. */
528                 update_resumable_tile_manager(effective_layer_samples);
529
530                 /* Update session itself. */
531                 session->reset(buffer_params, effective_layer_samples);
532
533                 /* render */
534                 session->start();
535                 session->wait();
536
537                 if(!b_engine.is_preview() && background && print_render_stats) {
538                         RenderStats stats;
539                         session->collect_statistics(&stats);
540                         printf("Render statistics:\n%s\n", stats.full_report().c_str());
541                 }
542
543                 if(session->progress.get_cancel())
544                         break;
545         }
546
547         stamp_view_layer_metadata(b_rlay_name);
548
549         /* Write cryptomatte metadata. */
550         if(scene->film->cryptomatte_passes & CRYPT_OBJECT) {
551                 add_cryptomatte_layer(b_rr, b_rlay_name+".CryptoObject",
552                                                           scene->object_manager->get_cryptomatte_objects(scene));
553         }
554         if(scene->film->cryptomatte_passes & CRYPT_MATERIAL) {
555                 add_cryptomatte_layer(b_rr, b_rlay_name+".CryptoMaterial",
556                                                           scene->shader_manager->get_cryptomatte_materials(scene));
557         }
558         if(scene->film->cryptomatte_passes & CRYPT_ASSET) {
559                 add_cryptomatte_layer(b_rr, b_rlay_name+".CryptoAsset",
560                                                           scene->object_manager->get_cryptomatte_assets(scene));
561         }
562
563         /* free result without merging */
564         end_render_result(b_engine, b_rr, true, true, false);
565
566         double total_time, render_time;
567         session->progress.get_time(total_time, render_time);
568         VLOG(1) << "Total render time: " << total_time;
569         VLOG(1) << "Render time (without synchronization): " << render_time;
570
571         /* clear callback */
572         session->write_render_tile_cb = function_null;
573         session->update_render_tile_cb = function_null;
574
575         /* TODO: find a way to clear this data for persistent data render */
576 #if 0
577         /* free all memory used (host and device), so we wouldn't leave render
578          * engine with extra memory allocated
579          */
580
581         session->device_free();
582
583         delete sync;
584         sync = NULL;
585 #endif
586 }
587
588 static void populate_bake_data(BakeData *data, const
589                                int object_id,
590                                BL::BakePixel& pixel_array,
591                                const int num_pixels)
592 {
593         BL::BakePixel bp = pixel_array;
594
595         int i;
596         for(i = 0; i < num_pixels; i++) {
597                 if(bp.object_id() == object_id) {
598                         data->set(i, bp.primitive_id(), bp.uv(), bp.du_dx(), bp.du_dy(), bp.dv_dx(), bp.dv_dy());
599                 } else {
600                         data->set_null(i);
601                 }
602                 bp = bp.next();
603         }
604 }
605
606 static int bake_pass_filter_get(const int pass_filter)
607 {
608         int flag = BAKE_FILTER_NONE;
609
610         if((pass_filter & BL::BakeSettings::pass_filter_DIRECT) != 0)
611                 flag |= BAKE_FILTER_DIRECT;
612         if((pass_filter & BL::BakeSettings::pass_filter_INDIRECT) != 0)
613                 flag |= BAKE_FILTER_INDIRECT;
614         if((pass_filter & BL::BakeSettings::pass_filter_COLOR) != 0)
615                 flag |= BAKE_FILTER_COLOR;
616
617         if((pass_filter & BL::BakeSettings::pass_filter_DIFFUSE) != 0)
618                 flag |= BAKE_FILTER_DIFFUSE;
619         if((pass_filter & BL::BakeSettings::pass_filter_GLOSSY) != 0)
620                 flag |= BAKE_FILTER_GLOSSY;
621         if((pass_filter & BL::BakeSettings::pass_filter_TRANSMISSION) != 0)
622                 flag |= BAKE_FILTER_TRANSMISSION;
623         if((pass_filter & BL::BakeSettings::pass_filter_SUBSURFACE) != 0)
624                 flag |= BAKE_FILTER_SUBSURFACE;
625
626         if((pass_filter & BL::BakeSettings::pass_filter_EMIT) != 0)
627                 flag |= BAKE_FILTER_EMISSION;
628         if((pass_filter & BL::BakeSettings::pass_filter_AO) != 0)
629                 flag |= BAKE_FILTER_AO;
630
631         return flag;
632 }
633
634 void BlenderSession::bake(BL::Depsgraph& b_depsgraph_,
635                           BL::Object& b_object,
636                           const string& pass_type,
637                           const int pass_filter,
638                           const int object_id,
639                           BL::BakePixel& pixel_array,
640                           const size_t num_pixels,
641                           const int /*depth*/,
642                           float result[])
643 {
644         b_depsgraph = b_depsgraph_;
645
646         ShaderEvalType shader_type = get_shader_type(pass_type);
647
648         /* Set baking flag in advance, so kernel loading can check if we need
649          * any baking capabilities.
650          */
651         scene->bake_manager->set_baking(true);
652
653         /* ensure kernels are loaded before we do any scene updates */
654         session->load_kernels();
655
656         if(shader_type == SHADER_EVAL_UV) {
657                 /* force UV to be available */
658                 Pass::add(PASS_UV, scene->film->passes);
659         }
660
661         int bake_pass_filter = bake_pass_filter_get(pass_filter);
662         bake_pass_filter = BakeManager::shader_type_to_pass_filter(shader_type, bake_pass_filter);
663
664         /* force use_light_pass to be true if we bake more than just colors */
665         if(bake_pass_filter & ~BAKE_FILTER_COLOR) {
666                 Pass::add(PASS_LIGHT, scene->film->passes);
667         }
668
669         /* create device and update scene */
670         scene->film->tag_update(scene);
671         scene->integrator->tag_update(scene);
672
673         if(!session->progress.get_cancel()) {
674                 /* update scene */
675                 BL::Object b_camera_override(b_engine.camera_override());
676                 sync->sync_camera(b_render, b_camera_override, width, height, "");
677                 sync->sync_data(b_render,
678                                 b_depsgraph,
679                                 b_v3d,
680                                 b_camera_override,
681                                 width, height,
682                                 &python_thread_state);
683                 builtin_images_load();
684         }
685
686         BakeData *bake_data = NULL;
687
688         if(!session->progress.get_cancel()) {
689                 /* get buffer parameters */
690                 SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
691                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
692
693                 scene->bake_manager->set_shader_limit((size_t)b_engine.tile_x(), (size_t)b_engine.tile_y());
694
695                 /* set number of samples */
696                 session->tile_manager.set_samples(session_params.samples);
697                 session->reset(buffer_params, session_params.samples);
698                 session->update_scene();
699
700                 /* find object index. todo: is arbitrary - copied from mesh_displace.cpp */
701                 size_t object_index = OBJECT_NONE;
702                 int tri_offset = 0;
703
704                 for(size_t i = 0; i < scene->objects.size(); i++) {
705                         if(strcmp(scene->objects[i]->name.c_str(), b_object.name().c_str()) == 0) {
706                                 object_index = i;
707                                 tri_offset = scene->objects[i]->mesh->tri_offset;
708                                 break;
709                         }
710                 }
711
712                 /* Object might have been disabled for rendering or excluded in some
713                  * other way, in that case Blender will report a warning afterwards. */
714                 if (object_index != OBJECT_NONE) {
715                         int object = object_index;
716
717                         bake_data = scene->bake_manager->init(object, tri_offset, num_pixels);
718                         populate_bake_data(bake_data, object_id, pixel_array, num_pixels);
719                 }
720
721                 /* set number of samples */
722                 session->tile_manager.set_samples(session_params.samples);
723                 session->reset(buffer_params, session_params.samples);
724                 session->update_scene();
725
726                 session->progress.set_update_callback(function_bind(&BlenderSession::update_bake_progress, this));
727         }
728
729         /* Perform bake. Check cancel to avoid crash with incomplete scene data. */
730         if(!session->progress.get_cancel() && bake_data) {
731                 scene->bake_manager->bake(scene->device, &scene->dscene, scene, session->progress, shader_type, bake_pass_filter, bake_data, result);
732         }
733
734         /* free all memory used (host and device), so we wouldn't leave render
735          * engine with extra memory allocated
736          */
737
738         session->device_free();
739
740         delete sync;
741         sync = NULL;
742 }
743
744 void BlenderSession::do_write_update_render_result(BL::RenderResult& b_rr,
745                                                    BL::RenderLayer& b_rlay,
746                                                    RenderTile& rtile,
747                                                    bool do_update_only)
748 {
749         RenderBuffers *buffers = rtile.buffers;
750
751         /* copy data from device */
752         if(!buffers->copy_from_device())
753                 return;
754
755         float exposure = scene->film->exposure;
756
757         vector<float> pixels(rtile.w*rtile.h*4);
758
759         /* Adjust absolute sample number to the range. */
760         int sample = rtile.sample;
761         const int range_start_sample = session->tile_manager.range_start_sample;
762         if(range_start_sample != -1) {
763                 sample -= range_start_sample;
764         }
765
766         if(!do_update_only) {
767                 /* copy each pass */
768                 BL::RenderLayer::passes_iterator b_iter;
769
770                 for(b_rlay.passes.begin(b_iter); b_iter != b_rlay.passes.end(); ++b_iter) {
771                         BL::RenderPass b_pass(*b_iter);
772
773                         /* find matching pass type */
774                         PassType pass_type = BlenderSync::get_pass_type(b_pass);
775                         int components = b_pass.channels();
776
777                         bool read = false;
778                         if(pass_type != PASS_NONE) {
779                                 /* copy pixels */
780                                 read = buffers->get_pass_rect(pass_type, exposure, sample, components, &pixels[0], b_pass.name());
781                         }
782                         else {
783                                 int denoising_offset = BlenderSync::get_denoising_pass(b_pass);
784                                 if(denoising_offset >= 0) {
785                                         read = buffers->get_denoising_pass_rect(denoising_offset, exposure, sample, components, &pixels[0]);
786                                 }
787                         }
788
789                         if(!read) {
790                                 memset(&pixels[0], 0, pixels.size()*sizeof(float));
791                         }
792
793                         b_pass.rect(&pixels[0]);
794                 }
795         }
796         else {
797                 /* copy combined pass */
798                 BL::RenderPass b_combined_pass(b_rlay.passes.find_by_name("Combined", b_rview_name.c_str()));
799                 if(buffers->get_pass_rect(PASS_COMBINED, exposure, sample, 4, &pixels[0], "Combined"))
800                         b_combined_pass.rect(&pixels[0]);
801         }
802
803         /* tag result as updated */
804         b_engine.update_result(b_rr);
805 }
806
807 void BlenderSession::write_render_result(BL::RenderResult& b_rr,
808                                          BL::RenderLayer& b_rlay,
809                                          RenderTile& rtile)
810 {
811         do_write_update_render_result(b_rr, b_rlay, rtile, false);
812 }
813
814 void BlenderSession::update_render_result(BL::RenderResult& b_rr,
815                                           BL::RenderLayer& b_rlay,
816                                           RenderTile& rtile)
817 {
818         do_write_update_render_result(b_rr, b_rlay, rtile, true);
819 }
820
821 void BlenderSession::synchronize(BL::Depsgraph& b_depsgraph_)
822 {
823         /* only used for viewport render */
824         if(!b_v3d)
825                 return;
826
827         /* on session/scene parameter changes, we recreate session entirely */
828         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
829         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
830         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
831
832         if(session->params.modified(session_params) ||
833            scene->params.modified(scene_params))
834         {
835                 free_session();
836                 create_session();
837                 return;
838         }
839
840         /* increase samples, but never decrease */
841         session->set_samples(session_params.samples);
842         session->set_pause(session_pause);
843
844         /* copy recalc flags, outside of mutex so we can decide to do the real
845          * synchronization at a later time to not block on running updates */
846         sync->sync_recalc(b_depsgraph_);
847
848         /* don't do synchronization if on pause */
849         if(session_pause) {
850                 tag_update();
851                 return;
852         }
853
854         /* try to acquire mutex. if we don't want to or can't, come back later */
855         if(!session->ready_to_reset() || !session->scene->mutex.try_lock()) {
856                 tag_update();
857                 return;
858         }
859
860         /* data and camera synchronize */
861         b_depsgraph = b_depsgraph_;
862
863         BL::Object b_camera_override(b_engine.camera_override());
864         sync->sync_data(b_render,
865                         b_depsgraph,
866                         b_v3d,
867                         b_camera_override,
868                         width, height,
869                         &python_thread_state);
870
871         if(b_rv3d)
872                 sync->sync_view(b_v3d, b_rv3d, width, height);
873         else
874                 sync->sync_camera(b_render, b_camera_override, width, height, "");
875
876         builtin_images_load();
877
878         /* unlock */
879         session->scene->mutex.unlock();
880
881         /* reset if needed */
882         if(scene->need_reset()) {
883                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
884                 session->reset(buffer_params, session_params.samples);
885
886                 /* reset time */
887                 start_resize_time = 0.0;
888         }
889
890         /* Start rendering thread, if it's not running already. Do this
891          * after all scene data has been synced at least once. */
892         session->start();
893 }
894
895 bool BlenderSession::draw(int w, int h)
896 {
897         /* pause in redraw in case update is not being called due to final render */
898         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
899
900         /* before drawing, we verify camera and viewport size changes, because
901          * we do not get update callbacks for those, we must detect them here */
902         if(session->ready_to_reset()) {
903                 bool reset = false;
904
905                 /* if dimensions changed, reset */
906                 if(width != w || height != h) {
907                         if(start_resize_time == 0.0) {
908                                 /* don't react immediately to resizes to avoid flickery resizing
909                                  * of the viewport, and some window managers changing the window
910                                  * size temporarily on unminimize */
911                                 start_resize_time = time_dt();
912                                 tag_redraw();
913                         }
914                         else if(time_dt() - start_resize_time < 0.2) {
915                                 tag_redraw();
916                         }
917                         else {
918                                 width = w;
919                                 height = h;
920                                 reset = true;
921                         }
922                 }
923
924                 /* try to acquire mutex. if we can't, come back later */
925                 if(!session->scene->mutex.try_lock()) {
926                         tag_update();
927                 }
928                 else {
929                         /* update camera from 3d view */
930
931                         sync->sync_view(b_v3d, b_rv3d, width, height);
932
933                         if(scene->camera->need_update)
934                                 reset = true;
935
936                         session->scene->mutex.unlock();
937                 }
938
939                 /* reset if requested */
940                 if(reset) {
941                         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
942                         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
943                         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
944
945                         if(session_pause == false) {
946                                 session->reset(buffer_params, session_params.samples);
947                                 start_resize_time = 0.0;
948                         }
949                 }
950         }
951         else {
952                 tag_update();
953         }
954
955         /* update status and progress for 3d view draw */
956         update_status_progress();
957
958         /* draw */
959         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
960         DeviceDrawParams draw_params;
961
962         if(session->params.display_buffer_linear) {
963                 draw_params.bind_display_space_shader_cb = function_bind(&BL::RenderEngine::bind_display_space_shader, &b_engine, b_scene);
964                 draw_params.unbind_display_space_shader_cb = function_bind(&BL::RenderEngine::unbind_display_space_shader, &b_engine);
965         }
966
967         return !session->draw(buffer_params, draw_params);
968 }
969
970 void BlenderSession::get_status(string& status, string& substatus)
971 {
972         session->progress.get_status(status, substatus);
973 }
974
975 void BlenderSession::get_progress(float& progress, double& total_time, double& render_time)
976 {
977         session->progress.get_time(total_time, render_time);
978         progress = session->progress.get_progress();
979 }
980
981 void BlenderSession::update_bake_progress()
982 {
983         float progress = session->progress.get_progress();
984
985         if(progress != last_progress) {
986                 b_engine.update_progress(progress);
987                 last_progress = progress;
988         }
989 }
990
991 void BlenderSession::update_status_progress()
992 {
993         string timestatus, status, substatus;
994         string scene_status = "";
995         float progress;
996         double total_time, remaining_time = 0, render_time;
997         char time_str[128];
998         float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
999         float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
1000
1001         get_status(status, substatus);
1002         get_progress(progress, total_time, render_time);
1003
1004         if(progress > 0)
1005                 remaining_time = (1.0 - (double)progress) * (render_time / (double)progress);
1006
1007         if(background) {
1008                 scene_status += " | " + scene->name;
1009                 if(b_rlay_name != "")
1010                         scene_status += ", "  + b_rlay_name;
1011
1012                 if(b_rview_name != "")
1013                         scene_status += ", " + b_rview_name;
1014
1015                 if(remaining_time > 0) {
1016                         BLI_timecode_string_from_time_simple(time_str, sizeof(time_str), remaining_time);
1017                         timestatus += "Remaining:" + string(time_str) + " | ";
1018                 }
1019
1020                 timestatus += string_printf("Mem:%.2fM, Peak:%.2fM", (double)mem_used, (double)mem_peak);
1021
1022                 if(status.size() > 0)
1023                         status = " | " + status;
1024                 if(substatus.size() > 0)
1025                         status += " | " + substatus;
1026         }
1027
1028         double current_time = time_dt();
1029         /* When rendering in a window, redraw the status at least once per second to keep the elapsed and remaining time up-to-date.
1030          * For headless rendering, only report when something significant changes to keep the console output readable. */
1031         if(status != last_status || (!headless && (current_time - last_status_time) > 1.0)) {
1032                 b_engine.update_stats("", (timestatus + scene_status + status).c_str());
1033                 b_engine.update_memory_stats(mem_used, mem_peak);
1034                 last_status = status;
1035                 last_status_time = current_time;
1036         }
1037         if(progress != last_progress) {
1038                 b_engine.update_progress(progress);
1039                 last_progress = progress;
1040         }
1041
1042         if(session->progress.get_error()) {
1043                 string error = session->progress.get_error_message();
1044                 if(error != last_error) {
1045                         /* TODO(sergey): Currently C++ RNA API doesn't let us to
1046                          * use mnemonic name for the variable. Would be nice to
1047                          * have this figured out.
1048                          *
1049                          * For until then, 1 << 5 means RPT_ERROR.
1050                          */
1051                         b_engine.report(1 << 5, error.c_str());
1052                         b_engine.error_set(error.c_str());
1053                         last_error = error;
1054                 }
1055         }
1056 }
1057
1058 void BlenderSession::tag_update()
1059 {
1060         /* tell blender that we want to get another update callback */
1061         b_engine.tag_update();
1062 }
1063
1064 void BlenderSession::tag_redraw()
1065 {
1066         if(background) {
1067                 /* update stats and progress, only for background here because
1068                  * in 3d view we do it in draw for thread safety reasons */
1069                 update_status_progress();
1070
1071                 /* offline render, redraw if timeout passed */
1072                 if(time_dt() - last_redraw_time > 1.0) {
1073                         b_engine.tag_redraw();
1074                         last_redraw_time = time_dt();
1075                 }
1076         }
1077         else {
1078                 /* tell blender that we want to redraw */
1079                 b_engine.tag_redraw();
1080         }
1081 }
1082
1083 void BlenderSession::test_cancel()
1084 {
1085         /* test if we need to cancel rendering */
1086         if(background)
1087                 if(b_engine.test_break())
1088                         session->progress.set_cancel("Cancelled");
1089 }
1090
1091 /* builtin image file name is actually an image datablock name with
1092  * absolute sequence frame number concatenated via '@' character
1093  *
1094  * this function splits frame from builtin name
1095  */
1096 int BlenderSession::builtin_image_frame(const string &builtin_name)
1097 {
1098         int last = builtin_name.find_last_of('@');
1099         return atoi(builtin_name.substr(last + 1, builtin_name.size() - last - 1).c_str());
1100 }
1101
1102 void BlenderSession::builtin_image_info(const string &builtin_name,
1103                                         void *builtin_data,
1104                                         ImageMetaData& metadata)
1105 {
1106         /* empty image */
1107         metadata.width = 1;
1108         metadata.height = 1;
1109
1110         if(!builtin_data)
1111                 return;
1112
1113         /* recover ID pointer */
1114         PointerRNA ptr;
1115         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1116         BL::ID b_id(ptr);
1117
1118         if(b_id.is_a(&RNA_Image)) {
1119                 /* image data */
1120                 BL::Image b_image(b_id);
1121
1122                 metadata.builtin_free_cache = !b_image.has_data();
1123                 metadata.is_float = b_image.is_float();
1124                 metadata.width = b_image.size()[0];
1125                 metadata.height = b_image.size()[1];
1126                 metadata.depth = 1;
1127                 metadata.channels = b_image.channels();
1128         }
1129         else if(b_id.is_a(&RNA_Object)) {
1130                 /* smoke volume data */
1131                 BL::Object b_ob(b_id);
1132                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
1133
1134                 metadata.is_float = true;
1135                 metadata.depth = 1;
1136                 metadata.channels = 1;
1137
1138                 if(!b_domain)
1139                         return;
1140
1141                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY) ||
1142                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME) ||
1143                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT) ||
1144                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_TEMPERATURE))
1145                         metadata.channels = 1;
1146                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR))
1147                         metadata.channels = 4;
1148                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY))
1149                         metadata.channels = 3;
1150                 else
1151                         return;
1152
1153                 int3 resolution = get_int3(b_domain.domain_resolution());
1154                 int amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
1155
1156                 /* Velocity and heat data is always low-resolution. */
1157                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY) ||
1158                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT))
1159                 {
1160                         amplify = 1;
1161                 }
1162
1163                 metadata.width = resolution.x * amplify;
1164                 metadata.height = resolution.y * amplify;
1165                 metadata.depth = resolution.z * amplify;
1166         }
1167         else {
1168                 /* TODO(sergey): Check we're indeed in shader node tree. */
1169                 PointerRNA ptr;
1170                 RNA_pointer_create(NULL, &RNA_Node, builtin_data, &ptr);
1171                 BL::Node b_node(ptr);
1172                 if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
1173                         BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
1174                         metadata.channels = 4;
1175                         metadata.width = b_point_density_node.resolution();
1176                         metadata.height = metadata.width;
1177                         metadata.depth = metadata.width;
1178                         metadata.is_float = true;
1179                 }
1180         }
1181 }
1182
1183 bool BlenderSession::builtin_image_pixels(const string &builtin_name,
1184                                           void *builtin_data,
1185                                           unsigned char *pixels,
1186                                           const size_t pixels_size,
1187                                           const bool free_cache)
1188 {
1189         if(!builtin_data) {
1190                 return false;
1191         }
1192
1193         const int frame = builtin_image_frame(builtin_name);
1194
1195         PointerRNA ptr;
1196         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1197         BL::Image b_image(ptr);
1198
1199         const int width = b_image.size()[0];
1200         const int height = b_image.size()[1];
1201         const int channels = b_image.channels();
1202
1203         unsigned char *image_pixels = image_get_pixels_for_frame(b_image, frame);
1204         const size_t num_pixels = ((size_t)width) * height;
1205
1206         if(image_pixels && num_pixels * channels == pixels_size) {
1207                 memcpy(pixels, image_pixels, pixels_size * sizeof(unsigned char));
1208         }
1209         else {
1210                 if(channels == 1) {
1211                         memset(pixels, 0, pixels_size * sizeof(unsigned char));
1212                 }
1213                 else {
1214                         const size_t num_pixels_safe = pixels_size / channels;
1215                         unsigned char *cp = pixels;
1216                         for(size_t i = 0; i < num_pixels_safe; i++, cp += channels) {
1217                                 cp[0] = 255;
1218                                 cp[1] = 0;
1219                                 cp[2] = 255;
1220                                 if(channels == 4) {
1221                                         cp[3] = 255;
1222                                 }
1223                         }
1224                 }
1225         }
1226
1227         if(image_pixels) {
1228                 MEM_freeN(image_pixels);
1229         }
1230
1231         /* Free image buffers to save memory during render. */
1232         if(free_cache) {
1233                 b_image.buffers_free();
1234         }
1235
1236         /* Premultiply, byte images are always straight for Blender. */
1237         unsigned char *cp = pixels;
1238         for(size_t i = 0; i < num_pixels; i++, cp += channels) {
1239                 cp[0] = (cp[0] * cp[3]) >> 8;
1240                 cp[1] = (cp[1] * cp[3]) >> 8;
1241                 cp[2] = (cp[2] * cp[3]) >> 8;
1242         }
1243         return true;
1244 }
1245
1246 bool BlenderSession::builtin_image_float_pixels(const string &builtin_name,
1247                                                 void *builtin_data,
1248                                                 float *pixels,
1249                                                 const size_t pixels_size,
1250                                                 const bool free_cache)
1251 {
1252         if(!builtin_data) {
1253                 return false;
1254         }
1255
1256         PointerRNA ptr;
1257         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1258         BL::ID b_id(ptr);
1259
1260         if(b_id.is_a(&RNA_Image)) {
1261                 /* image data */
1262                 BL::Image b_image(b_id);
1263                 int frame = builtin_image_frame(builtin_name);
1264
1265                 const int width = b_image.size()[0];
1266                 const int height = b_image.size()[1];
1267                 const int channels = b_image.channels();
1268
1269                 float *image_pixels;
1270                 image_pixels = image_get_float_pixels_for_frame(b_image, frame);
1271                 const size_t num_pixels = ((size_t)width) * height;
1272
1273                 if(image_pixels && num_pixels * channels == pixels_size) {
1274                         memcpy(pixels, image_pixels, pixels_size * sizeof(float));
1275                 }
1276                 else {
1277                         if(channels == 1) {
1278                                 memset(pixels, 0, num_pixels * sizeof(float));
1279                         }
1280                         else {
1281                                 const size_t num_pixels_safe = pixels_size / channels;
1282                                 float *fp = pixels;
1283                                 for(int i = 0; i < num_pixels_safe; i++, fp += channels) {
1284                                         fp[0] = 1.0f;
1285                                         fp[1] = 0.0f;
1286                                         fp[2] = 1.0f;
1287                                         if(channels == 4) {
1288                                                 fp[3] = 1.0f;
1289                                         }
1290                                 }
1291                         }
1292                 }
1293
1294                 if(image_pixels) {
1295                         MEM_freeN(image_pixels);
1296                 }
1297
1298                 /* Free image buffers to save memory during render. */
1299                 if(free_cache) {
1300                         b_image.buffers_free();
1301                 }
1302
1303                 return true;
1304         }
1305         else if(b_id.is_a(&RNA_Object)) {
1306                 /* smoke volume data */
1307                 BL::Object b_ob(b_id);
1308                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
1309
1310                 if(!b_domain) {
1311                         return false;
1312                 }
1313
1314                 int3 resolution = get_int3(b_domain.domain_resolution());
1315                 int length, amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
1316
1317                 /* Velocity and heat data is always low-resolution. */
1318                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY) ||
1319                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT))
1320                 {
1321                         amplify = 1;
1322                 }
1323
1324                 const int width = resolution.x * amplify;
1325                 const int height = resolution.y * amplify;
1326                 const int depth = resolution.z * amplify;
1327                 const size_t num_pixels = ((size_t)width) * height * depth;
1328
1329                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY)) {
1330                         SmokeDomainSettings_density_grid_get_length(&b_domain.ptr, &length);
1331                         if(length == num_pixels) {
1332                                 SmokeDomainSettings_density_grid_get(&b_domain.ptr, pixels);
1333                                 return true;
1334                         }
1335                 }
1336                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME)) {
1337                         /* this is in range 0..1, and interpreted by the OpenGL smoke viewer
1338                          * as 1500..3000 K with the first part faded to zero density */
1339                         SmokeDomainSettings_flame_grid_get_length(&b_domain.ptr, &length);
1340                         if(length == num_pixels) {
1341                                 SmokeDomainSettings_flame_grid_get(&b_domain.ptr, pixels);
1342                                 return true;
1343                         }
1344                 }
1345                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR)) {
1346                         /* the RGB is "premultiplied" by density for better interpolation results */
1347                         SmokeDomainSettings_color_grid_get_length(&b_domain.ptr, &length);
1348                         if(length == num_pixels*4) {
1349                                 SmokeDomainSettings_color_grid_get(&b_domain.ptr, pixels);
1350                                 return true;
1351                         }
1352                 }
1353                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_VELOCITY)) {
1354                         SmokeDomainSettings_velocity_grid_get_length(&b_domain.ptr, &length);
1355                         if(length == num_pixels*3) {
1356                                 SmokeDomainSettings_velocity_grid_get(&b_domain.ptr, pixels);
1357                                 return true;
1358                         }
1359                 }
1360                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_HEAT)) {
1361                         SmokeDomainSettings_heat_grid_get_length(&b_domain.ptr, &length);
1362                         if(length == num_pixels) {
1363                                 SmokeDomainSettings_heat_grid_get(&b_domain.ptr, pixels);
1364                                 return true;
1365                         }
1366                 }
1367                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_TEMPERATURE)) {
1368                         SmokeDomainSettings_temperature_grid_get_length(&b_domain.ptr, &length);
1369                         if(length == num_pixels) {
1370                                 SmokeDomainSettings_temperature_grid_get(&b_domain.ptr, pixels);
1371                                 return true;
1372                         }
1373                 }
1374                 else {
1375                         fprintf(stderr,
1376                                 "Cycles error: unknown volume attribute %s, skipping\n",
1377                                 builtin_name.c_str());
1378                         pixels[0] = 0.0f;
1379                         return false;
1380                 }
1381
1382                 fprintf(stderr, "Cycles error: unexpected smoke volume resolution, skipping\n");
1383         }
1384         else {
1385                 /* We originally were passing view_layer here but in reality we need a
1386                  * a depsgraph to pass to the RE_point_density_minmax() function.
1387                  */
1388                 /* TODO(sergey): Check we're indeed in shader node tree. */
1389                 PointerRNA ptr;
1390                 RNA_pointer_create(NULL, &RNA_Node, builtin_data, &ptr);
1391                 BL::Node b_node(ptr);
1392                 if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
1393                         BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
1394                         int length;
1395                         b_point_density_node.calc_point_density(b_depsgraph, &length, &pixels);
1396                 }
1397         }
1398
1399         return false;
1400 }
1401
1402 void BlenderSession::builtin_images_load()
1403 {
1404         /* Force builtin images to be loaded along with Blender data sync. This
1405          * is needed because we may be reading from depsgraph evaluated data which
1406          * can be freed by Blender before Cycles reads it. */
1407         ImageManager *manager = session->scene->image_manager;
1408         Device *device = session->device;
1409         manager->device_load_builtin(device, session->scene, session->progress);
1410 }
1411
1412 void BlenderSession::update_resumable_tile_manager(int num_samples)
1413 {
1414         const int num_resumable_chunks = BlenderSession::num_resumable_chunks,
1415                   current_resumable_chunk = BlenderSession::current_resumable_chunk;
1416         if(num_resumable_chunks == 0) {
1417                 return;
1418         }
1419
1420         if (num_resumable_chunks > num_samples) {
1421                 fprintf(stderr, "Cycles warning: more sample chunks (%d) than samples (%d), "
1422                         "this will cause some samples to be included in multiple chunks.\n",
1423                         num_resumable_chunks, num_samples);
1424         }
1425
1426         const float num_samples_per_chunk = (float)num_samples / num_resumable_chunks;
1427
1428         float range_start_sample, range_num_samples;
1429         if(current_resumable_chunk != 0) {
1430                 /* Single chunk rendering. */
1431                 range_start_sample = num_samples_per_chunk * (current_resumable_chunk - 1);
1432                 range_num_samples = num_samples_per_chunk;
1433         }
1434         else {
1435                 /* Ranged-chunks. */
1436                 const int num_chunks = end_resumable_chunk - start_resumable_chunk + 1;
1437                 range_start_sample = num_samples_per_chunk * (start_resumable_chunk - 1);
1438                 range_num_samples = num_chunks * num_samples_per_chunk;
1439         }
1440
1441         /* Round after doing the multiplications with num_chunks and num_samples_per_chunk
1442          * to allow for many small chunks. */
1443         int rounded_range_start_sample = (int)floor(range_start_sample + 0.5f);
1444         int rounded_range_num_samples = max((int)floor(range_num_samples + 0.5f), 1);
1445
1446         /* Make sure we don't overshoot. */
1447         if(rounded_range_start_sample + rounded_range_num_samples > num_samples) {
1448                 rounded_range_num_samples = num_samples - rounded_range_num_samples;
1449         }
1450
1451         VLOG(1) << "Samples range start is " << range_start_sample << ", "
1452                 << "number of samples to render is " << range_num_samples;
1453
1454         scene->integrator->start_sample = rounded_range_start_sample;
1455         scene->integrator->tag_update(scene);
1456
1457         session->tile_manager.range_start_sample = rounded_range_start_sample;
1458         session->tile_manager.range_num_samples = rounded_range_num_samples;
1459 }
1460
1461 void BlenderSession::free_blender_memory_if_possible()
1462 {
1463         if(!background) {
1464                 /* During interactive render we can not free anything: attempts to save
1465                  * memory would cause things to be allocated and evaluated for every
1466                  * updated sample.
1467                  */
1468                 return;
1469         }
1470         b_engine.free_blender_memory();
1471 }
1472
1473 CCL_NAMESPACE_END