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