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