Cycles: add "density", "flame" and "color" attributes for smoke domains.
[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 "background.h"
18 #include "buffers.h"
19 #include "camera.h"
20 #include "device.h"
21 #include "integrator.h"
22 #include "film.h"
23 #include "light.h"
24 #include "scene.h"
25 #include "session.h"
26 #include "shader.h"
27
28 #include "util_color.h"
29 #include "util_foreach.h"
30 #include "util_function.h"
31 #include "util_progress.h"
32 #include "util_time.h"
33
34 #include "blender_sync.h"
35 #include "blender_session.h"
36 #include "blender_util.h"
37
38 CCL_NAMESPACE_BEGIN
39
40 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
41         BL::BlendData b_data_, BL::Scene b_scene_)
42 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_engine_.render()), b_scene(b_scene_),
43   b_v3d(PointerRNA_NULL), b_rv3d(PointerRNA_NULL), python_thread_state(NULL)
44 {
45         /* offline render */
46
47         width = render_resolution_x(b_render);
48         height = render_resolution_y(b_render);
49
50         background = true;
51         last_redraw_time = 0.0;
52         start_resize_time = 0.0;
53 }
54
55 BlenderSession::BlenderSession(BL::RenderEngine b_engine_, BL::UserPreferences b_userpref_,
56         BL::BlendData b_data_, BL::Scene b_scene_,
57         BL::SpaceView3D b_v3d_, BL::RegionView3D b_rv3d_, int width_, int height_)
58 : b_engine(b_engine_), b_userpref(b_userpref_), b_data(b_data_), b_render(b_scene_.render()), b_scene(b_scene_),
59   b_v3d(b_v3d_), b_rv3d(b_rv3d_), python_thread_state(NULL)
60 {
61         /* 3d view render */
62
63         width = width_;
64         height = height_;
65         background = false;
66         last_redraw_time = 0.0;
67         start_resize_time = 0.0;
68 }
69
70 BlenderSession::~BlenderSession()
71 {
72         free_session();
73 }
74
75 void BlenderSession::create()
76 {
77         create_session();
78
79         if(b_v3d)
80                 session->start();
81 }
82
83 void BlenderSession::create_session()
84 {
85         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
86         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
87
88         /* reset status/progress */
89         last_status = "";
90         last_progress = -1.0f;
91         start_resize_time = 0.0;
92
93         /* create scene */
94         scene = new Scene(scene_params, session_params.device);
95
96         /* setup callbacks for builtin image support */
97         scene->image_manager->builtin_image_info_cb = function_bind(&BlenderSession::builtin_image_info, this, _1, _2, _3, _4, _5, _6, _7);
98         scene->image_manager->builtin_image_pixels_cb = function_bind(&BlenderSession::builtin_image_pixels, this, _1, _2, _3);
99         scene->image_manager->builtin_image_float_pixels_cb = function_bind(&BlenderSession::builtin_image_float_pixels, this, _1, _2, _3);
100
101         /* create session */
102         session = new Session(session_params);
103         session->scene = scene;
104         session->progress.set_update_callback(function_bind(&BlenderSession::tag_redraw, this));
105         session->progress.set_cancel_callback(function_bind(&BlenderSession::test_cancel, this));
106         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
107
108         /* create sync */
109         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, session_params.device.type == DEVICE_CPU);
110
111         if(b_v3d) {
112                 /* full data sync */
113                 sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
114                 sync->sync_view(b_v3d, b_rv3d, width, height);
115         }
116         else {
117                 /* for final render we will do full data sync per render layer, only
118                  * do some basic syncing here, no objects or materials for speed */
119                 sync->sync_render_layers(b_v3d, NULL);
120                 sync->sync_integrator();
121                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
122         }
123
124         /* set buffer parameters */
125         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
126         session->reset(buffer_params, session_params.samples);
127
128         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
129 }
130
131 void BlenderSession::reset_session(BL::BlendData b_data_, BL::Scene b_scene_)
132 {
133         b_data = b_data_;
134         b_render = b_engine.render();
135         b_scene = b_scene_;
136
137         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
138         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
139
140         width = render_resolution_x(b_render);
141         height = render_resolution_y(b_render);
142
143         if(scene->params.modified(scene_params) ||
144            session->params.modified(session_params) ||
145            !scene_params.persistent_data)
146         {
147                 /* if scene or session parameters changed, it's easier to simply re-create
148                  * them rather than trying to distinguish which settings need to be updated
149                  */
150
151                 delete session;
152
153                 create_session();
154
155                 return;
156         }
157
158         session->progress.reset();
159         scene->reset();
160
161         session->tile_manager.set_tile_order(session_params.tile_order);
162
163         /* peak memory usage should show current render peak, not peak for all renders
164          * made by this render session
165          */
166         session->stats.mem_peak = session->stats.mem_used;
167
168         /* sync object should be re-created */
169         sync = new BlenderSync(b_engine, b_data, b_scene, scene, !background, session->progress, session_params.device.type == DEVICE_CPU);
170
171         /* for final render we will do full data sync per render layer, only
172          * do some basic syncing here, no objects or materials for speed */
173         sync->sync_render_layers(b_v3d, NULL);
174         sync->sync_integrator();
175         sync->sync_camera(b_render, b_engine.camera_override(), width, height);
176
177         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, PointerRNA_NULL, PointerRNA_NULL, scene->camera, width, height);
178         session->reset(buffer_params, session_params.samples);
179
180         b_engine.use_highlight_tiles(session_params.progressive_refine == false);
181
182         /* reset time */
183         start_resize_time = 0.0;
184 }
185
186 void BlenderSession::free_session()
187 {
188         if(sync)
189                 delete sync;
190
191         delete session;
192 }
193
194 static PassType get_pass_type(BL::RenderPass b_pass)
195 {
196         switch(b_pass.type()) {
197                 case BL::RenderPass::type_COMBINED:
198                         return PASS_COMBINED;
199
200                 case BL::RenderPass::type_Z:
201                         return PASS_DEPTH;
202                 case BL::RenderPass::type_MIST:
203                         return PASS_MIST;
204                 case BL::RenderPass::type_NORMAL:
205                         return PASS_NORMAL;
206                 case BL::RenderPass::type_OBJECT_INDEX:
207                         return PASS_OBJECT_ID;
208                 case BL::RenderPass::type_UV:
209                         return PASS_UV;
210                 case BL::RenderPass::type_VECTOR:
211                         return PASS_MOTION;
212                 case BL::RenderPass::type_MATERIAL_INDEX:
213                         return PASS_MATERIAL_ID;
214
215                 case BL::RenderPass::type_DIFFUSE_DIRECT:
216                         return PASS_DIFFUSE_DIRECT;
217                 case BL::RenderPass::type_GLOSSY_DIRECT:
218                         return PASS_GLOSSY_DIRECT;
219                 case BL::RenderPass::type_TRANSMISSION_DIRECT:
220                         return PASS_TRANSMISSION_DIRECT;
221                 case BL::RenderPass::type_SUBSURFACE_DIRECT:
222                         return PASS_SUBSURFACE_DIRECT;
223
224                 case BL::RenderPass::type_DIFFUSE_INDIRECT:
225                         return PASS_DIFFUSE_INDIRECT;
226                 case BL::RenderPass::type_GLOSSY_INDIRECT:
227                         return PASS_GLOSSY_INDIRECT;
228                 case BL::RenderPass::type_TRANSMISSION_INDIRECT:
229                         return PASS_TRANSMISSION_INDIRECT;
230                 case BL::RenderPass::type_SUBSURFACE_INDIRECT:
231                         return PASS_SUBSURFACE_INDIRECT;
232
233                 case BL::RenderPass::type_DIFFUSE_COLOR:
234                         return PASS_DIFFUSE_COLOR;
235                 case BL::RenderPass::type_GLOSSY_COLOR:
236                         return PASS_GLOSSY_COLOR;
237                 case BL::RenderPass::type_TRANSMISSION_COLOR:
238                         return PASS_TRANSMISSION_COLOR;
239                 case BL::RenderPass::type_SUBSURFACE_COLOR:
240                         return PASS_SUBSURFACE_COLOR;
241
242                 case BL::RenderPass::type_EMIT:
243                         return PASS_EMISSION;
244                 case BL::RenderPass::type_ENVIRONMENT:
245                         return PASS_BACKGROUND;
246                 case BL::RenderPass::type_AO:
247                         return PASS_AO;
248                 case BL::RenderPass::type_SHADOW:
249                         return PASS_SHADOW;
250
251                 case BL::RenderPass::type_DIFFUSE:
252                 case BL::RenderPass::type_COLOR:
253                 case BL::RenderPass::type_REFRACTION:
254                 case BL::RenderPass::type_SPECULAR:
255                 case BL::RenderPass::type_REFLECTION:
256                         return PASS_NONE;
257         }
258         
259         return PASS_NONE;
260 }
261
262 static BL::RenderResult begin_render_result(BL::RenderEngine b_engine, int x, int y, int w, int h, const char *layername)
263 {
264         return b_engine.begin_result(x, y, w, h, layername);
265 }
266
267 static void end_render_result(BL::RenderEngine b_engine, BL::RenderResult b_rr, bool cancel, bool do_merge_results)
268 {
269         b_engine.end_result(b_rr, (int)cancel, (int)do_merge_results);
270 }
271
272 void BlenderSession::do_write_update_render_tile(RenderTile& rtile, bool do_update_only)
273 {
274         BufferParams& params = rtile.buffers->params;
275         int x = params.full_x - session->tile_manager.params.full_x;
276         int y = params.full_y - session->tile_manager.params.full_y;
277         int w = params.width;
278         int h = params.height;
279
280         /* get render result */
281         BL::RenderResult b_rr = begin_render_result(b_engine, x, y, w, h, b_rlay_name.c_str());
282
283         /* can happen if the intersected rectangle gives 0 width or height */
284         if (b_rr.ptr.data == NULL) {
285                 return;
286         }
287
288         BL::RenderResult::layers_iterator b_single_rlay;
289         b_rr.layers.begin(b_single_rlay);
290
291         /* layer will be missing if it was disabled in the UI */
292         if(b_single_rlay == b_rr.layers.end())
293                 return;
294
295         BL::RenderLayer b_rlay = *b_single_rlay;
296
297         if (do_update_only) {
298                 /* update only needed */
299
300                 if (rtile.sample != 0) {
301                         /* sample would be zero at initial tile update, which is only needed
302                          * to tag tile form blender side as IN PROGRESS for proper highlight
303                          * no buffers should be sent to blender yet
304                          */
305                         update_render_result(b_rr, b_rlay, rtile);
306                 }
307
308                 end_render_result(b_engine, b_rr, true, true);
309         }
310         else {
311                 /* write result */
312                 write_render_result(b_rr, b_rlay, rtile);
313                 end_render_result(b_engine, b_rr, false, true);
314         }
315 }
316
317 void BlenderSession::write_render_tile(RenderTile& rtile)
318 {
319         do_write_update_render_tile(rtile, false);
320 }
321
322 void BlenderSession::update_render_tile(RenderTile& rtile)
323 {
324         /* use final write for preview renders, otherwise render result wouldn't be
325          * be updated in blender side
326          * would need to be investigated a bit further, but for now shall be fine
327          */
328         if (!b_engine.is_preview())
329                 do_write_update_render_tile(rtile, true);
330         else
331                 do_write_update_render_tile(rtile, false);
332 }
333
334 void BlenderSession::render()
335 {
336         /* set callback to write out render results */
337         session->write_render_tile_cb = function_bind(&BlenderSession::write_render_tile, this, _1);
338         session->update_render_tile_cb = function_bind(&BlenderSession::update_render_tile, this, _1);
339
340         /* get buffer parameters */
341         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
342         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
343
344         /* render each layer */
345         BL::RenderSettings r = b_scene.render();
346         BL::RenderSettings::layers_iterator b_iter;
347         
348         for(r.layers.begin(b_iter); b_iter != r.layers.end(); ++b_iter) {
349                 b_rlay_name = b_iter->name();
350
351                 /* temporary render result to find needed passes */
352                 BL::RenderResult b_rr = begin_render_result(b_engine, 0, 0, 1, 1, b_rlay_name.c_str());
353                 BL::RenderResult::layers_iterator b_single_rlay;
354                 b_rr.layers.begin(b_single_rlay);
355
356                 /* layer will be missing if it was disabled in the UI */
357                 if(b_single_rlay == b_rr.layers.end()) {
358                         end_render_result(b_engine, b_rr, true, false);
359                         continue;
360                 }
361
362                 BL::RenderLayer b_rlay = *b_single_rlay;
363
364                 /* add passes */
365                 vector<Pass> passes;
366                 Pass::add(PASS_COMBINED, passes);
367
368                 if(session_params.device.advanced_shading) {
369
370                         /* loop over passes */
371                         BL::RenderLayer::passes_iterator b_pass_iter;
372
373                         for(b_rlay.passes.begin(b_pass_iter); b_pass_iter != b_rlay.passes.end(); ++b_pass_iter) {
374                                 BL::RenderPass b_pass(*b_pass_iter);
375                                 PassType pass_type = get_pass_type(b_pass);
376
377                                 if(pass_type == PASS_MOTION && scene->integrator->motion_blur)
378                                         continue;
379                                 if(pass_type != PASS_NONE)
380                                         Pass::add(pass_type, passes);
381                         }
382                 }
383
384                 /* free result without merging */
385                 end_render_result(b_engine, b_rr, true, false);
386
387                 buffer_params.passes = passes;
388                 scene->film->pass_alpha_threshold = b_iter->pass_alpha_threshold();
389                 scene->film->tag_passes_update(scene, passes);
390                 scene->film->tag_update(scene);
391                 scene->integrator->tag_update(scene);
392
393                 /* update scene */
394                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
395                 sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state, b_rlay_name.c_str());
396
397                 /* update number of samples per layer */
398                 int samples = sync->get_layer_samples();
399                 bool bound_samples = sync->get_layer_bound_samples();
400
401                 if(samples != 0 && (!bound_samples || (samples < session_params.samples)))
402                         session->reset(buffer_params, samples);
403                 else
404                         session->reset(buffer_params, session_params.samples);
405
406                 /* render */
407                 session->start();
408                 session->wait();
409
410                 if(session->progress.get_cancel())
411                         break;
412         }
413
414         /* clear callback */
415         session->write_render_tile_cb = NULL;
416         session->update_render_tile_cb = NULL;
417
418         /* free all memory used (host and device), so we wouldn't leave render
419          * engine with extra memory allocated
420          */
421
422         session->device_free();
423
424         delete sync;
425         sync = NULL;
426 }
427
428 void BlenderSession::do_write_update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile, bool do_update_only)
429 {
430         RenderBuffers *buffers = rtile.buffers;
431
432         /* copy data from device */
433         if(!buffers->copy_from_device())
434                 return;
435
436         BufferParams& params = buffers->params;
437         float exposure = scene->film->exposure;
438
439         vector<float> pixels(params.width*params.height*4);
440
441         if (!do_update_only) {
442                 /* copy each pass */
443                 BL::RenderLayer::passes_iterator b_iter;
444
445                 for(b_rlay.passes.begin(b_iter); b_iter != b_rlay.passes.end(); ++b_iter) {
446                         BL::RenderPass b_pass(*b_iter);
447
448                         /* find matching pass type */
449                         PassType pass_type = get_pass_type(b_pass);
450                         int components = b_pass.channels();
451
452                         /* copy pixels */
453                         if(!buffers->get_pass_rect(pass_type, exposure, rtile.sample, components, &pixels[0]))
454                                 memset(&pixels[0], 0, pixels.size()*sizeof(float));
455
456                         b_pass.rect(&pixels[0]);
457                 }
458         }
459
460         /* copy combined pass */
461         if(buffers->get_pass_rect(PASS_COMBINED, exposure, rtile.sample, 4, &pixels[0]))
462                 b_rlay.rect(&pixels[0]);
463
464         /* tag result as updated */
465         b_engine.update_result(b_rr);
466 }
467
468 void BlenderSession::write_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
469 {
470         do_write_update_render_result(b_rr, b_rlay, rtile, false);
471 }
472
473 void BlenderSession::update_render_result(BL::RenderResult b_rr, BL::RenderLayer b_rlay, RenderTile& rtile)
474 {
475         do_write_update_render_result(b_rr, b_rlay, rtile, true);
476 }
477
478 void BlenderSession::synchronize()
479 {
480         /* only used for viewport render */
481         if(!b_v3d)
482                 return;
483
484         /* on session/scene parameter changes, we recreate session entirely */
485         SceneParams scene_params = BlenderSync::get_scene_params(b_scene, background);
486         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
487
488         if(session->params.modified(session_params) ||
489            scene->params.modified(scene_params))
490         {
491                 free_session();
492                 create_session();
493                 session->start();
494                 return;
495         }
496
497         /* increase samples, but never decrease */
498         session->set_samples(session_params.samples);
499         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
500
501         /* copy recalc flags, outside of mutex so we can decide to do the real
502          * synchronization at a later time to not block on running updates */
503         sync->sync_recalc();
504
505         /* try to acquire mutex. if we don't want to or can't, come back later */
506         if(!session->ready_to_reset() || !session->scene->mutex.try_lock()) {
507                 tag_update();
508                 return;
509         }
510
511         /* data and camera synchronize */
512         sync->sync_data(b_v3d, b_engine.camera_override(), &python_thread_state);
513
514         if(b_rv3d)
515                 sync->sync_view(b_v3d, b_rv3d, width, height);
516         else
517                 sync->sync_camera(b_render, b_engine.camera_override(), width, height);
518
519         /* unlock */
520         session->scene->mutex.unlock();
521
522         /* reset if needed */
523         if(scene->need_reset()) {
524                 BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
525                 session->reset(buffer_params, session_params.samples);
526
527                 /* reset time */
528                 start_resize_time = 0.0;
529         }
530 }
531
532 bool BlenderSession::draw(int w, int h)
533 {
534         /* pause in redraw in case update is not being called due to final render */
535         session->set_pause(BlenderSync::get_session_pause(b_scene, background));
536
537         /* before drawing, we verify camera and viewport size changes, because
538          * we do not get update callbacks for those, we must detect them here */
539         if(session->ready_to_reset()) {
540                 bool reset = false;
541
542                 /* if dimensions changed, reset */
543                 if(width != w || height != h) {
544                         if(start_resize_time == 0.0) {
545                                 /* don't react immediately to resizes to avoid flickery resizing
546                                  * of the viewport, and some window managers changing the window
547                                  * size temporarily on unminimize */
548                                 start_resize_time = time_dt();
549                                 tag_redraw();
550                         }
551                         else if(time_dt() - start_resize_time < 0.2) {
552                                 tag_redraw();
553                         }
554                         else {
555                                 width = w;
556                                 height = h;
557                                 reset = true;
558                         }
559                 }
560
561                 /* try to acquire mutex. if we can't, come back later */
562                 if(!session->scene->mutex.try_lock()) {
563                         tag_update();
564                 }
565                 else {
566                         /* update camera from 3d view */
567
568                         sync->sync_view(b_v3d, b_rv3d, width, height);
569
570                         if(scene->camera->need_update)
571                                 reset = true;
572
573                         session->scene->mutex.unlock();
574                 }
575
576                 /* reset if requested */
577                 if(reset) {
578                         SessionParams session_params = BlenderSync::get_session_params(b_engine, b_userpref, b_scene, background);
579                         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
580
581                         session->reset(buffer_params, session_params.samples);
582
583                         start_resize_time = 0.0;
584                 }
585         }
586         else {
587                 tag_update();
588         }
589
590         /* update status and progress for 3d view draw */
591         update_status_progress();
592
593         /* draw */
594         BufferParams buffer_params = BlenderSync::get_buffer_params(b_render, b_scene, b_v3d, b_rv3d, scene->camera, width, height);
595         DeviceDrawParams draw_params;
596
597         if(session->params.display_buffer_linear) {
598                 draw_params.bind_display_space_shader_cb = function_bind(&BL::RenderEngine::bind_display_space_shader, &b_engine, b_scene);
599                 draw_params.unbind_display_space_shader_cb = function_bind(&BL::RenderEngine::unbind_display_space_shader, &b_engine);
600         }
601
602         return !session->draw(buffer_params, draw_params);
603 }
604
605 void BlenderSession::get_status(string& status, string& substatus)
606 {
607         session->progress.get_status(status, substatus);
608 }
609
610 void BlenderSession::get_progress(float& progress, double& total_time)
611 {
612         double tile_time;
613         int tile, sample, samples_per_tile;
614         int tile_total = session->tile_manager.state.num_tiles;
615
616         session->progress.get_tile(tile, total_time, tile_time);
617
618         sample = session->progress.get_sample();
619         samples_per_tile = session->tile_manager.num_samples;
620
621         if(samples_per_tile && tile_total)
622                 progress = ((float)sample / (float)(tile_total * samples_per_tile));
623         else
624                 progress = 0.0;
625 }
626
627 void BlenderSession::update_status_progress()
628 {
629         string timestatus, status, substatus;
630         string scene = "";
631         float progress;
632         double total_time, remaining_time = 0;
633         char time_str[128];
634         float mem_used = (float)session->stats.mem_used / 1024.0f / 1024.0f;
635         float mem_peak = (float)session->stats.mem_peak / 1024.0f / 1024.0f;
636         int samples = session->tile_manager.state.sample + 1;
637         int total_samples = session->tile_manager.num_samples;
638
639         get_status(status, substatus);
640         get_progress(progress, total_time);
641
642         
643
644         if(background) {
645                 if(progress>0)
646                         remaining_time = (1-progress) * (total_time / progress);
647
648                 scene += " | " + b_scene.name();
649                 if(b_rlay_name != "")
650                         scene += ", "  + b_rlay_name;
651         }
652         else {
653                 BLI_timestr(total_time, time_str, sizeof(time_str));
654                 timestatus = "Time:" + string(time_str) + " | ";
655
656                 if(samples > 0 && total_samples != USHRT_MAX)
657                         remaining_time = (total_samples - samples) * (total_time / samples);
658         }
659         
660         if(remaining_time>0) {
661                 BLI_timestr(remaining_time, time_str, sizeof(time_str));
662                 timestatus += "Remaining:" + string(time_str) + " | ";
663         }
664         
665         timestatus += string_printf("Mem:%.2fM, Peak:%.2fM", mem_used, mem_peak);
666
667         if(status.size() > 0)
668                 status = " | " + status;
669         if(substatus.size() > 0)
670                 status += " | " + substatus;
671
672         if(status != last_status) {
673                 b_engine.update_stats("", (timestatus + scene + status).c_str());
674                 b_engine.update_memory_stats(mem_used, mem_peak);
675                 last_status = status;
676         }
677         if(progress != last_progress) {
678                 b_engine.update_progress(progress);
679                 last_progress = progress;
680         }
681 }
682
683 void BlenderSession::tag_update()
684 {
685         /* tell blender that we want to get another update callback */
686         b_engine.tag_update();
687 }
688
689 void BlenderSession::tag_redraw()
690 {
691         if(background) {
692                 /* update stats and progress, only for background here because
693                  * in 3d view we do it in draw for thread safety reasons */
694                 update_status_progress();
695
696                 /* offline render, redraw if timeout passed */
697                 if(time_dt() - last_redraw_time > 1.0) {
698                         b_engine.tag_redraw();
699                         last_redraw_time = time_dt();
700                 }
701         }
702         else {
703                 /* tell blender that we want to redraw */
704                 b_engine.tag_redraw();
705         }
706 }
707
708 void BlenderSession::test_cancel()
709 {
710         /* test if we need to cancel rendering */
711         if(background)
712                 if(b_engine.test_break())
713                         session->progress.set_cancel("Cancelled");
714 }
715
716 /* builtin image file name is actually an image datablock name with
717  * absolute sequence frame number concatenated via '@' character
718  *
719  * this function splits frame from builtin name
720  */
721 int BlenderSession::builtin_image_frame(const string &builtin_name)
722 {
723         int last = builtin_name.find_last_of('@');
724         return atoi(builtin_name.substr(last + 1, builtin_name.size() - last - 1).c_str());
725 }
726
727 void BlenderSession::builtin_image_info(const string &builtin_name, void *builtin_data, bool &is_float, int &width, int &height, int &depth, int &channels)
728 {
729         /* empty image */
730         is_float = false;
731         width = 0;
732         height = 0;
733         depth = 0;
734         channels = 0;
735
736         if(!builtin_data)
737                 return;
738
739         /* recover ID pointer */
740         PointerRNA ptr;
741         RNA_id_pointer_create((ID*)builtin_data, &ptr);
742         BL::ID b_id(ptr);
743
744         if(b_id.is_a(&RNA_Image)) {
745                 /* image data */
746                 BL::Image b_image(b_id);
747
748                 is_float = b_image.is_float();
749                 width = b_image.size()[0];
750                 height = b_image.size()[1];
751                 depth = 1;
752                 channels = b_image.channels();
753         }
754         else if(b_id.is_a(&RNA_Object)) {
755                 /* smoke volume data */
756                 BL::Object b_ob(b_id);
757                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
758
759                 if(!b_domain)
760                         return;
761
762                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY) ||
763                    builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME))
764                         channels = 1;
765                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR))
766                         channels = 4;
767                 else
768                         return;
769
770                 int3 resolution = get_int3(b_domain.domain_resolution());
771                 int amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
772
773                 width = resolution.x * amplify;
774                 height = resolution.y * amplify;
775                 depth = resolution.z * amplify;
776
777                 is_float = true;
778         }
779 }
780
781 bool BlenderSession::builtin_image_pixels(const string &builtin_name, void *builtin_data, unsigned char *pixels)
782 {
783         if(!builtin_data)
784                 return false;
785
786         int frame = builtin_image_frame(builtin_name);
787
788         PointerRNA ptr;
789         RNA_id_pointer_create((ID*)builtin_data, &ptr);
790         BL::Image b_image(ptr);
791
792         int width = b_image.size()[0];
793         int height = b_image.size()[1];
794         int channels = b_image.channels();
795
796         unsigned char *image_pixels;
797         image_pixels = image_get_pixels_for_frame(b_image, frame);
798
799         if(image_pixels) {
800                 memcpy(pixels, image_pixels, width * height * channels * sizeof(unsigned char));
801                 MEM_freeN(image_pixels);
802         }
803         else {
804                 if(channels == 1) {
805                         memset(pixels, 0, width * height * sizeof(unsigned char));
806                 }
807                 else {
808                         unsigned char *cp = pixels;
809                         for(int i = 0; i < width * height; i++, cp += channels) {
810                                 cp[0] = 255;
811                                 cp[1] = 0;
812                                 cp[2] = 255;
813                                 if(channels == 4)
814                                         cp[3] = 255;
815                         }
816                 }
817         }
818
819         /* premultiply, byte images are always straight for blender */
820         unsigned char *cp = pixels;
821         for(int i = 0; i < width * height; i++, cp += channels) {
822                 cp[0] = (cp[0] * cp[3]) >> 8;
823                 cp[1] = (cp[1] * cp[3]) >> 8;
824                 cp[2] = (cp[2] * cp[3]) >> 8;
825         }
826
827         return true;
828 }
829
830 bool BlenderSession::builtin_image_float_pixels(const string &builtin_name, void *builtin_data, float *pixels)
831 {
832         if(!builtin_data)
833                 return false;
834
835         PointerRNA ptr;
836         RNA_id_pointer_create((ID*)builtin_data, &ptr);
837         BL::ID b_id(ptr);
838
839         if(b_id.is_a(&RNA_Image)) {
840                 /* image data */
841                 BL::Image b_image(b_id);
842                 int frame = builtin_image_frame(builtin_name);
843
844                 int width = b_image.size()[0];
845                 int height = b_image.size()[1];
846                 int channels = b_image.channels();
847
848                 float *image_pixels;
849                 image_pixels = image_get_float_pixels_for_frame(b_image, frame);
850
851                 if(image_pixels) {
852                         memcpy(pixels, image_pixels, width * height * channels * sizeof(float));
853                         MEM_freeN(image_pixels);
854                 }
855                 else {
856                         if(channels == 1) {
857                                 memset(pixels, 0, width * height * sizeof(float));
858                         }
859                         else {
860                                 float *fp = pixels;
861                                 for(int i = 0; i < width * height; i++, fp += channels) {
862                                         fp[0] = 1.0f;
863                                         fp[1] = 0.0f;
864                                         fp[2] = 1.0f;
865                                         if(channels == 4)
866                                                 fp[3] = 1.0f;
867                                 }
868                         }
869                 }
870
871                 return true;
872         }
873         else if(b_id.is_a(&RNA_Object)) {
874                 /* smoke volume data */
875                 BL::Object b_ob(b_id);
876                 BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
877
878                 if(!b_domain)
879                         return false;
880
881                 int3 resolution = get_int3(b_domain.domain_resolution());
882                 int length, amplify = (b_domain.use_high_resolution())? b_domain.amplify() + 1: 1;
883
884                 int width = resolution.x * amplify;
885                 int height = resolution.y * amplify;
886                 int depth = resolution.z * amplify;
887
888                 if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_DENSITY)) {
889                         SmokeDomainSettings_density_grid_get_length(&b_domain.ptr, &length);
890
891                         if(length == width*height*depth) {
892                                 SmokeDomainSettings_density_grid_get(&b_domain.ptr, pixels);
893                                 return true;
894                         }
895                 }
896                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_FLAME)) {
897                         /* this is in range 0..1, and interpreted by the OpenGL smoke viewer
898                          * as 1500..3000 K with the first part faded to zero density */
899                         SmokeDomainSettings_flame_grid_get_length(&b_domain.ptr, &length);
900
901                         if(length == width*height*depth) {
902                                 SmokeDomainSettings_flame_grid_get(&b_domain.ptr, pixels);
903                                 return true;
904                         }
905                 }
906                 else if(builtin_name == Attribute::standard_name(ATTR_STD_VOLUME_COLOR)) {
907                         /* the RGB is "premultiplied" by density for better interpolation results */
908                         SmokeDomainSettings_color_grid_get_length(&b_domain.ptr, &length);
909
910                         if(length == width*height*depth*4) {
911                                 SmokeDomainSettings_color_grid_get(&b_domain.ptr, pixels);
912                                 return true;
913                         }
914                 }
915
916                 fprintf(stderr, "Cycles error: unexpected smoke volume resolution, skipping\n");
917         }
918
919         return false;
920 }
921
922 CCL_NAMESPACE_END
923