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