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