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