Multi-View and Stereo 3D
[blender-staging.git] / intern / cycles / blender / blender_session.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdlib.h>
18
19 #include "background.h"
20 #include "buffers.h"
21 #include "camera.h"
22 #include "device.h"
23 #include "integrator.h"
24 #include "film.h"
25 #include "light.h"
26 #include "mesh.h"
27 #include "object.h"
28 #include "scene.h"
29 #include "session.h"
30 #include "shader.h"
31
32 #include "util_color.h"
33 #include "util_foreach.h"
34 #include "util_function.h"
35 #include "util_progress.h"
36 #include "util_time.h"
37
38 #include "blender_sync.h"
39 #include "blender_session.h"
40 #include "blender_util.h"
41
42 CCL_NAMESPACE_BEGIN
43
44 bool BlenderSession::headless = false;
45
46 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
47         BL::BlendData b_data_, BL::Scene b_scene_)
48 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_engine_.render()), b_scene(b_scene_),
49   b_v3d(PointerRNA_NULL), b_rv3d(PointerRNA_NULL), python_thread_state(NULL)
50 {
51         /* offline render */
52
53         width = render_resolution_x(b_render);
54         height = render_resolution_y(b_render);
55
56         background = true;
57         last_redraw_time = 0.0;
58         start_resize_time = 0.0;
59 }
60
61 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
62         BL::BlendData b_data_, BL::Scene b_scene_,
63         BL::SpaceView3D b_v3d_, BL::RegionView3D b_rv3d_, int width_, int height_)
64 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_scene_.render()), b_scene(b_scene_),
65   b_v3d(b_v3d_), b_rv3d(b_rv3d_), python_thread_state(NULL)
66 {
67         /* 3d view render */
68
69         width = width_;
70         height = height_;
71         background = false;
72         last_redraw_time = 0.0;
73         start_resize_time = 0.0;
74 }
75
76 BlenderSession::~BlenderSession()
77 {
78         free_session();
79 }
80
81 void BlenderSession::create()
82 {
83         create_session();
84
85         if(b_v3d)
86                 session->start();
87 }
88
89 void BlenderSession::create_session()
90 {
91         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
92         bool is_cpu = session_params.device.type == DEVICE_CPU;
93         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background, is_cpu);
94         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
95
96         /* reset status/progress */
97         last_status = "";
98         last_error = "";
99         last_progress = -1.0f;
100         start_resize_time = 0.0;
101
102         /* create scene */
103         scene = new Scene(scene_params, session_params.device);
104
105         /* setup callbacks for builtin image support */
106         scene->image_manager->builtin_image_info_cb = function_bind(&BlenderSession::builtin_image_info, this, _1, _2, _3, _4, _5, _6, _7);
107         scene->image_manager->builtin_image_pixels_cb = function_bind(&BlenderSession::builtin_image_pixels, this, _1, _2, _3);
108         scene->image_manager->builtin_image_float_pixels_cb = function_bind(&BlenderSession::builtin_image_float_pixels, this, _1, _2, _3);
109
110         /* create session */
111         session = new Session(session_params);
112         session->scene = scene;
113         session->progress.set_update_callback(function_bind(&BlenderSession::tag_redraw, this));
114         session->progress.set_cancel_callback(function_bind(&BlenderSession::test_cancel, this));
115         session->set_pause(session_pause);
116
117         /* create sync */
118         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, is_cpu);
119
120         if(b_v3d) {
121                 if(session_pause == false) {
122                         /* full data sync */
123                         sync->sync_view(b_v3d, b_rv3d, width, height);
124                         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
125                 }
126         }
127         else {
128                 /* for final render we will do full data sync per render layer, only
129                  * do some basic syncing here, no objects or materials for speed */
130                 sync->sync_render_layers(b_v3d, NULL);
131                 sync->sync_integrator();
132                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
133         }
134
135         /* set buffer parameters */
136         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
137         session->reset(buffer_params, session_params.samples);
138
139         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
140 }
141
142 void BlenderSession::reset_session(BL::BlendData b_data_, BL::Scene b_scene_)
143 {
144         b_data = b_data_;
145         b_render = b_engine.render();
146         b_scene = b_scene_;
147
148         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
149         const bool is_cpu = session_params.device.type == DEVICE_CPU;
150         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background, is_cpu);
151
152         width = render_resolution_x(b_render);
153         height = render_resolution_y(b_render);
154
155         if(scene->params.modified(scene_params) ||
156            session->params.modified(session_params) ||
157            !scene_params.persistent_data)
158         {
159                 /* if scene or session parameters changed, it's easier to simply re-create
160                  * them rather than trying to distinguish which settings need to be updated
161                  */
162
163                 delete session;
164
165                 create_session();
166
167                 return;
168         }
169
170         session->progress.reset();
171         scene->reset();
172
173         session->tile_manager.set_tile_order(session_params.tile_order);
174
175         /* peak memory usage should show current render peak, not peak for all renders
176          * made by this render session
177          */
178         session->stats.mem_peak = session->stats.mem_used;
179
180         /* sync object should be re-created */
181         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, is_cpu);
182
183         /* for final render we will do full data sync per render layer, only
184          * do some basic syncing here, no objects or materials for speed */
185         sync->sync_render_layers(b_v3d, NULL);
186         sync->sync_integrator();
187         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
188
189         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, PointerRNA_NULL, PointerRNA_NULL, scene->camera, width, height);
190         session->reset(buffer_params, session_params.samples);
191
192         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
193
194         /* reset time */
195         start_resize_time = 0.0;
196 }
197
198 void BlenderSession::free_session()
199 {
200         if(sync)
201                 delete sync;
202
203         delete session;
204 }
205
206 static PassType get_pass_type(BL::RenderPass b_pass)
207 {
208         switch(b_pass.type()) {
209                 case BL::RenderPass::type_COMBINED:
210                         return PASS_COMBINED;
211
212                 case BL::RenderPass::type_Z:
213                         return PASS_DEPTH;
214                 case BL::RenderPass::type_MIST:
215                         return PASS_MIST;
216                 case BL::RenderPass::type_NORMAL:
217                         return PASS_NORMAL;
218                 case BL::RenderPass::type_OBJECT_INDEX:
219                         return PASS_OBJECT_ID;
220                 case BL::RenderPass::type_UV:
221                         return PASS_UV;
222                 case BL::RenderPass::type_VECTOR:
223                         return PASS_MOTION;
224                 case BL::RenderPass::type_MATERIAL_INDEX:
225                         return PASS_MATERIAL_ID;
226
227                 case BL::RenderPass::type_DIFFUSE_DIRECT:
228                         return PASS_DIFFUSE_DIRECT;
229                 case BL::RenderPass::type_GLOSSY_DIRECT:
230                         return PASS_GLOSSY_DIRECT;
231                 case BL::RenderPass::type_TRANSMISSION_DIRECT:
232                         return PASS_TRANSMISSION_DIRECT;
233                 case BL::RenderPass::type_SUBSURFACE_DIRECT:
234                         return PASS_SUBSURFACE_DIRECT;
235
236                 case BL::RenderPass::type_DIFFUSE_INDIRECT:
237                         return PASS_DIFFUSE_INDIRECT;
238                 case BL::RenderPass::type_GLOSSY_INDIRECT:
239                         return PASS_GLOSSY_INDIRECT;
240                 case BL::RenderPass::type_TRANSMISSION_INDIRECT:
241                         return PASS_TRANSMISSION_INDIRECT;
242                 case BL::RenderPass::type_SUBSURFACE_INDIRECT:
243                         return PASS_SUBSURFACE_INDIRECT;
244
245                 case BL::RenderPass::type_DIFFUSE_COLOR:
246                         return PASS_DIFFUSE_COLOR;
247                 case BL::RenderPass::type_GLOSSY_COLOR:
248                         return PASS_GLOSSY_COLOR;
249                 case BL::RenderPass::type_TRANSMISSION_COLOR:
250                         return PASS_TRANSMISSION_COLOR;
251                 case BL::RenderPass::type_SUBSURFACE_COLOR:
252                         return PASS_SUBSURFACE_COLOR;
253
254                 case BL::RenderPass::type_EMIT:
255                         return PASS_EMISSION;
256                 case BL::RenderPass::type_ENVIRONMENT:
257                         return PASS_BACKGROUND;
258                 case BL::RenderPass::type_AO:
259                         return PASS_AO;
260                 case BL::RenderPass::type_SHADOW:
261                         return PASS_SHADOW;
262
263                 case BL::RenderPass::type_DIFFUSE:
264                 case BL::RenderPass::type_COLOR:
265                 case BL::RenderPass::type_REFRACTION:
266                 case BL::RenderPass::type_SPECULAR:
267                 case BL::RenderPass::type_REFLECTION:
268                         return PASS_NONE;
269 #ifdef WITH_CYCLES_DEBUG
270                 case BL::RenderPass::type_DEBUG:
271                 {
272                         if(b_pass.debug_type() == BL::RenderPass::debug_type_BVH_TRAVERSAL_STEPS)
273                                 return PASS_BVH_TRAVERSAL_STEPS;
274                         break;
275                 }
276 #endif
277         }
278         
279         return PASS_NONE;
280 }
281
282 static ShaderEvalType get_shader_type(const string& pass_type)
283 {
284         const char *shader_type = pass_type.c_str();
285
286         /* data passes */
287         if(strcmp(shader_type, "NORMAL")==0)
288                 return SHADER_EVAL_NORMAL;
289         else if(strcmp(shader_type, "UV")==0)
290                 return SHADER_EVAL_UV;
291         else if(strcmp(shader_type, "DIFFUSE_COLOR")==0)
292                 return SHADER_EVAL_DIFFUSE_COLOR;
293         else if(strcmp(shader_type, "GLOSSY_COLOR")==0)
294                 return SHADER_EVAL_GLOSSY_COLOR;
295         else if(strcmp(shader_type, "TRANSMISSION_COLOR")==0)
296                 return SHADER_EVAL_TRANSMISSION_COLOR;
297         else if(strcmp(shader_type, "SUBSURFACE_COLOR")==0)
298                 return SHADER_EVAL_SUBSURFACE_COLOR;
299         else if(strcmp(shader_type, "EMIT")==0)
300                 return SHADER_EVAL_EMISSION;
301
302         /* light passes */
303         else if(strcmp(shader_type, "AO")==0)
304                 return SHADER_EVAL_AO;
305         else if(strcmp(shader_type, "COMBINED")==0)
306                 return SHADER_EVAL_COMBINED;
307         else if(strcmp(shader_type, "SHADOW")==0)
308                 return SHADER_EVAL_SHADOW;
309         else if(strcmp(shader_type, "DIFFUSE_DIRECT")==0)
310                 return SHADER_EVAL_DIFFUSE_DIRECT;
311         else if(strcmp(shader_type, "GLOSSY_DIRECT")==0)
312                 return SHADER_EVAL_GLOSSY_DIRECT;
313         else if(strcmp(shader_type, "TRANSMISSION_DIRECT")==0)
314                 return SHADER_EVAL_TRANSMISSION_DIRECT;
315         else if(strcmp(shader_type, "SUBSURFACE_DIRECT")==0)
316                 return SHADER_EVAL_SUBSURFACE_DIRECT;
317         else if(strcmp(shader_type, "DIFFUSE_INDIRECT")==0)
318                 return SHADER_EVAL_DIFFUSE_INDIRECT;
319         else if(strcmp(shader_type, "GLOSSY_INDIRECT")==0)
320                 return SHADER_EVAL_GLOSSY_INDIRECT;
321         else if(strcmp(shader_type, "TRANSMISSION_INDIRECT")==0)
322                 return SHADER_EVAL_TRANSMISSION_INDIRECT;
323         else if(strcmp(shader_type, "SUBSURFACE_INDIRECT")==0)
324                 return SHADER_EVAL_SUBSURFACE_INDIRECT;
325
326         /* extra */
327         else if(strcmp(shader_type, "ENVIRONMENT")==0)
328                 return SHADER_EVAL_ENVIRONMENT;
329
330         else
331                 return SHADER_EVAL_BAKE;
332 }
333
334 static BL::RenderResult begin_render_result(BL::RenderEngine b_engine, int x, int y, int w, int h, const char *layername, const char *viewname)
335 {
336         return b_engine.begin_result(x, y, w, h, layername, viewname);
337 }
338
339 static void end_render_result(BL::RenderEngine b_engine, BL::RenderResult b_rr, bool cancel, bool do_merge_results)
340 {
341         b_engine.end_result(b_rr, (int)cancel, (int)do_merge_results);
342 }
343
344 void BlenderSession::do_write_update_render_tile(RenderTile& rtile, bool do_update_only)
345 {
346         BufferParams& params = rtile.buffers->params;
347         int x = params.full_x - session->tile_manager.params.full_x;
348         int y = params.full_y - session->tile_manager.params.full_y;
349         int w = params.width;
350         int h = params.height;
351
352         /* get render result */
353         BL::RenderResult b_rr = begin_render_result(b_engine, x, y, w, h, b_rlay_name.c_str(), b_rview_name.c_str());
354
355         /* can happen if the intersected rectangle gives 0 width or height */
356         if(b_rr.ptr.data == NULL) {
357                 return;
358         }
359
360         BL::RenderResult::layers_iterator b_single_rlay;
361         b_rr.layers.begin(b_single_rlay);
362
363         /* layer will be missing if it was disabled in the UI */
364         if(b_single_rlay == b_rr.layers.end())
365                 return;
366
367         BL::RenderLayer b_rlay = *b_single_rlay;
368
369         if(do_update_only) {
370                 /* update only needed */
371
372                 if(rtile.sample != 0) {
373                         /* sample would be zero at initial tile update, which is only needed
374                          * to tag tile form blender side as IN PROGRESS for proper highlight
375                          * no buffers should be sent to blender yet
376                          */
377                         update_render_result(b_rr, b_rlay, rtile);
378                 }
379
380                 end_render_result(b_engine, b_rr, true, true);
381         }
382         else {
383                 /* write result */
384                 write_render_result(b_rr, b_rlay, rtile);
385                 end_render_result(b_engine, b_rr, false, true);
386         }
387 }
388
389 void BlenderSession::write_render_tile(RenderTile& rtile)
390 {
391         do_write_update_render_tile(rtile, false);
392 }
393
394 void BlenderSession::update_render_tile(RenderTile& rtile)
395 {
396         /* use final write for preview renders, otherwise render result wouldn't be
397          * be updated in blender side
398          * would need to be investigated a bit further, but for now shall be fine
399          */
400         if(!b_engine.is_preview())
401                 do_write_update_render_tile(rtile, true);
402         else
403                 do_write_update_render_tile(rtile, false);
404 }
405
406 void BlenderSession::render()
407 {
408         /* set callback to write out render results */
409         session->write_render_tile_cb = function_bind(&BlenderSession::write_render_tile, this, _1);
410         session->update_render_tile_cb = function_bind(&BlenderSession::update_render_tile, this, _1);
411
412         /* get buffer parameters */
413         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
414         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
415
416         /* render each layer */
417         BL::RenderSettings r = b_scene.render();
418         BL::RenderSettings::layers_iterator b_layer_iter;
419         BL::RenderResult::views_iterator b_view_iter;
420         
421         for(r.layers.begin(b_layer_iter); b_layer_iter != r.layers.end(); ++b_layer_iter) {
422                 b_rlay_name = b_layer_iter->name();
423
424                 /* temporary render result to find needed passes and views */
425                 BL::RenderResult b_rr = begin_render_result(b_engine, 0, 0, 1, 1, b_rlay_name.c_str(), NULL);
426                 BL::RenderResult::layers_iterator b_single_rlay;
427                 b_rr.layers.begin(b_single_rlay);
428
429                 /* layer will be missing if it was disabled in the UI */
430                 if(b_single_rlay == b_rr.layers.end()) {
431                         end_render_result(b_engine, b_rr, true, false);
432                         continue;
433                 }
434
435                 BL::RenderLayer b_rlay = *b_single_rlay;
436
437                 /* add passes */
438                 vector<Pass> passes;
439                 Pass::add(PASS_COMBINED, passes);
440 #ifdef WITH_CYCLES_DEBUG
441                 Pass::add(PASS_BVH_TRAVERSAL_STEPS, passes);
442 #endif
443
444                 if(session_params.device.advanced_shading) {
445
446                         /* loop over passes */
447                         BL::RenderLayer::passes_iterator b_pass_iter;
448
449                         for(b_rlay.passes.begin(b_pass_iter); b_pass_iter != b_rlay.passes.end(); ++b_pass_iter) {
450                                 BL::RenderPass b_pass(*b_pass_iter);
451                                 PassType pass_type = get_pass_type(b_pass);
452
453                                 if(pass_type == PASS_MOTION && scene->integrator->motion_blur)
454                                         continue;
455                                 if(pass_type != PASS_NONE)
456                                         Pass::add(pass_type, passes);
457                         }
458                 }
459
460                 buffer_params.passes = passes;
461                 scene->film->pass_alpha_threshold = b_layer_iter->pass_alpha_threshold();
462                 scene->film->tag_passes_update(scene, passes);
463                 scene->film->tag_update(scene);
464                 scene->integrator->tag_update(scene);
465
466                 for(b_rr.views.begin(b_view_iter); b_view_iter != b_rr.views.end(); ++b_view_iter) {
467                         b_rview_name = b_view_iter->name();
468
469                         /* set the current view */
470                         b_engine.active_view_set(b_rview_name.c_str());
471
472                         /* update scene */
473                         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
474                         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state, b_rlay_name.c_str());
475
476                         /* update number of samples per layer */
477                         int samples = sync->get_layer_samples();
478                         bool bound_samples = sync->get_layer_bound_samples();
479
480                         if(samples != 0 && (!bound_samples || (samples < session_params.samples)))
481                                 session->reset(buffer_params, samples);
482                         else
483                                 session->reset(buffer_params, session_params.samples);
484
485                         /* render */
486                         session->start();
487                         session->wait();
488
489                         if(session->progress.get_cancel())
490                                 break;
491                 }
492
493                 /* free result without merging */
494                 end_render_result(b_engine, b_rr, true, false);
495
496                 if(session->progress.get_cancel())
497                         break;
498         }
499
500         /* clear callback */
501         session->write_render_tile_cb = function_null;
502         session->update_render_tile_cb = function_null;
503
504         /* free all memory used (host and device), so we wouldn't leave render
505          * engine with extra memory allocated
506          */
507
508         session->device_free();
509
510         delete sync;
511         sync = NULL;
512 }
513
514 static void populate_bake_data(BakeData *data, BL::BakePixel pixel_array, const int num_pixels)
515 {
516         BL::BakePixel bp = pixel_array;
517
518         int i;
519         for(i=0; i < num_pixels; i++) {
520                 data->set(i, bp.primitive_id(), bp.uv(), bp.du_dx(), bp.du_dy(), bp.dv_dx(), bp.dv_dy());
521                 bp = bp.next();
522         }
523 }
524
525 void BlenderSession::bake(BL::Object b_object, const string& pass_type, BL::BakePixel pixel_array, const size_t num_pixels, const int /*depth*/, float result[])
526 {
527         ShaderEvalType shader_type = get_shader_type(pass_type);
528         size_t object_index = OBJECT_NONE;
529         int tri_offset = 0;
530
531         /* ensure kernels are loaded before we do any scene updates */
532         session->load_kernels();
533
534         if(session->progress.get_cancel())
535                 return;
536
537         if(shader_type == SHADER_EVAL_UV) {
538                 /* force UV to be available */
539                 Pass::add(PASS_UV, scene->film->passes);
540         }
541
542         if(BakeManager::is_light_pass(shader_type)) {
543                 /* force use_light_pass to be true */
544                 Pass::add(PASS_LIGHT, scene->film->passes);
545         }
546
547         /* create device and update scene */
548         scene->film->tag_update(scene);
549         scene->integrator->tag_update(scene);
550
551         /* update scene */
552         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
553         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
554
555         /* get buffer parameters */
556         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
557         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
558
559         scene->bake_manager->set_shader_limit((size_t)b_engine.tile_x(), (size_t)b_engine.tile_y());
560         scene->bake_manager->set_baking(true);
561
562         /* set number of samples */
563         session->tile_manager.set_samples(session_params.samples);
564         session->reset(buffer_params, session_params.samples);
565         session->update_scene();
566
567         /* find object index. todo: is arbitrary - copied from mesh_displace.cpp */
568         for(size_t i = 0; i < scene->objects.size(); i++) {
569                 if(strcmp(scene->objects[i]->name.c_str(), b_object.name().c_str()) == 0) {
570                         object_index = i;
571                         tri_offset = scene->objects[i]->mesh->tri_offset;
572                         break;
573                 }
574         }
575
576         /* when used, non-instanced convention: object = ~object */
577         int object = ~object_index;
578
579         BakeData *bake_data = scene->bake_manager->init(object, tri_offset, num_pixels);
580
581         populate_bake_data(bake_data, pixel_array, num_pixels);
582
583         /* set number of samples */
584         session->tile_manager.set_samples(session_params.samples);
585         session->reset(buffer_params, session_params.samples);
586         session->update_scene();
587
588         session->progress.set_update_callback(function_bind(&BlenderSession::update_bake_progress, this));
589
590         scene->bake_manager->bake(scene->device, &scene->dscene, scene, session->progress, shader_type, bake_data, result);
591
592         /* free all memory used (host and device), so we wouldn't leave render
593          * engine with extra memory allocated
594          */
595
596         session->device_free();
597
598         delete sync;
599         sync = NULL;
600 }
601
602 void BlenderSession::do_write_update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile, bool do_update_only)
603 {
604         RenderBuffers *buffers = rtile.buffers;
605
606         /* copy data from device */
607         if(!buffers->copy_from_device())
608                 return;
609
610         BufferParams& params = buffers->params;
611         float exposure = scene->film->exposure;
612
613         vector<float> pixels(params.width*params.height*4);
614
615         if(!do_update_only) {
616                 /* copy each pass */
617                 BL::RenderLayer::passes_iterator b_iter;
618
619                 for(b_rlay.passes.begin(b_iter); b_iter != b_rlay.passes.end(); ++b_iter) {
620                         BL::RenderPass b_pass(*b_iter);
621
622                         /* find matching pass type */
623                         PassType pass_type = get_pass_type(b_pass);
624                         int components = b_pass.channels();
625
626                         /* copy pixels */
627                         if(!buffers->get_pass_rect(pass_type, exposure, rtile.sample, components, &pixels[0]))
628                                 memset(&pixels[0], 0, pixels.size()*sizeof(float));
629
630                         b_pass.rect(&pixels[0]);
631                 }
632         }
633         else {
634                 /* copy combined pass */
635                  BL::RenderPass b_combined_pass(b_rlay.passes.find_by_type(BL::RenderPass::type_COMBINED, b_rview_name.c_str()));
636                 if(buffers->get_pass_rect(PASS_COMBINED, exposure, rtile.sample, 4, &pixels[0]))
637                         b_combined_pass.rect(&pixels[0]);
638         }
639
640         /* tag result as updated */
641         b_engine.update_result(b_rr);
642 }
643
644 void BlenderSession::write_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
645 {
646         do_write_update_render_result(b_rr, b_rlay, rtile, false);
647 }
648
649 void BlenderSession::update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
650 {
651         do_write_update_render_result(b_rr, b_rlay, rtile, true);
652 }
653
654 void BlenderSession::synchronize()
655 {
656         /* only used for viewport render */
657         if(!b_v3d)
658                 return;
659
660         /* on session/scene parameter changes, we recreate session entirely */
661         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
662         const bool is_cpu = session_params.device.type == DEVICE_CPU;
663         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background, is_cpu);
664         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
665
666         if(session->params.modified(session_params) ||
667            scene->params.modified(scene_params))
668         {
669                 free_session();
670                 create_session();
671                 session->start();
672                 return;
673         }
674
675         /* increase samples, but never decrease */
676         session->set_samples(session_params.samples);
677         session->set_pause(session_pause);
678
679         /* copy recalc flags, outside of mutex so we can decide to do the real
680          * synchronization at a later time to not block on running updates */
681         sync->sync_recalc();
682
683         /* don't do synchronization if on pause */
684         if(session_pause) {
685                 tag_update();
686                 return;
687         }
688
689         /* try to acquire mutex. if we don't want to or can't, come back later */
690         if(!session->ready_to_reset() || !session->scene->mutex.try_lock()) {
691                 tag_update();
692                 return;
693         }
694
695         /* data and camera synchronize */
696         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
697
698         if(b_rv3d)
699                 sync->sync_view(b_v3d, b_rv3d, width, height);
700         else
701                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
702
703         /* unlock */
704         session->scene->mutex.unlock();
705
706         /* reset if needed */
707         if(scene->need_reset()) {
708                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
709                 session->reset(buffer_params, session_params.samples);
710
711                 /* reset time */
712                 start_resize_time = 0.0;
713         }
714 }
715
716 bool BlenderSession::draw(int w, int h)
717 {
718         /* pause in redraw in case update is not being called due to final render */
719         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
720
721         /* before drawing, we verify camera and viewport size changes, because
722          * we do not get update callbacks for those, we must detect them here */
723         if(session->ready_to_reset()) {
724                 bool reset = false;
725
726                 /* if dimensions changed, reset */
727                 if(width != w || height != h) {
728                         if(start_resize_time == 0.0) {
729                                 /* don't react immediately to resizes to avoid flickery resizing
730                                  * of the viewport, and some window managers changing the window
731                                  * size temporarily on unminimize */
732                                 start_resize_time = time_dt();
733                                 tag_redraw();
734                         }
735                         else if(time_dt() - start_resize_time < 0.2) {
736                                 tag_redraw();
737                         }
738                         else {
739                                 width = w;
740                                 height = h;
741                                 reset = true;
742                         }
743                 }
744
745                 /* try to acquire mutex. if we can't, come back later */
746                 if(!session->scene->mutex.try_lock()) {
747                         tag_update();
748                 }
749                 else {
750                         /* update camera from 3d view */
751
752                         sync->sync_view(b_v3d, b_rv3d, width, height);
753
754                         if(scene->camera->need_update)
755                                 reset = true;
756
757                         session->scene->mutex.unlock();
758                 }
759
760                 /* reset if requested */
761                 if(reset) {
762                         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
763                         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
764                         bool session_pause = BlenderSync::get_session_pause(b_scene, background);
765
766                         if(session_pause == false) {
767                                 session->reset(buffer_params, session_params.samples);
768                                 start_resize_time = 0.0;
769                         }
770                 }
771         }
772         else {
773                 tag_update();
774         }
775
776         /* update status and progress for 3d view draw */
777         update_status_progress();
778
779         /* draw */
780         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_v3d, b_rv3d, scene->camera, width, height);
781         DeviceDrawParams draw_params;
782
783         if(session->params.display_buffer_linear) {
784                 draw_params.bind_display_space_shader_cb = function_bind(&BL::RenderEngine::bind_display_space_shader, &b_engine, b_scene);
785                 draw_params.unbind_display_space_shader_cb = function_bind(&BL::RenderEngine::unbind_display_space_shader, &b_engine);
786         }
787
788         return !session->draw(buffer_params, draw_params);
789 }
790
791 void BlenderSession::get_status(string& status, string& substatus)
792 {
793         session->progress.get_status(status, substatus);
794 }
795
796 void BlenderSession::get_progress(float& progress, double& total_time, double& render_time)
797 {
798         double tile_time;
799         int tile, sample, samples_per_tile;
800         int tile_total = session->tile_manager.state.num_tiles;
801         int samples = session->tile_manager.state.sample + 1;
802         int total_samples = session->tile_manager.num_samples;
803
804         session->progress.get_tile(tile, total_time, render_time, tile_time);
805
806         sample = session->progress.get_sample();
807         samples_per_tile = session->tile_manager.num_samples;
808
809         if(background && samples_per_tile && tile_total)
810                 progress = ((float)sample / (float)(tile_total * samples_per_tile));
811         else if(!background && samples > 0 && total_samples != USHRT_MAX)
812                 progress = ((float)samples) / total_samples;
813         else
814                 progress = 0.0;
815 }
816
817 void BlenderSession::update_bake_progress()
818 {
819         float progress;
820         int sample, samples_per_task, parts_total;
821
822         sample = session->progress.get_sample();
823         samples_per_task = scene->bake_manager->num_samples;
824         parts_total = scene->bake_manager->num_parts;
825
826         if(samples_per_task)
827                 progress = ((float)sample / (float)(parts_total * samples_per_task));
828         else
829                 progress = 0.0;
830
831         if(progress != last_progress) {
832                 b_engine.update_progress(progress);
833                 last_progress = progress;
834         }
835 }
836
837 void BlenderSession::update_status_progress()
838 {
839         string timestatus, status, substatus;
840         string scene = "";
841         float progress;
842         double total_time, remaining_time = 0, render_time;
843         char time_str[128];
844         float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
845         float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
846
847         get_status(status, substatus);
848         get_progress(progress, total_time, render_time);
849
850         if(progress > 0)
851                 remaining_time = (1.0 - (double)progress) * (render_time / (double)progress);
852
853         if(background) {
854                 scene += " | " + b_scene.name();
855                 if(b_rlay_name != "")
856                         scene += ", "  + b_rlay_name;
857
858                 if(b_rview_name != "")
859                         scene += ", " + b_rview_name;
860         }
861         else {
862                 BLI_timestr(total_time, time_str, sizeof(time_str));
863                 timestatus = "Time:" + string(time_str) + " | ";
864         }
865
866         if(remaining_time > 0) {
867                 BLI_timestr(remaining_time, time_str, sizeof(time_str));
868                 timestatus += "Remaining:" + string(time_str) + " | ";
869         }
870
871         timestatus += string_printf("Mem:%.2fM, Peak:%.2fM", (double)mem_used, (double)mem_peak);
872
873         if(status.size() > 0)
874                 status = " | " + status;
875         if(substatus.size() > 0)
876                 status += " | " + substatus;
877
878         if(status != last_status) {
879                 b_engine.update_stats("", (timestatus + scene + status).c_str());
880                 b_engine.update_memory_stats(mem_used, mem_peak);
881                 last_status = status;
882         }
883         if(progress != last_progress) {
884                 b_engine.update_progress(progress);
885                 last_progress = progress;
886         }
887
888         if(session->progress.get_error()) {
889                 string error = session->progress.get_error_message();
890                 if(error != last_error) {
891                         /* TODO(sergey): Currently C++ RNA API doesn't let us to
892                          * use mnemonic name for the variable. Would be nice to
893                          * have this figured out.
894                          *
895                          * For until then, 1 << 5 means RPT_ERROR.
896                          */
897                         b_engine.report(1 << 5, error.c_str());
898                         b_engine.error_set(error.c_str());
899                         last_error = error;
900                 }
901         }
902 }
903
904 void BlenderSession::tag_update()
905 {
906         /* tell blender that we want to get another update callback */
907         b_engine.tag_update();
908 }
909
910 void BlenderSession::tag_redraw()
911 {
912         if(background) {
913                 /* update stats and progress, only for background here because
914                  * in 3d view we do it in draw for thread safety reasons */
915                 update_status_progress();
916
917                 /* offline render, redraw if timeout passed */
918                 if(time_dt() - last_redraw_time > 1.0) {
919                         b_engine.tag_redraw();
920                         last_redraw_time = time_dt();
921                 }
922         }
923         else {
924                 /* tell blender that we want to redraw */
925                 b_engine.tag_redraw();
926         }
927 }
928
929 void BlenderSession::test_cancel()
930 {
931         /* test if we need to cancel rendering */
932         if(background)
933                 if(b_engine.test_break())
934                         session->progress.set_cancel("Cancelled");
935 }
936
937 /* builtin image file name is actually an image datablock name with
938  * absolute sequence frame number concatenated via '@' character
939  *
940  * this function splits frame from builtin name
941  */
942 int BlenderSession::builtin_image_frame(const string &builtin_name)
943 {
944         int last = builtin_name.find_last_of('@');
945         return atoi(builtin_name.substr(last + 1, builtin_name.size() - last - 1).c_str());
946 }
947
948 void BlenderSession::builtin_image_info(const string &builtin_name, void *builtin_data, bool &is_float, int &width, int &height, int &depth, int &channels)
949 {
950         /* empty image */
951         is_float = false;
952         width = 0;
953         height = 0;
954         depth = 0;
955         channels = 0;
956
957         if(!builtin_data)
958                 return;
959
960         /* recover ID pointer */
961         PointerRNA ptr;
962         RNA_id_pointer_create((ID*)builtin_data, &ptr);
963         BL::ID b_id(ptr);
964
965         if(b_id.is_a(&RNA_Image)) {
966                 /* image data */
967                 BL::Image b_image(b_id);
968
969                 is_float = b_image.is_float();
970                 width = b_image.size()[0];
971                 height = b_image.size()[1];
972                 depth = 1;
973                 channels = b_image.channels();
974         }
975         else if(b_id.is_a(&RNA_Object)) {
976                 /* smoke volume data */
977                 BL::Object b_ob(b_id);
978                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
979
980                 if(!b_domain)
981                         return;
982
983                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY) ||
984                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME))
985                         channels = 1;
986                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR))
987                         channels = 4;
988                 else
989                         return;
990
991                 int3 resolution = get_int3(b_domain.domain_resolution());
992                 int amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
993
994                 width = resolution.x * amplify;
995                 height = resolution.y * amplify;
996                 depth = resolution.z * amplify;
997
998                 is_float = true;
999         }
1000 }
1001
1002 bool BlenderSession::builtin_image_pixels(const string &builtin_name, void *builtin_data, unsigned char *pixels)
1003 {
1004         if(!builtin_data)
1005                 return false;
1006
1007         int frame = builtin_image_frame(builtin_name);
1008
1009         PointerRNA ptr;
1010         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1011         BL::Image b_image(ptr);
1012
1013         int width = b_image.size()[0];
1014         int height = b_image.size()[1];
1015         int channels = b_image.channels();
1016
1017         unsigned char *image_pixels;
1018         image_pixels = image_get_pixels_for_frame(b_image, frame);
1019
1020         if(image_pixels) {
1021                 memcpy(pixels, image_pixels, width * height * channels * sizeof(unsigned char));
1022                 MEM_freeN(image_pixels);
1023         }
1024         else {
1025                 if(channels == 1) {
1026                         memset(pixels, 0, width * height * sizeof(unsigned char));
1027                 }
1028                 else {
1029                         unsigned char *cp = pixels;
1030                         for(int i = 0; i < width * height; i++, cp += channels) {
1031                                 cp[0] = 255;
1032                                 cp[1] = 0;
1033                                 cp[2] = 255;
1034                                 if(channels == 4)
1035                                         cp[3] = 255;
1036                         }
1037                 }
1038         }
1039
1040         /* premultiply, byte images are always straight for blender */
1041         unsigned char *cp = pixels;
1042         for(int i = 0; i < width * height; i++, cp += channels) {
1043                 cp[0] = (cp[0] * cp[3]) >> 8;
1044                 cp[1] = (cp[1] * cp[3]) >> 8;
1045                 cp[2] = (cp[2] * cp[3]) >> 8;
1046         }
1047
1048         return true;
1049 }
1050
1051 bool BlenderSession::builtin_image_float_pixels(const string &builtin_name, void *builtin_data, float *pixels)
1052 {
1053         if(!builtin_data)
1054                 return false;
1055
1056         PointerRNA ptr;
1057         RNA_id_pointer_create((ID*)builtin_data, &ptr);
1058         BL::ID b_id(ptr);
1059
1060         if(b_id.is_a(&RNA_Image)) {
1061                 /* image data */
1062                 BL::Image b_image(b_id);
1063                 int frame = builtin_image_frame(builtin_name);
1064
1065                 int width = b_image.size()[0];
1066                 int height = b_image.size()[1];
1067                 int channels = b_image.channels();
1068
1069                 float *image_pixels;
1070                 image_pixels = image_get_float_pixels_for_frame(b_image, frame);
1071
1072                 if(image_pixels) {
1073                         memcpy(pixels, image_pixels, width * height * channels * sizeof(float));
1074                         MEM_freeN(image_pixels);
1075                 }
1076                 else {
1077                         if(channels == 1) {
1078                                 memset(pixels, 0, width * height * sizeof(float));
1079                         }
1080                         else {
1081                                 float *fp = pixels;
1082                                 for(int i = 0; i < width * height; i++, fp += channels) {
1083                                         fp[0] = 1.0f;
1084                                         fp[1] = 0.0f;
1085                                         fp[2] = 1.0f;
1086                                         if(channels == 4)
1087                                                 fp[3] = 1.0f;
1088                                 }
1089                         }
1090                 }
1091
1092                 return true;
1093         }
1094         else if(b_id.is_a(&RNA_Object)) {
1095                 /* smoke volume data */
1096                 BL::Object b_ob(b_id);
1097                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
1098
1099                 if(!b_domain)
1100                         return false;
1101
1102                 int3 resolution = get_int3(b_domain.domain_resolution());
1103                 int length, amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
1104
1105                 int width = resolution.x * amplify;
1106                 int height = resolution.y * amplify;
1107                 int depth = resolution.z * amplify;
1108
1109                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY)) {
1110                         SmokeDomainSettings_density_grid_get_length(&b_domain.ptr, &length);
1111
1112                         if(length == width*height*depth) {
1113                                 SmokeDomainSettings_density_grid_get(&b_domain.ptr, pixels);
1114                                 return true;
1115                         }
1116                 }
1117                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME)) {
1118                         /* this is in range 0..1, and interpreted by the OpenGL smoke viewer
1119                          * as 1500..3000 K with the first part faded to zero density */
1120                         SmokeDomainSettings_flame_grid_get_length(&b_domain.ptr, &length);
1121
1122                         if(length == width*height*depth) {
1123                                 SmokeDomainSettings_flame_grid_get(&b_domain.ptr, pixels);
1124                                 return true;
1125                         }
1126                 }
1127                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR)) {
1128                         /* the RGB is "premultiplied" by density for better interpolation results */
1129                         SmokeDomainSettings_color_grid_get_length(&b_domain.ptr, &length);
1130
1131                         if(length == width*height*depth*4) {
1132                                 SmokeDomainSettings_color_grid_get(&b_domain.ptr, pixels);
1133                                 return true;
1134                         }
1135                 }
1136
1137                 fprintf(stderr, "Cycles error: unexpected smoke volume resolution, skipping\n");
1138         }
1139
1140         return false;
1141 }
1142
1143 CCL_NAMESPACE_END
1144