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