Fixed render time regression in Blender Internal
[blender.git] / source / blender / render / intern / source / pipeline.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2006 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/render/intern/source/pipeline.c
29  *  \ingroup render
30  */
31
32 #include <math.h>
33 #include <limits.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stddef.h>
37
38 #include "DNA_group_types.h"
39 #include "DNA_image_types.h"
40 #include "DNA_node_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_sequence_types.h"
44 #include "DNA_userdef_types.h"
45
46 #include "MEM_guardedalloc.h"
47
48 #include "BLI_math.h"
49 #include "BLI_rect.h"
50 #include "BLI_listbase.h"
51 #include "BLI_string.h"
52 #include "BLI_path_util.h"
53 #include "BLI_fileops.h"
54 #include "BLI_threads.h"
55 #include "BLI_rand.h"
56 #include "BLI_callbacks.h"
57
58 #include "BKE_animsys.h"  /* <------ should this be here?, needed for sequencer update */
59 #include "BKE_camera.h"
60 #include "BKE_global.h"
61 #include "BKE_image.h"
62 #include "BKE_main.h"
63 #include "BKE_node.h"
64 #include "BKE_pointcache.h"
65 #include "BKE_report.h"
66 #include "BKE_scene.h"
67 #include "BKE_sequencer.h"
68 #include "BKE_writeavi.h"  /* <------ should be replaced once with generic movie module */
69
70 #include "PIL_time.h"
71 #include "IMB_colormanagement.h"
72 #include "IMB_imbuf.h"
73 #include "IMB_imbuf_types.h"
74
75 #include "RE_engine.h"
76 #include "RE_pipeline.h"
77
78 /* internal */
79 #include "render_result.h"
80 #include "render_types.h"
81 #include "renderpipeline.h"
82 #include "renderdatabase.h"
83 #include "rendercore.h"
84 #include "initrender.h"
85 #include "shadbuf.h"
86 #include "pixelblending.h"
87 #include "zbuf.h"
88
89 /* render flow
90  *
91  * 1) Initialize state
92  * - state data, tables
93  * - movie/image file init
94  * - everything that doesn't change during animation
95  *
96  * 2) Initialize data
97  * - camera, world, matrices
98  * - make render verts, faces, halos, strands
99  * - everything can change per frame/field
100  *
101  * 3) Render Processor
102  * - multiple layers
103  * - tiles, rect, baking
104  * - layers/tiles optionally to disk or directly in Render Result
105  *
106  * 4) Composite Render Result
107  * - also read external files etc
108  *
109  * 5) Image Files
110  * - save file or append in movie
111  *
112  */
113
114
115 /* ********* globals ******** */
116
117 /* here we store all renders */
118 static struct {
119         ListBase renderlist;
120
121         /* commandline thread override */
122         int threads;
123 } RenderGlobal = {{NULL, NULL}, -1}; 
124
125 /* hardcopy of current render, used while rendering for speed */
126 Render R;
127
128 /* ********* alloc and free ******** */
129
130 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override);
131
132 static volatile int g_break = 0;
133 static int thread_break(void *UNUSED(arg))
134 {
135         return g_break;
136 }
137
138 /* default callbacks, set in each new render */
139 static void result_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr)) {}
140 static void result_rcti_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect)) {}
141 static void stats_nothing(void *UNUSED(arg), RenderStats *UNUSED(rs)) {}
142 static void float_nothing(void *UNUSED(arg), float UNUSED(val)) {}
143 static int default_break(void *UNUSED(arg)) { return G.is_break == TRUE; }
144
145 static void stats_background(void *UNUSED(arg), RenderStats *rs)
146 {
147         uintptr_t mem_in_use, mmap_in_use, peak_memory;
148         float megs_used_memory, mmap_used_memory, megs_peak_memory;
149
150         mem_in_use = MEM_get_memory_in_use();
151         mmap_in_use = MEM_get_mapped_memory_in_use();
152         peak_memory = MEM_get_peak_memory();
153
154         megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
155         mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
156         megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
157
158         fprintf(stdout, "Fra:%d Mem:%.2fM (%.2fM, peak %.2fM) ", rs->cfra,
159                 megs_used_memory, mmap_used_memory, megs_peak_memory);
160
161         if (rs->curfield)
162                 fprintf(stdout, "Field %d ", rs->curfield);
163         if (rs->curblur)
164                 fprintf(stdout, "Blur %d ", rs->curblur);
165
166         if (rs->infostr) {
167                 fprintf(stdout, "| %s", rs->infostr);
168         }
169         else {
170                 if (rs->tothalo)
171                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", rs->scene_name, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
172                 else
173                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d La:%d", rs->scene_name, rs->totvert, rs->totface, rs->totlamp);
174         }
175
176         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
177
178         fputc('\n', stdout);
179         fflush(stdout);
180 }
181
182 void RE_FreeRenderResult(RenderResult *res)
183 {
184         render_result_free(res);
185 }
186
187 float *RE_RenderLayerGetPass(RenderLayer *rl, int passtype)
188 {
189         RenderPass *rpass;
190         
191         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
192                 if (rpass->passtype == passtype)
193                         return rpass->rect;
194         return NULL;
195 }
196
197 RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
198 {
199         if (rr == NULL) {
200                 return NULL;
201         }
202         else {
203                 return BLI_findstring(&rr->layers, name, offsetof(RenderLayer, name));
204         }
205 }
206
207 RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, int predivide, int rectx, int recty)
208 {
209         return render_result_new_from_exr(exrhandle, colorspace, predivide, rectx, recty);
210 }
211
212 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
213 {
214         RenderLayer *rl = BLI_findlink(&rr->layers, re->r.actlay);
215         
216         if (rl)
217                 return rl;
218         else 
219                 return rr->layers.first;
220 }
221
222 static int render_scene_needs_vector(Render *re)
223 {
224         SceneRenderLayer *srl;
225         
226         for (srl = re->scene->r.layers.first; srl; srl = srl->next)
227                 if (!(srl->layflag & SCE_LAY_DISABLE))
228                         if (srl->passflag & SCE_PASS_VECTOR)
229                                 return 1;
230
231         return 0;
232 }
233
234 /* *************************************************** */
235
236 Render *RE_GetRender(const char *name)
237 {
238         Render *re;
239
240         /* search for existing renders */
241         for (re = RenderGlobal.renderlist.first; re; re = re->next)
242                 if (strncmp(re->name, name, RE_MAXNAME) == 0)
243                         break;
244
245         return re;
246 }
247
248
249 /* if you want to know exactly what has been done */
250 RenderResult *RE_AcquireResultRead(Render *re)
251 {
252         if (re) {
253                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
254                 return re->result;
255         }
256
257         return NULL;
258 }
259
260 RenderResult *RE_AcquireResultWrite(Render *re)
261 {
262         if (re) {
263                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
264                 return re->result;
265         }
266
267         return NULL;
268 }
269
270 void RE_SwapResult(Render *re, RenderResult **rr)
271 {
272         /* for keeping render buffers */
273         if (re) {
274                 SWAP(RenderResult *, re->result, *rr);
275         }
276 }
277
278
279 void RE_ReleaseResult(Render *re)
280 {
281         if (re)
282                 BLI_rw_mutex_unlock(&re->resultmutex);
283 }
284
285 /* displist.c util.... */
286 Scene *RE_GetScene(Render *re)
287 {
288         if (re)
289                 return re->scene;
290         return NULL;
291 }
292
293 /* fill provided result struct with what's currently active or done */
294 void RE_AcquireResultImage(Render *re, RenderResult *rr)
295 {
296         memset(rr, 0, sizeof(RenderResult));
297
298         if (re) {
299                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
300
301                 if (re->result) {
302                         RenderLayer *rl;
303                         
304                         rr->rectx = re->result->rectx;
305                         rr->recty = re->result->recty;
306                         
307                         rr->rectf = re->result->rectf;
308                         rr->rectz = re->result->rectz;
309                         rr->rect32 = re->result->rect32;
310                         
311                         /* active layer */
312                         rl = render_get_active_layer(re, re->result);
313
314                         if (rl) {
315                                 if (rr->rectf == NULL)
316                                         rr->rectf = rl->rectf;
317                                 if (rr->rectz == NULL)
318                                         rr->rectz = RE_RenderLayerGetPass(rl, SCE_PASS_Z);
319                         }
320
321                         rr->have_combined = (re->result->rectf != NULL);
322                         rr->layers = re->result->layers;
323                 }
324         }
325 }
326
327 void RE_ReleaseResultImage(Render *re)
328 {
329         if (re)
330                 BLI_rw_mutex_unlock(&re->resultmutex);
331 }
332
333 /* caller is responsible for allocating rect in correct size! */
334 void RE_ResultGet32(Render *re, unsigned int *rect)
335 {
336         RenderResult rres;
337         
338         RE_AcquireResultImage(re, &rres);
339         render_result_rect_get_pixels(&rres, rect, re->rectx, re->recty, &re->scene->view_settings, &re->scene->display_settings);
340         RE_ReleaseResultImage(re);
341 }
342
343 RenderStats *RE_GetStats(Render *re)
344 {
345         return &re->i;
346 }
347
348 Render *RE_NewRender(const char *name)
349 {
350         Render *re;
351
352         /* only one render per name exists */
353         re = RE_GetRender(name);
354         if (re == NULL) {
355                 
356                 /* new render data struct */
357                 re = MEM_callocN(sizeof(Render), "new render");
358                 BLI_addtail(&RenderGlobal.renderlist, re);
359                 BLI_strncpy(re->name, name, RE_MAXNAME);
360                 BLI_rw_mutex_init(&re->resultmutex);
361         }
362         
363         RE_InitRenderCB(re);
364
365         /* init some variables */
366         re->ycor = 1.0f;
367         
368         return re;
369 }
370
371 /* called for new renders and when finishing rendering so
372  * we always have valid callbacks on a render */
373 void RE_InitRenderCB(Render *re)
374 {
375         /* set default empty callbacks */
376         re->display_init = result_nothing;
377         re->display_clear = result_nothing;
378         re->display_draw = result_rcti_nothing;
379         re->progress = float_nothing;
380         re->test_break = default_break;
381         if (G.background)
382                 re->stats_draw = stats_background;
383         else
384                 re->stats_draw = stats_nothing;
385         /* clear callback handles */
386         re->dih = re->dch = re->ddh = re->sdh = re->prh = re->tbh = NULL;
387 }
388
389 /* only call this while you know it will remove the link too */
390 void RE_FreeRender(Render *re)
391 {
392         if (re->engine)
393                 RE_engine_free(re->engine);
394
395         BLI_rw_mutex_end(&re->resultmutex);
396         
397         free_renderdata_tables(re);
398         free_sample_tables(re);
399         
400         render_result_free(re->result);
401         render_result_free(re->pushedresult);
402         
403         BLI_remlink(&RenderGlobal.renderlist, re);
404         MEM_freeN(re);
405 }
406
407 /* exit blender */
408 void RE_FreeAllRender(void)
409 {
410         while (RenderGlobal.renderlist.first) {
411                 RE_FreeRender(RenderGlobal.renderlist.first);
412         }
413 }
414
415 /* on file load, free all re */
416 void RE_FreeAllRenderResults(void)
417 {
418         Render *re;
419
420         for (re = RenderGlobal.renderlist.first; re; re = re->next) {
421                 render_result_free(re->result);
422                 render_result_free(re->pushedresult);
423
424                 re->result = NULL;
425                 re->pushedresult = NULL;
426         }
427 }
428
429 void RE_FreePersistentData(void)
430 {
431         Render *re;
432
433         /* render engines can be kept around for quick re-render, this clears all */
434         for (re = RenderGlobal.renderlist.first; re; re = re->next) {
435                 if (re->engine) {
436                         /* if engine is currently rendering, just tag it to be freed when render is finished */
437                         if (!(re->engine->flag & RE_ENGINE_RENDERING))
438                                 RE_engine_free(re->engine);
439
440                         re->engine = NULL;
441                 }
442         }
443 }
444
445 /* ********* initialize state ******** */
446
447
448 /* what doesn't change during entire render sequence */
449 /* disprect is optional, if NULL it assumes full window render */
450 void RE_InitState(Render *re, Render *source, RenderData *rd, SceneRenderLayer *srl, int winx, int winy, rcti *disprect)
451 {
452         re->ok = TRUE;   /* maybe flag */
453         
454         re->i.starttime = PIL_check_seconds_timer();
455         re->r = *rd;     /* hardcopy */
456         
457         re->winx = winx;
458         re->winy = winy;
459         if (disprect) {
460                 re->disprect = *disprect;
461                 re->rectx = BLI_rcti_size_x(disprect);
462                 re->recty = BLI_rcti_size_y(disprect);
463         }
464         else {
465                 re->disprect.xmin = re->disprect.ymin = 0;
466                 re->disprect.xmax = winx;
467                 re->disprect.ymax = winy;
468                 re->rectx = winx;
469                 re->recty = winy;
470         }
471         
472         if (re->rectx < 1 || re->recty < 1 || (BKE_imtype_is_movie(rd->im_format.imtype) &&
473                                                (re->rectx < 16 || re->recty < 16) ))
474         {
475                 BKE_report(re->reports, RPT_ERROR, "Image too small");
476                 re->ok = 0;
477                 return;
478         }
479
480         if ((re->r.mode & (R_OSA)) == 0)
481                 re->r.scemode &= ~R_FULL_SAMPLE;
482
483 #ifdef WITH_OPENEXR
484         if (re->r.scemode & R_FULL_SAMPLE)
485                 re->r.scemode |= R_EXR_TILE_FILE;   /* enable automatic */
486
487         /* Until use_border is made compatible with save_buffers/full_sample, render without the later instead of not rendering at all.*/
488         if (re->r.mode & R_BORDER) {
489                 re->r.scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
490         }
491
492 #else
493         /* can't do this without openexr support */
494         re->r.scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
495 #endif
496         
497         /* fullsample wants uniform osa levels */
498         if (source && (re->r.scemode & R_FULL_SAMPLE)) {
499                 /* but, if source has no full sample we disable it */
500                 if ((source->r.scemode & R_FULL_SAMPLE) == 0)
501                         re->r.scemode &= ~R_FULL_SAMPLE;
502                 else
503                         re->r.osa = re->osa = source->osa;
504         }
505         else {
506                 /* check state variables, osa? */
507                 if (re->r.mode & (R_OSA)) {
508                         re->osa = re->r.osa;
509                         if (re->osa > 16) re->osa = 16;
510                 }
511                 else re->osa = 0;
512         }
513         
514         if (srl) {
515                 int index = BLI_findindex(&re->r.layers, srl);
516                 if (index != -1) {
517                         re->r.actlay = index;
518                         re->r.scemode |= R_SINGLE_LAYER;
519                 }
520         }
521                 
522         /* always call, checks for gamma, gamma tables and jitter too */
523         make_sample_tables(re);
524         
525         /* if preview render, we try to keep old result */
526         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
527
528         if (re->r.scemode & R_PREVIEWBUTS) {
529                 if (re->result && re->result->rectx == re->rectx && re->result->recty == re->recty) {
530                         /* pass */
531                 }
532                 else {
533                         render_result_free(re->result);
534                         re->result = NULL;
535                 }
536         }
537         else {
538                 
539                 /* make empty render result, so display callbacks can initialize */
540                 render_result_free(re->result);
541                 re->result = MEM_callocN(sizeof(RenderResult), "new render result");
542                 re->result->rectx = re->rectx;
543                 re->result->recty = re->recty;
544         }
545
546         BLI_rw_mutex_unlock(&re->resultmutex);
547         
548         /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
549         re->clipcrop = 1.0f + 2.0f / (float)(re->winx > re->winy ? re->winy : re->winx);
550         
551         re->mblur_offs = re->field_offs = 0.f;
552         
553         RE_init_threadcount(re);
554 }
555
556 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
557 {
558         /* re->ok flag? */
559         
560         re->viewplane = *viewplane;
561         re->clipsta = clipsta;
562         re->clipend = clipend;
563         re->r.mode &= ~R_ORTHO;
564
565         perspective_m4(re->winmat,
566                        re->viewplane.xmin, re->viewplane.xmax,
567                        re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
568         
569 }
570
571 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
572 {
573         /* re->ok flag? */
574         
575         re->viewplane = *viewplane;
576         re->clipsta = clipsta;
577         re->clipend = clipend;
578         re->r.mode |= R_ORTHO;
579
580         orthographic_m4(re->winmat,
581                         re->viewplane.xmin, re->viewplane.xmax,
582                         re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
583 }
584
585 void RE_SetView(Render *re, float mat[4][4])
586 {
587         /* re->ok flag? */
588         copy_m4_m4(re->viewmat, mat);
589         invert_m4_m4(re->viewinv, re->viewmat);
590 }
591
592 /* image and movie output has to move to either imbuf or kernel */
593 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
594 {
595         re->display_init = f;
596         re->dih = handle;
597 }
598 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
599 {
600         re->display_clear = f;
601         re->dch = handle;
602 }
603 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
604 {
605         re->display_draw = f;
606         re->ddh = handle;
607 }
608 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
609 {
610         re->stats_draw = f;
611         re->sdh = handle;
612 }
613 void RE_progress_cb(Render *re, void *handle, void (*f)(void *handle, float))
614 {
615         re->progress = f;
616         re->prh = handle;
617 }
618
619 void RE_draw_lock_cb(Render *re, void *handle, void (*f)(void *handle, int i))
620 {
621         re->draw_lock = f;
622         re->tbh = handle;
623 }
624
625 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
626 {
627         re->test_break = f;
628         re->tbh = handle;
629 }
630
631
632 /* ********* add object data (later) ******** */
633
634 /* object is considered fully prepared on correct time etc */
635 /* includes lights */
636 #if 0
637 void RE_AddObject(Render *UNUSED(re), Object *UNUSED(ob))
638 {
639         
640 }
641 #endif
642
643 /* *************************************** */
644
645 static int render_display_draw_enabled(Render *re)
646 {
647         /* don't show preprocess for previewrender sss */
648         if (re->sss_points)
649                 return !(re->r.scemode & R_PREVIEWBUTS);
650         else
651                 return 1;
652 }
653
654 /* the main thread call, renders an entire part */
655 static void *do_part_thread(void *pa_v)
656 {
657         RenderPart *pa = pa_v;
658
659         pa->status = PART_STATUS_IN_PROGRESS;
660
661         /* need to return nicely all parts on esc */
662         if (R.test_break(R.tbh) == 0) {
663                 
664                 if (!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
665                         pa->result = render_result_new_full_sample(&R, &pa->fullresult, &pa->disprect, pa->crop, RR_USE_MEM);
666                 else
667                         pa->result = render_result_new(&R, &pa->disprect, pa->crop, RR_USE_MEM, RR_ALL_LAYERS);
668
669                 if (R.sss_points)
670                         zbufshade_sss_tile(pa);
671                 else if (R.osa)
672                         zbufshadeDA_tile(pa);
673                 else
674                         zbufshade_tile(pa);
675                 
676                 /* merge too on break! */
677                 if (R.result->do_exr_tile) {
678                         render_result_exr_file_merge(R.result, pa->result);
679                 }
680                 else if (render_display_draw_enabled(&R)) {
681                         /* on break, don't merge in result for preview renders, looks nicer */
682                         if (R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS)) {
683                                 /* pass */
684                         }
685                         else {
686                                 render_result_merge(R.result, pa->result);
687                         }
688                 }
689         }
690         
691         pa->status = PART_STATUS_READY;
692         
693         return NULL;
694 }
695
696 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
697 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
698 /* called in initrender.c, RE_parts_init() and convertblender.c, for speedvectors */
699 float panorama_pixel_rot(Render *re)
700 {
701         float psize, phi, xfac;
702         float borderfac = (float)BLI_rcti_size_x(&re->disprect) / (float)re->winx;
703         int xparts = (re->rectx + re->partx - 1) / re->partx;
704         
705         /* size of 1 pixel mapped to viewplane coords */
706         psize = BLI_rctf_size_x(&re->viewplane) / (float)re->winx;
707         /* angle of a pixel */
708         phi = atan(psize / re->clipsta);
709         
710         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
711         xfac = borderfac * BLI_rctf_size_x(&re->viewplane) / (float)xparts;
712         xfac = atan(0.5f * xfac / re->clipsta);
713         /* and how much the same viewplane angle is wrapped */
714         psize = 0.5f * phi * ((float)re->partx);
715         
716         /* the ratio applied to final per-pixel angle */
717         phi *= xfac / psize;
718         
719         return phi;
720 }
721
722 /* call when all parts stopped rendering, to find the next Y slice */
723 /* if slice found, it rotates the dbase */
724 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
725 {
726         RenderPart *pa, *best = NULL;
727         
728         *minx = re->winx;
729         
730         /* most left part of the non-rendering parts */
731         for (pa = re->parts.first; pa; pa = pa->next) {
732                 if (pa->status == PART_STATUS_NONE && pa->nr == 0) {
733                         if (pa->disprect.xmin < *minx) {
734                                 best = pa;
735                                 *minx = pa->disprect.xmin;
736                         }
737                 }
738         }
739                         
740         if (best) {
741                 float phi = panorama_pixel_rot(re);
742
743                 R.panodxp = (re->winx - (best->disprect.xmin + best->disprect.xmax) ) / 2;
744                 R.panodxv = (BLI_rctf_size_x(viewplane) * R.panodxp) / (float)(re->winx);
745
746                 /* shift viewplane */
747                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
748                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
749                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
750                 copy_m4_m4(R.winmat, re->winmat);
751                 
752                 /* rotate database according to part coordinates */
753                 project_renderdata(re, projectverto, 1, -R.panodxp * phi, 1);
754                 R.panosi = sin(R.panodxp * phi);
755                 R.panoco = cos(R.panodxp * phi);
756         }
757         return best;
758 }
759
760 static RenderPart *find_next_part(Render *re, int minx)
761 {
762         RenderPart *pa, *best = NULL;
763
764         /* long long int's needed because of overflow [#24414] */
765         long long int centx = re->winx / 2, centy = re->winy / 2, tot = 1;
766         long long int mindist = (long long int)re->winx * (long long int)re->winy;
767         
768         /* find center of rendered parts, image center counts for 1 too */
769         for (pa = re->parts.first; pa; pa = pa->next) {
770                 if (pa->status == PART_STATUS_READY) {
771                         centx += BLI_rcti_cent_x(&pa->disprect);
772                         centy += BLI_rcti_cent_y(&pa->disprect);
773                         tot++;
774                 }
775         }
776         centx /= tot;
777         centy /= tot;
778         
779         /* closest of the non-rendering parts */
780         for (pa = re->parts.first; pa; pa = pa->next) {
781                 if (pa->status == PART_STATUS_NONE && pa->nr == 0) {
782                         long long int distx = centx - BLI_rcti_cent_x(&pa->disprect);
783                         long long int disty = centy - BLI_rcti_cent_y(&pa->disprect);
784                         distx = (long long int)sqrt(distx * distx + disty * disty);
785                         if (distx < mindist) {
786                                 if (re->r.mode & R_PANORAMA) {
787                                         if (pa->disprect.xmin == minx) {
788                                                 best = pa;
789                                                 mindist = distx;
790                                         }
791                                 }
792                                 else {
793                                         best = pa;
794                                         mindist = distx;
795                                 }
796                         }
797                 }
798         }
799         return best;
800 }
801
802 static void print_part_stats(Render *re, RenderPart *pa)
803 {
804         char str[64];
805         
806         BLI_snprintf(str, sizeof(str), "%s, Part %d-%d", re->scene->id.name + 2, pa->nr, re->i.totpart);
807         re->i.infostr = str;
808         re->stats_draw(re->sdh, &re->i);
809         re->i.infostr = NULL;
810 }
811
812 static void threaded_tile_processor(Render *re)
813 {
814         ListBase threads;
815         RenderPart *pa, *nextpa;
816         rctf viewplane = re->viewplane;
817         int rendering = 1, counter = 1, drawtimer = 0, hasdrawn, minx = 0;
818         
819         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
820
821         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
822         if (re->result == NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
823                 render_result_free(re->result);
824         
825                 if (re->sss_points && render_display_draw_enabled(re))
826                         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
827                 else if (re->r.scemode & R_FULL_SAMPLE)
828                         re->result = render_result_new_full_sample(re, &re->fullresult, &re->disprect, 0, RR_USE_EXR);
829                 else
830                         re->result = render_result_new(re, &re->disprect, 0,
831                                                        (re->r.scemode & R_EXR_TILE_FILE) ? RR_USE_EXR : RR_USE_MEM, RR_ALL_LAYERS);
832         }
833
834         BLI_rw_mutex_unlock(&re->resultmutex);
835         
836         if (re->result == NULL)
837                 return;
838
839         /* warning; no return here without closing exr file */
840         
841         RE_parts_init(re, TRUE);
842
843         if (re->result->do_exr_tile)
844                 render_result_exr_file_begin(re);
845         
846         BLI_init_threads(&threads, do_part_thread, re->r.threads);
847         
848         /* assuming no new data gets added to dbase... */
849         R = *re;
850         
851         /* set threadsafe break */
852         R.test_break = thread_break;
853         
854         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
855         if (re->r.mode & R_PANORAMA)
856                 nextpa = find_next_pano_slice(re, &minx, &viewplane);
857         else
858                 nextpa = find_next_part(re, 0);
859         
860         while (rendering) {
861                 
862                 if (re->test_break(re->tbh))
863                         PIL_sleep_ms(50);
864                 else if (nextpa && BLI_available_threads(&threads)) {
865                         drawtimer = 0;
866                         nextpa->nr = counter++;  /* for nicest part, and for stats */
867                         nextpa->thread = BLI_available_thread_index(&threads);   /* sample index */
868                         BLI_insert_thread(&threads, nextpa);
869
870                         nextpa = find_next_part(re, minx);
871                 }
872                 else if (re->r.mode & R_PANORAMA) {
873                         if (nextpa == NULL && BLI_available_threads(&threads) == re->r.threads)
874                                 nextpa = find_next_pano_slice(re, &minx, &viewplane);
875                         else {
876                                 PIL_sleep_ms(50);
877                                 drawtimer++;
878                         }
879                 }
880                 else {
881                         PIL_sleep_ms(50);
882                         drawtimer++;
883                 }
884                 
885                 /* check for ready ones to display, and if we need to continue */
886                 rendering = 0;
887                 hasdrawn = 0;
888                 for (pa = re->parts.first; pa; pa = pa->next) {
889                         if (pa->status == PART_STATUS_READY) {
890                                 
891                                 BLI_remove_thread(&threads, pa);
892                                 
893                                 if (pa->result) {
894                                         if (render_display_draw_enabled(re))
895                                                 re->display_draw(re->ddh, pa->result, NULL);
896                                         print_part_stats(re, pa);
897                                         
898                                         render_result_free_list(&pa->fullresult, pa->result);
899                                         pa->result = NULL;
900                                         re->i.partsdone++;
901                                         re->progress(re->prh, re->i.partsdone / (float)re->i.totpart);
902                                         hasdrawn = 1;
903                                 }
904                         }
905                         else {
906                                 rendering = 1;
907                                 if (pa->nr && pa->result && drawtimer > 20) {
908                                         if (render_display_draw_enabled(re))
909                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
910                                         hasdrawn = 1;
911                                 }
912                         }
913                 }
914                 if (hasdrawn)
915                         drawtimer = 0;
916
917                 /* on break, wait for all slots to get freed */
918                 if ( (g_break = re->test_break(re->tbh)) && BLI_available_threads(&threads) == re->r.threads)
919                         rendering = 0;
920                 
921         }
922         
923         if (re->result->do_exr_tile) {
924                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
925                 render_result_exr_file_end(re);
926                 BLI_rw_mutex_unlock(&re->resultmutex);
927         }
928         
929         /* unset threadsafety */
930         g_break = 0;
931         
932         BLI_end_threads(&threads);
933         RE_parts_free(re);
934         re->viewplane = viewplane; /* restore viewplane, modified by pano render */
935 }
936
937 /* currently only called by preview renders and envmap */
938 void RE_TileProcessor(Render *re)
939 {
940         threaded_tile_processor(re);
941 }
942
943 /* ************  This part uses API, for rendering Blender scenes ********** */
944
945 static void do_render_3d(Render *re)
946 {
947         float cfra;
948         int cfra_backup;
949
950         /* try external */
951         if (RE_engine_render(re, 0))
952                 return;
953
954         /* internal */
955         RE_parts_clamp(re);
956         
957         /* add motion blur and fields offset to frames */
958         cfra_backup = re->scene->r.cfra;
959
960         cfra = re->scene->r.cfra + re->mblur_offs + re->field_offs;
961         re->scene->r.cfra = floorf(cfra);
962         re->scene->r.subframe = cfra - floorf(cfra);
963
964         /* lock drawing in UI during data phase */
965         if (re->draw_lock)
966                 re->draw_lock(re->dlh, 1);
967         
968         /* make render verts/faces/halos/lamps */
969         if (render_scene_needs_vector(re))
970                 RE_Database_FromScene_Vectors(re, re->main, re->scene, re->lay);
971         else
972                 RE_Database_FromScene(re, re->main, re->scene, re->lay, 1);
973         
974         /* clear UI drawing locks */
975         if (re->draw_lock)
976                 re->draw_lock(re->dlh, 0);
977         
978         threaded_tile_processor(re);
979         
980         /* do left-over 3d post effects (flares) */
981         if (re->flag & R_HALO)
982                 if (!re->test_break(re->tbh))
983                         add_halo_flare(re);
984         
985         /* free all render verts etc */
986         RE_Database_Free(re);
987         
988         re->scene->r.cfra = cfra_backup;
989         re->scene->r.subframe = 0.f;
990 }
991
992 /* called by blur loop, accumulate RGBA key alpha */
993 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
994 {
995         float mfac = 1.0f - blurfac;
996         int a, b, stride = 4 * rr->rectx;
997         int len = stride * sizeof(float);
998         
999         for (a = 0; a < rr->recty; a++) {
1000                 if (blurfac == 1.0f) {
1001                         memcpy(rectf, rectf1, len);
1002                 }
1003                 else {
1004                         float *rf = rectf, *rf1 = rectf1;
1005                         
1006                         for (b = rr->rectx; b > 0; b--, rf += 4, rf1 += 4) {
1007                                 if (rf1[3] < 0.01f)
1008                                         rf[3] = mfac * rf[3];
1009                                 else if (rf[3] < 0.01f) {
1010                                         rf[0] = rf1[0];
1011                                         rf[1] = rf1[1];
1012                                         rf[2] = rf1[2];
1013                                         rf[3] = blurfac * rf1[3];
1014                                 }
1015                                 else {
1016                                         rf[0] = mfac * rf[0] + blurfac * rf1[0];
1017                                         rf[1] = mfac * rf[1] + blurfac * rf1[1];
1018                                         rf[2] = mfac * rf[2] + blurfac * rf1[2];
1019                                         rf[3] = mfac * rf[3] + blurfac * rf1[3];
1020                                 }
1021                         }
1022                 }
1023                 rectf += stride;
1024                 rectf1 += stride;
1025         }
1026 }
1027
1028 /* called by blur loop, accumulate renderlayers */
1029 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1030 {
1031         float mfac = 1.0f - blurfac;
1032         int a, b, stride = channels * rr->rectx;
1033         int len = stride * sizeof(float);
1034         
1035         for (a = 0; a < rr->recty; a++) {
1036                 if (blurfac == 1.0f) {
1037                         memcpy(rectf, rectf1, len);
1038                 }
1039                 else {
1040                         float *rf = rectf, *rf1 = rectf1;
1041                         
1042                         for (b = rr->rectx * channels; b > 0; b--, rf++, rf1++) {
1043                                 rf[0] = mfac * rf[0] + blurfac * rf1[0];
1044                         }
1045                 }
1046                 rectf += stride;
1047                 rectf1 += stride;
1048         }
1049 }
1050
1051
1052 /* called by blur loop, accumulate renderlayers */
1053 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1054 {
1055         RenderLayer *rl, *rl1;
1056         RenderPass *rpass, *rpass1;
1057         
1058         rl1 = brr->layers.first;
1059         for (rl = rr->layers.first; rl && rl1; rl = rl->next, rl1 = rl1->next) {
1060                 
1061                 /* combined */
1062                 if (rl->rectf && rl1->rectf) {
1063                         if (key_alpha)
1064                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1065                         else
1066                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1067                 }
1068                 
1069                 /* passes are allocated in sync */
1070                 rpass1 = rl1->passes.first;
1071                 for (rpass = rl->passes.first; rpass && rpass1; rpass = rpass->next, rpass1 = rpass1->next) {
1072                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1073                 }
1074         }
1075 }
1076
1077 /* main blur loop, can be called by fields too */
1078 static void do_render_blur_3d(Render *re)
1079 {
1080         RenderResult *rres;
1081         float blurfac;
1082         int blur = re->r.mblur_samples;
1083         
1084         /* create accumulation render result */
1085         rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1086         
1087         /* do the blur steps */
1088         while (blur--) {
1089                 re->mblur_offs = re->r.blurfac * ((float)(re->r.mblur_samples - blur)) / (float)re->r.mblur_samples;
1090                 
1091                 re->i.curblur = re->r.mblur_samples - blur;    /* stats */
1092                 
1093                 do_render_3d(re);
1094                 
1095                 blurfac = 1.0f / (float)(re->r.mblur_samples - blur);
1096                 
1097                 merge_renderresult_blur(rres, re->result, blurfac, FALSE);
1098                 if (re->test_break(re->tbh)) break;
1099         }
1100         
1101         /* swap results */
1102         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1103         render_result_free(re->result);
1104         re->result = rres;
1105         BLI_rw_mutex_unlock(&re->resultmutex);
1106         
1107         re->mblur_offs = 0.0f;
1108         re->i.curblur = 0;   /* stats */
1109         
1110         /* weak... the display callback wants an active renderlayer pointer... */
1111         re->result->renlay = render_get_active_layer(re, re->result);
1112         re->display_draw(re->ddh, re->result, NULL);
1113 }
1114
1115
1116 /* function assumes rectf1 and rectf2 to be half size of rectf */
1117 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1118 {
1119         int a, stride = channels * rr->rectx;
1120         int len = stride * sizeof(float);
1121         
1122         for (a = 0; a < rr->recty; a += 2) {
1123                 memcpy(rectf, rectf1, len);
1124                 rectf += stride;
1125                 rectf1 += stride;
1126                 memcpy(rectf, rectf2, len);
1127                 rectf += stride;
1128                 rectf2 += stride;
1129         }
1130 }
1131
1132 /* merge render results of 2 fields */
1133 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1134 {
1135         RenderLayer *rl, *rl1, *rl2;
1136         RenderPass *rpass, *rpass1, *rpass2;
1137         
1138         rl1 = rr1->layers.first;
1139         rl2 = rr2->layers.first;
1140         for (rl = rr->layers.first; rl && rl1 && rl2; rl = rl->next, rl1 = rl1->next, rl2 = rl2->next) {
1141                 
1142                 /* combined */
1143                 if (rl->rectf && rl1->rectf && rl2->rectf)
1144                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1145                 
1146                 /* passes are allocated in sync */
1147                 rpass1 = rl1->passes.first;
1148                 rpass2 = rl2->passes.first;
1149                 for (rpass = rl->passes.first;
1150                      rpass && rpass1 && rpass2;
1151                      rpass = rpass->next, rpass1 = rpass1->next, rpass2 = rpass2->next)
1152                 {
1153                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1154                 }
1155         }
1156 }
1157
1158
1159 /* interleaves 2 frames */
1160 static void do_render_fields_3d(Render *re)
1161 {
1162         Object *camera = RE_GetCamera(re);
1163         RenderResult *rr1, *rr2 = NULL;
1164         
1165         /* no render result was created, we can safely halve render y */
1166         re->winy /= 2;
1167         re->recty /= 2;
1168         re->disprect.ymin /= 2;
1169         re->disprect.ymax /= 2;
1170         
1171         re->i.curfield = 1;  /* stats */
1172         
1173         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1174         RE_SetCamera(re, camera);
1175         if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1176                 do_render_blur_3d(re);
1177         else
1178                 do_render_3d(re);
1179
1180         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1181         rr1 = re->result;
1182         re->result = NULL;
1183         BLI_rw_mutex_unlock(&re->resultmutex);
1184         
1185         /* second field */
1186         if (!re->test_break(re->tbh)) {
1187                 
1188                 re->i.curfield = 2;  /* stats */
1189                 
1190                 re->flag |= R_SEC_FIELD;
1191                 if ((re->r.mode & R_FIELDSTILL) == 0) {
1192                         re->field_offs = 0.5f;
1193                 }
1194                 RE_SetCamera(re, camera);
1195                 if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1196                         do_render_blur_3d(re);
1197                 else
1198                         do_render_3d(re);
1199                 re->flag &= ~R_SEC_FIELD;
1200                 
1201                 re->field_offs = 0.0f;
1202                 
1203                 rr2 = re->result;
1204         }
1205         
1206         /* allocate original height new buffers */
1207         re->winy *= 2;
1208         re->recty *= 2;
1209         re->disprect.ymin *= 2;
1210         re->disprect.ymax *= 2;
1211
1212         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1213         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1214
1215         if (rr2) {
1216                 if (re->r.mode & R_ODDFIELD)
1217                         merge_renderresult_fields(re->result, rr2, rr1);
1218                 else
1219                         merge_renderresult_fields(re->result, rr1, rr2);
1220                 
1221                 render_result_free(rr2);
1222         }
1223
1224         render_result_free(rr1);
1225         
1226         re->i.curfield = 0;  /* stats */
1227         
1228         /* weak... the display callback wants an active renderlayer pointer... */
1229         re->result->renlay = render_get_active_layer(re, re->result);
1230
1231         BLI_rw_mutex_unlock(&re->resultmutex);
1232
1233         re->display_draw(re->ddh, re->result, NULL);
1234 }
1235
1236 /* main render routine, no compositing */
1237 static void do_render_fields_blur_3d(Render *re)
1238 {
1239         Object *camera = RE_GetCamera(re);
1240         /* also check for camera here */
1241         if (camera == NULL) {
1242                 BKE_report(re->reports, RPT_ERROR, "Cannot render, no camera");
1243                 G.is_break = TRUE;
1244                 return;
1245         }
1246
1247         /* now use renderdata and camera to set viewplane */
1248         RE_SetCamera(re, camera);
1249         
1250         if (re->r.mode & R_FIELDS)
1251                 do_render_fields_3d(re);
1252         else if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1253                 do_render_blur_3d(re);
1254         else
1255                 do_render_3d(re);
1256         
1257         /* when border render, check if we have to insert it in black */
1258         if (re->result) {
1259                 if (re->r.mode & R_BORDER) {
1260                         if ((re->r.mode & R_CROP) == 0) {
1261                                 RenderResult *rres;
1262                                 
1263                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1264
1265                                 /* sub-rect for merge call later on */
1266                                 re->result->tilerect = re->disprect;
1267                                 
1268                                 /* this copying sequence could become function? */
1269                                 /* weak is: it chances disprect from border */
1270                                 re->disprect.xmin = re->disprect.ymin = 0;
1271                                 re->disprect.xmax = re->winx;
1272                                 re->disprect.ymax = re->winy;
1273                                 re->rectx = re->winx;
1274                                 re->recty = re->winy;
1275                                 
1276                                 rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1277                                 
1278                                 render_result_merge(rres, re->result);
1279                                 render_result_free(re->result);
1280                                 re->result = rres;
1281                                 
1282                                 /* weak... the display callback wants an active renderlayer pointer... */
1283                                 re->result->renlay = render_get_active_layer(re, re->result);
1284                                 
1285                                 BLI_rw_mutex_unlock(&re->resultmutex);
1286                 
1287                                 re->display_init(re->dih, re->result);
1288                                 re->display_draw(re->ddh, re->result, NULL);
1289                         }
1290                         else {
1291                                 /* set offset (again) for use in compositor, disprect was manipulated. */
1292                                 re->result->xof = 0;
1293                                 re->result->yof = 0;
1294                         }
1295                 }
1296         }
1297 }
1298
1299
1300 /* within context of current Render *re, render another scene.
1301  * it uses current render image size and disprect, but doesn't execute composite
1302  */
1303 static void render_scene(Render *re, Scene *sce, int cfra)
1304 {
1305         Render *resc = RE_NewRender(sce->id.name);
1306         int winx = re->winx, winy = re->winy;
1307         
1308         sce->r.cfra = cfra;
1309
1310         BKE_scene_camera_switch_update(sce);
1311
1312         /* exception: scene uses own size (unfinished code) */
1313         if (0) {
1314                 winx = (sce->r.size * sce->r.xsch) / 100;
1315                 winy = (sce->r.size * sce->r.ysch) / 100;
1316         }
1317         
1318         /* initial setup */
1319         RE_InitState(resc, re, &sce->r, NULL, winx, winy, &re->disprect);
1320         
1321         /* still unsure entity this... */
1322         resc->main = re->main;
1323         resc->scene = sce;
1324         resc->lay = sce->lay;
1325         
1326         /* ensure scene has depsgraph, base flags etc OK */
1327         BKE_scene_set_background(re->main, sce);
1328
1329         /* copy callbacks */
1330         resc->display_draw = re->display_draw;
1331         resc->ddh = re->ddh;
1332         resc->test_break = re->test_break;
1333         resc->tbh = re->tbh;
1334         resc->stats_draw = re->stats_draw;
1335         resc->sdh = re->sdh;
1336         
1337         do_render_fields_blur_3d(resc);
1338 }
1339
1340 /* helper call to detect if this scene needs a render, or if there's a any render layer to render */
1341 static int composite_needs_render(Scene *sce, int this_scene)
1342 {
1343         bNodeTree *ntree = sce->nodetree;
1344         bNode *node;
1345         
1346         if (ntree == NULL) return 1;
1347         if (sce->use_nodes == FALSE) return 1;
1348         if ((sce->r.scemode & R_DOCOMP) == 0) return 1;
1349         
1350         for (node = ntree->nodes.first; node; node = node->next) {
1351                 if (node->type == CMP_NODE_R_LAYERS)
1352                         if (this_scene == 0 || node->id == NULL || node->id == &sce->id)
1353                                 return 1;
1354         }
1355         return 0;
1356 }
1357
1358 static void tag_scenes_for_render(Render *re)
1359 {
1360         bNode *node;
1361         Scene *sce;
1362         
1363         for (sce = re->main->scene.first; sce; sce = sce->id.next)
1364                 sce->id.flag &= ~LIB_DOIT;
1365         
1366         if (RE_GetCamera(re) && composite_needs_render(re->scene, 1))
1367                 re->scene->id.flag |= LIB_DOIT;
1368         
1369         if (re->scene->nodetree == NULL) return;
1370         
1371         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
1372         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1373                 if (node->type == CMP_NODE_R_LAYERS) {
1374                         if (node->id) {
1375                                 if (node->id != (ID *)re->scene)
1376                                         node->id->flag |= LIB_DOIT;
1377                         }
1378                 }
1379         }
1380         
1381 }
1382
1383 static void ntree_render_scenes(Render *re)
1384 {
1385         bNode *node;
1386         int cfra = re->scene->r.cfra;
1387         int restore_scene = 0;
1388         
1389         if (re->scene->nodetree == NULL) return;
1390         
1391         tag_scenes_for_render(re);
1392         
1393         /* now foreach render-result node tagged we do a full render */
1394         /* results are stored in a way compisitor will find it */
1395         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1396                 if (node->type == CMP_NODE_R_LAYERS) {
1397                         if (node->id && node->id != (ID *)re->scene) {
1398                                 if (node->id->flag & LIB_DOIT) {
1399                                         Scene *scene = (Scene *)node->id;
1400
1401                                         render_scene(re, scene, cfra);
1402                                         restore_scene = (scene != re->scene);
1403                                         node->id->flag &= ~LIB_DOIT;
1404                                         
1405                                         nodeUpdate(re->scene->nodetree, node);
1406                                 }
1407                         }
1408                 }
1409         }
1410
1411         /* restore scene if we rendered another last */
1412         if (restore_scene)
1413                 BKE_scene_set_background(re->main, re->scene);
1414 }
1415
1416 /* bad call... need to think over proper method still */
1417 static void render_composit_stats(void *UNUSED(arg), char *str)
1418 {
1419         R.i.infostr = str;
1420         R.stats_draw(R.sdh, &R.i);
1421         R.i.infostr = NULL;
1422 }
1423
1424
1425 /* reads all buffers, calls optional composite, merges in first result->rectf */
1426 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
1427 {
1428         float *rectf, filt[3][3];
1429         int x, y, sample;
1430         
1431         /* interaction callbacks */
1432         if (ntree) {
1433                 ntree->stats_draw = render_composit_stats;
1434                 ntree->test_break = re->test_break;
1435                 ntree->progress = re->progress;
1436                 ntree->sdh = re->sdh;
1437                 ntree->tbh = re->tbh;
1438                 ntree->prh = re->prh;
1439         }
1440         
1441         /* filtmask needs it */
1442         R = *re;
1443         
1444         /* we accumulate in here */
1445         rectf = MEM_mapallocN(re->rectx * re->recty * sizeof(float) * 4, "fullsample rgba");
1446         
1447         for (sample = 0; sample < re->r.osa; sample++) {
1448                 Render *re1;
1449                 RenderResult rres;
1450                 int mask;
1451                 
1452                 /* enable full sample print */
1453                 R.i.curfsa = sample + 1;
1454                 
1455                 /* set all involved renders on the samplebuffers (first was done by render itself, but needs tagged) */
1456                 /* also function below assumes this */
1457                         
1458                 tag_scenes_for_render(re);
1459                 for (re1 = RenderGlobal.renderlist.first; re1; re1 = re1->next) {
1460                         if (re1->scene->id.flag & LIB_DOIT) {
1461                                 if (re1->r.scemode & R_FULL_SAMPLE) {
1462                                         if (sample) {
1463                                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1464                                                 render_result_exr_file_read(re1, sample);
1465                                                 BLI_rw_mutex_unlock(&re->resultmutex);
1466                                         }
1467                                         ntreeCompositTagRender(re1->scene); /* ensure node gets exec to put buffers on stack */
1468                                 }
1469                         }
1470                 }
1471                 
1472                 /* composite */
1473                 if (ntree) {
1474                         ntreeCompositTagRender(re->scene);
1475                         ntreeCompositTagAnimated(ntree);
1476                         
1477                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0, &re->scene->view_settings, &re->scene->display_settings);
1478                 }
1479                 
1480                 /* ensure we get either composited result or the active layer */
1481                 RE_AcquireResultImage(re, &rres);
1482                 
1483                 /* accumulate with filter, and clip */
1484                 mask = (1 << sample);
1485                 mask_array(mask, filt);
1486
1487                 for (y = 0; y < re->recty; y++) {
1488                         float *rf = rectf + 4 * y * re->rectx;
1489                         float *col = rres.rectf + 4 * y * re->rectx;
1490                                 
1491                         for (x = 0; x < re->rectx; x++, rf += 4, col += 4) {
1492                                 /* clamping to 1.0 is needed for correct AA */
1493                                 if (col[0] < 0.0f) col[0] = 0.0f; else if (col[0] > 1.0f) col[0] = 1.0f;
1494                                 if (col[1] < 0.0f) col[1] = 0.0f; else if (col[1] > 1.0f) col[1] = 1.0f;
1495                                 if (col[2] < 0.0f) col[2] = 0.0f; else if (col[2] > 1.0f) col[2] = 1.0f;
1496                                 
1497                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
1498                         }
1499                 }
1500                 
1501                 RE_ReleaseResultImage(re);
1502
1503                 /* show stuff */
1504                 if (sample != re->osa - 1) {
1505                         /* weak... the display callback wants an active renderlayer pointer... */
1506                         re->result->renlay = render_get_active_layer(re, re->result);
1507                         re->display_draw(re->ddh, re->result, NULL);
1508                 }
1509                 
1510                 if (re->test_break(re->tbh))
1511                         break;
1512         }
1513
1514         /* clamp alpha and RGB to 0..1 and 0..inf, can go outside due to filter */
1515         for (y = 0; y < re->recty; y++) {
1516                 float *rf = rectf + 4 * y * re->rectx;
1517                         
1518                 for (x = 0; x < re->rectx; x++, rf += 4) {
1519                         rf[0] = MAX2(rf[0], 0.0f);
1520                         rf[1] = MAX2(rf[1], 0.0f);
1521                         rf[2] = MAX2(rf[2], 0.0f);
1522                         CLAMP(rf[3], 0.0f, 1.0f);
1523                 }
1524         }
1525         
1526         /* clear interaction callbacks */
1527         if (ntree) {
1528                 ntree->stats_draw = NULL;
1529                 ntree->test_break = NULL;
1530                 ntree->progress = NULL;
1531                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1532         }
1533         
1534         /* disable full sample print */
1535         R.i.curfsa = 0;
1536         
1537         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1538         if (re->result->rectf)
1539                 MEM_freeN(re->result->rectf);
1540         re->result->rectf = rectf;
1541         BLI_rw_mutex_unlock(&re->resultmutex);
1542 }
1543
1544 /* called externally, via compositor */
1545 void RE_MergeFullSample(Render *re, Main *bmain, Scene *sce, bNodeTree *ntree)
1546 {
1547         Scene *scene;
1548         bNode *node;
1549
1550         /* default start situation */
1551         G.is_break = FALSE;
1552         
1553         re->main = bmain;
1554         re->scene = sce;
1555         re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
1556         
1557         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
1558         
1559         /* tag scenes unread */
1560         for (scene = re->main->scene.first; scene; scene = scene->id.next)
1561                 scene->id.flag |= LIB_DOIT;
1562         
1563         for (node = ntree->nodes.first; node; node = node->next) {
1564                 if (node->type == CMP_NODE_R_LAYERS) {
1565                         Scene *nodescene = (Scene *)node->id;
1566                         
1567                         if (nodescene == NULL) nodescene = sce;
1568                         if (nodescene->id.flag & LIB_DOIT) {
1569                                 nodescene->r.mode |= R_OSA; /* render struct needs tables */
1570                                 RE_ReadRenderResult(sce, nodescene);
1571                                 nodescene->id.flag &= ~LIB_DOIT;
1572                         }
1573                 }
1574         }
1575         
1576         /* own render result should be read/allocated */
1577         if (re->scene->id.flag & LIB_DOIT) {
1578                 RE_ReadRenderResult(re->scene, re->scene);
1579                 re->scene->id.flag &= ~LIB_DOIT;
1580         }
1581         
1582         /* and now we can draw (result is there) */
1583         re->display_init(re->dih, re->result);
1584         re->display_clear(re->dch, re->result);
1585         
1586         do_merge_fullsample(re, ntree);
1587 }
1588
1589 /* returns fully composited render-result on given time step (in RenderData) */
1590 static void do_render_composite_fields_blur_3d(Render *re)
1591 {
1592         bNodeTree *ntree = re->scene->nodetree;
1593         int update_newframe = 0;
1594         
1595         /* INIT seeding, compositor can use random texture */
1596         BLI_srandom(re->r.cfra);
1597         
1598         if (composite_needs_render(re->scene, 1)) {
1599                 /* save memory... free all cached images */
1600                 ntreeFreeCache(ntree);
1601                 
1602                 do_render_fields_blur_3d(re);
1603         }
1604         else {
1605                 /* ensure new result gets added, like for regular renders */
1606                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1607                 
1608                 render_result_free(re->result);
1609                 re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1610
1611                 BLI_rw_mutex_unlock(&re->resultmutex);
1612                 
1613                 /* scene render process already updates animsys */
1614                 update_newframe = 1;
1615         }
1616         
1617         /* swap render result */
1618         if (re->r.scemode & R_SINGLE_LAYER) {
1619                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1620                 render_result_single_layer_end(re);
1621                 BLI_rw_mutex_unlock(&re->resultmutex);
1622         }
1623         
1624         if (!re->test_break(re->tbh)) {
1625                 
1626                 if (ntree) {
1627                         ntreeCompositTagRender(re->scene);
1628                         ntreeCompositTagAnimated(ntree);
1629                 }
1630                 
1631                 if (ntree && re->scene->use_nodes && re->r.scemode & R_DOCOMP) {
1632                         /* checks if there are render-result nodes that need scene */
1633                         if ((re->r.scemode & R_SINGLE_LAYER) == 0)
1634                                 ntree_render_scenes(re);
1635                         
1636                         if (!re->test_break(re->tbh)) {
1637                                 ntree->stats_draw = render_composit_stats;
1638                                 ntree->test_break = re->test_break;
1639                                 ntree->progress = re->progress;
1640                                 ntree->sdh = re->sdh;
1641                                 ntree->tbh = re->tbh;
1642                                 ntree->prh = re->prh;
1643                                 
1644                                 /* in case it was never initialized */
1645                                 R.sdh = re->sdh;
1646                                 R.stats_draw = re->stats_draw;
1647                                 
1648                                 if (update_newframe)
1649                                         BKE_scene_update_for_newframe(re->main, re->scene, re->lay);
1650                                 
1651                                 if (re->r.scemode & R_FULL_SAMPLE)
1652                                         do_merge_fullsample(re, ntree);
1653                                 else {
1654                                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0, &re->scene->view_settings, &re->scene->display_settings);
1655                                 }
1656                                 
1657                                 ntree->stats_draw = NULL;
1658                                 ntree->test_break = NULL;
1659                                 ntree->progress = NULL;
1660                                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1661                         }
1662                 }
1663                 else if (re->r.scemode & R_FULL_SAMPLE)
1664                         do_merge_fullsample(re, NULL);
1665         }
1666
1667         /* weak... the display callback wants an active renderlayer pointer... */
1668         re->result->renlay = render_get_active_layer(re, re->result);
1669         re->display_draw(re->ddh, re->result, NULL);
1670 }
1671
1672 static void renderresult_stampinfo(Render *re)
1673 {
1674         RenderResult rres;
1675
1676         /* this is the basic trick to get the displayed float or char rect from render result */
1677         RE_AcquireResultImage(re, &rres);
1678         BKE_stamp_buf(re->scene, RE_GetCamera(re), (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
1679         RE_ReleaseResultImage(re);
1680 }
1681
1682 int RE_seq_render_active(Scene *scene, RenderData *rd)
1683 {
1684         Editing *ed;
1685         Sequence *seq;
1686
1687         ed = scene->ed;
1688         
1689         if (!(rd->scemode & R_DOSEQ) || !ed || !ed->seqbase.first)
1690                 return 0;
1691         
1692         for (seq = ed->seqbase.first; seq; seq = seq->next) {
1693                 if (seq->type != SEQ_TYPE_SOUND_RAM)
1694                         return 1;
1695         }
1696         
1697         return 0;
1698 }
1699
1700 static void do_render_seq(Render *re)
1701 {
1702         static int recurs_depth = 0;
1703         struct ImBuf *ibuf, *out;
1704         RenderResult *rr; /* don't assign re->result here as it might change during give_ibuf_seq */
1705         int cfra = re->r.cfra;
1706         SeqRenderData context;
1707
1708         re->i.cfra = cfra;
1709
1710         if (recurs_depth == 0) {
1711                 /* otherwise sequencer animation isn't updated */
1712                 BKE_animsys_evaluate_all_animation(re->main, re->scene, (float)cfra); // XXX, was BKE_scene_frame_get(re->scene)
1713         }
1714
1715         recurs_depth++;
1716
1717         if ((re->r.mode & R_BORDER) && (re->r.mode & R_CROP) == 0) {
1718                 /* if border rendering is used and cropping is disabled, final buffer should
1719                  * be as large as the whole frame */
1720                 context = BKE_sequencer_new_render_data(re->main, re->scene,
1721                                               re->winx, re->winy,
1722                                               100);
1723         }
1724         else {
1725                 context = BKE_sequencer_new_render_data(re->main, re->scene,
1726                                               re->result->rectx, re->result->recty,
1727                                               100);
1728         }
1729
1730         out = BKE_sequencer_give_ibuf(context, cfra, 0);
1731
1732         if (out) {
1733                 ibuf = IMB_dupImBuf(out);
1734                 IMB_freeImBuf(out);
1735                 BKE_sequencer_imbuf_from_sequencer_space(re->scene, ibuf);
1736         }
1737         else {
1738                 ibuf = NULL;
1739         }
1740
1741         recurs_depth--;
1742
1743         rr = re->result;
1744         
1745         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1746
1747         if (ibuf) {
1748                 /* copy ibuf into combined pixel rect */
1749                 render_result_rect_from_ibuf(rr, &re->r, ibuf);
1750                 
1751                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
1752                         Editing *ed = re->scene->ed;
1753                         if (ed)
1754                                 BKE_sequencer_free_imbuf(re->scene, &ed->seqbase, TRUE);
1755                 }
1756                 IMB_freeImBuf(ibuf);
1757         }
1758         else {
1759                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
1760                 render_result_rect_fill_zero(rr);
1761         }
1762
1763         BLI_rw_mutex_unlock(&re->resultmutex);
1764
1765         /* just in case this flag went missing at some point */
1766         re->r.scemode |= R_DOSEQ;
1767
1768         /* set overall progress of sequence rendering */
1769         if (re->r.efra != re->r.sfra)
1770                 re->progress(re->prh, (float)(cfra - re->r.sfra) / (re->r.efra - re->r.sfra));
1771         else
1772                 re->progress(re->prh, 1.0f);
1773
1774         /* would mark display buffers as invalid */
1775         re->display_draw(re->ddh, re->result, NULL);
1776 }
1777
1778 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1779
1780 /* main loop: doing sequence + fields + blur + 3d render + compositing */
1781 static void do_render_all_options(Render *re)
1782 {
1783         BKE_scene_camera_switch_update(re->scene);
1784
1785         re->i.starttime = PIL_check_seconds_timer();
1786
1787         /* ensure no images are in memory from previous animated sequences */
1788         BKE_image_all_free_anim_ibufs(re->r.cfra);
1789
1790         re->pool = BKE_image_pool_new();
1791
1792         if (RE_engine_render(re, 1)) {
1793                 /* in this case external render overrides all */
1794         }
1795         else if (RE_seq_render_active(re->scene, &re->r)) {
1796                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
1797                 if (!re->test_break(re->tbh))
1798                         do_render_seq(re);
1799                 
1800                 re->stats_draw(re->sdh, &re->i);
1801                 re->display_draw(re->ddh, re->result, NULL);
1802         }
1803         else {
1804                 do_render_composite_fields_blur_3d(re);
1805         }
1806         
1807         re->i.lastframetime = PIL_check_seconds_timer() - re->i.starttime;
1808         
1809         re->stats_draw(re->sdh, &re->i);
1810         
1811         /* stamp image info here */
1812         if ((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
1813                 renderresult_stampinfo(re);
1814                 re->display_draw(re->ddh, re->result, NULL);
1815         }
1816
1817         BKE_image_pool_free(re->pool);
1818         re->pool = NULL;
1819 }
1820
1821 static int check_valid_camera(Scene *scene, Object *camera_override)
1822 {
1823         int check_comp = 1;
1824
1825         if (camera_override == NULL && scene->camera == NULL)
1826                 scene->camera = BKE_scene_camera_find(scene);
1827
1828         if (scene->r.scemode & R_DOSEQ) {
1829                 if (scene->ed) {
1830                         Sequence *seq = scene->ed->seqbase.first;
1831
1832                         check_comp = 0;
1833
1834                         while (seq) {
1835                                 if (seq->type == SEQ_TYPE_SCENE && seq->scene) {
1836                                         if (!seq->scene_camera) {
1837                                                 if (!seq->scene->camera && !BKE_scene_camera_find(seq->scene)) {
1838                                                         if (seq->scene == scene) {
1839                                                                 /* for current scene camera could be unneeded due to compisite nodes */
1840                                                                 check_comp = 1;
1841                                                         }
1842                                                         else {
1843                                                                 /* for other scenes camera is necessary */
1844                                                                 return 0;
1845                                                         }
1846                                                 }
1847                                         }
1848                                 }
1849
1850                                 seq = seq->next;
1851                         }
1852                 }
1853         }
1854
1855         if (check_comp) { /* no sequencer or sequencer depends on compositor */
1856                 if (scene->r.scemode & R_DOCOMP && scene->use_nodes) {
1857                         bNode *node = scene->nodetree->nodes.first;
1858
1859                         while (node) {
1860                                 if (node->type == CMP_NODE_R_LAYERS) {
1861                                         Scene *sce = node->id ? (Scene *)node->id : scene;
1862
1863                                         if (!sce->camera && !BKE_scene_camera_find(sce)) {
1864                                                 /* all render layers nodes need camera */
1865                                                 return 0;
1866                                         }
1867                                 }
1868
1869                                 node = node->next;
1870                         }
1871                 }
1872                 else {
1873                         return (camera_override != NULL || scene->camera != NULL);
1874                 }
1875         }
1876
1877         return 1;
1878 }
1879
1880 static int node_tree_has_composite_output(bNodeTree *ntree)
1881 {
1882         bNode *node;
1883
1884         for (node = ntree->nodes.first; node; node = node->next) {
1885                 if (node->type == CMP_NODE_COMPOSITE) {
1886                         return TRUE;
1887                 }
1888                 else if (node->type == NODE_GROUP) {
1889                         if (node->id) {
1890                                 if (node_tree_has_composite_output((bNodeTree *)node->id)) {
1891                                         return TRUE;
1892                                 }
1893                         }
1894                 }
1895         }
1896
1897         return FALSE;
1898 }
1899
1900 static int check_composite_output(Scene *scene)
1901 {
1902         return node_tree_has_composite_output(scene->nodetree);
1903 }
1904
1905 int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *reports)
1906 {
1907         SceneRenderLayer *srl;
1908         
1909         if (scene->r.mode & R_BORDER) {
1910                 if (scene->r.border.xmax <= scene->r.border.xmin ||
1911                     scene->r.border.ymax <= scene->r.border.ymin)
1912                 {
1913                         BKE_report(reports, RPT_ERROR, "No border area selected");
1914                         return 0;
1915                 }
1916         }
1917         
1918         if (scene->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
1919                 char str[FILE_MAX];
1920                 
1921                 render_result_exr_file_path(scene, "", 0, str);
1922                 
1923                 if (BLI_file_is_writable(str) == 0) {
1924                         BKE_report(reports, RPT_ERROR, "Cannot save render buffers, check the temp default path");
1925                         return 0;
1926                 }
1927                 
1928                 /* no fullsample and edge */
1929                 if ((scene->r.scemode & R_FULL_SAMPLE) && (scene->r.mode & R_EDGE)) {
1930                         BKE_report(reports, RPT_ERROR, "Full sample does not support edge enhance");
1931                         return 0;
1932                 }
1933                 
1934         }
1935         else
1936                 scene->r.scemode &= ~R_FULL_SAMPLE;  /* clear to be sure */
1937         
1938         if (scene->r.scemode & R_DOCOMP) {
1939                 if (scene->use_nodes) {
1940                         if (!scene->nodetree) {
1941                                 BKE_report(reports, RPT_ERROR, "No node tree in scene");
1942                                 return 0;
1943                         }
1944                         
1945                         if (!check_composite_output(scene)) {
1946                                 BKE_report(reports, RPT_ERROR, "No render output node in scene");
1947                                 return 0;
1948                         }
1949                         
1950                         if (scene->r.scemode & R_FULL_SAMPLE) {
1951                                 if (composite_needs_render(scene, 0) == 0) {
1952                                         BKE_report(reports, RPT_ERROR, "Full sample AA not supported without 3D rendering");
1953                                         return 0;
1954                                 }
1955                         }
1956                 }
1957         }
1958         
1959         /* check valid camera, without camera render is OK (compo, seq) */
1960         if (!check_valid_camera(scene, camera_override)) {
1961                 BKE_report(reports, RPT_ERROR, "No camera");
1962                 return 0;
1963         }
1964         
1965         /* get panorama & ortho, only after camera is set */
1966         BKE_camera_object_mode(&scene->r, camera_override ? camera_override : scene->camera);
1967
1968         /* forbidden combinations */
1969         if (scene->r.mode & R_PANORAMA) {
1970                 if (scene->r.mode & R_ORTHO) {
1971                         BKE_report(reports, RPT_ERROR, "No ortho render possible for panorama");
1972                         return 0;
1973                 }
1974         }
1975
1976         /* layer flag tests */
1977         if (scene->r.scemode & R_SINGLE_LAYER) {
1978                 srl = BLI_findlink(&scene->r.layers, scene->r.actlay);
1979                 /* force layer to be enabled */
1980                 srl->layflag &= ~SCE_LAY_DISABLE;
1981         }
1982         
1983         for (srl = scene->r.layers.first; srl; srl = srl->next)
1984                 if (!(srl->layflag & SCE_LAY_DISABLE))
1985                         break;
1986         if (srl == NULL) {
1987                 BKE_report(reports, RPT_ERROR, "All render layers are disabled");
1988                 return 0;
1989         }
1990
1991         return 1;
1992 }
1993
1994 static void validate_render_settings(Render *re)
1995 {
1996         if (re->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
1997                 /* no osa + fullsample won't work... */
1998                 if (re->r.osa == 0)
1999                         re->r.scemode &= ~R_FULL_SAMPLE;
2000         }
2001         else re->r.scemode &= ~R_FULL_SAMPLE;   /* clear to be sure */
2002
2003         if (RE_engine_is_external(re)) {
2004                 /* not supported yet */
2005                 re->r.scemode &= ~(R_FULL_SAMPLE);
2006                 re->r.mode &= ~(R_FIELDS | R_MBLUR);
2007         }
2008 }
2009
2010 static void update_physics_cache(Render *re, Scene *scene, int UNUSED(anim_init))
2011 {
2012         PTCacheBaker baker;
2013
2014         baker.main = re->main;
2015         baker.scene = scene;
2016         baker.pid = NULL;
2017         baker.bake = 0;
2018         baker.render = 1;
2019         baker.anim_init = 1;
2020         baker.quick_step = 1;
2021         baker.break_test = re->test_break;
2022         baker.break_data = re->tbh;
2023         baker.progressbar = NULL;
2024
2025         BKE_ptcache_bake(&baker);
2026 }
2027 /* evaluating scene options for general Blender render */
2028 static int render_initialize_from_main(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int anim, int anim_init)
2029 {
2030         int winx, winy;
2031         rcti disprect;
2032         
2033         /* r.xsch and r.ysch has the actual view window size
2034          * r.border is the clipping rect */
2035         
2036         /* calculate actual render result and display size */
2037         winx = (scene->r.size * scene->r.xsch) / 100;
2038         winy = (scene->r.size * scene->r.ysch) / 100;
2039         
2040         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2041         if (scene->r.mode & R_BORDER) {
2042                 disprect.xmin = scene->r.border.xmin * winx;
2043                 disprect.xmax = scene->r.border.xmax * winx;
2044                 
2045                 disprect.ymin = scene->r.border.ymin * winy;
2046                 disprect.ymax = scene->r.border.ymax * winy;
2047         }
2048         else {
2049                 disprect.xmin = disprect.ymin = 0;
2050                 disprect.xmax = winx;
2051                 disprect.ymax = winy;
2052         }
2053         
2054         re->main = bmain;
2055         re->scene = scene;
2056         re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
2057         re->camera_override = camera_override;
2058         re->lay = lay;
2059         
2060         /* not too nice, but it survives anim-border render */
2061         if (anim) {
2062                 re->disprect = disprect;
2063                 return 1;
2064         }
2065         
2066         /* check all scenes involved */
2067         tag_scenes_for_render(re);
2068
2069         /*
2070          * Disabled completely for now,
2071          * can be later set as render profile option
2072          * and default for background render.
2073          */
2074         if (0) {
2075                 /* make sure dynamics are up to date */
2076                 update_physics_cache(re, scene, anim_init);
2077         }
2078         
2079         if (srl || scene->r.scemode & R_SINGLE_LAYER) {
2080                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2081                 render_result_single_layer_begin(re);
2082                 BLI_rw_mutex_unlock(&re->resultmutex);
2083         }
2084         
2085         RE_InitState(re, NULL, &scene->r, srl, winx, winy, &disprect);
2086         if (!re->ok)  /* if an error was printed, abort */
2087                 return 0;
2088         
2089         /* initstate makes new result, have to send changed tags around */
2090         ntreeCompositTagRender(re->scene);
2091
2092         validate_render_settings(re);
2093
2094         re->display_init(re->dih, re->result);
2095         re->display_clear(re->dch, re->result);
2096         
2097         return 1;
2098 }
2099
2100 void RE_SetReports(Render *re, ReportList *reports)
2101 {
2102         re->reports = reports;
2103 }
2104
2105 /* general Blender frame render call */
2106 void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int frame, const short write_still)
2107 {
2108         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2109         G.is_rendering = TRUE;
2110         
2111         scene->r.cfra = frame;
2112         
2113         if (render_initialize_from_main(re, bmain, scene, srl, camera_override, lay, 0, 0)) {
2114                 MEM_reset_peak_memory();
2115
2116                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2117
2118                 do_render_all_options(re);
2119
2120                 if (write_still && !G.is_break) {
2121                         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2122                                 /* operator checks this but in case its called from elsewhere */
2123                                 printf("Error: cant write single images with a movie format!\n");
2124                         }
2125                         else {
2126                                 char name[FILE_MAX];
2127                                 BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, &scene->r.im_format, scene->r.scemode & R_EXTENSION, FALSE);
2128
2129                                 /* reports only used for Movie */
2130                                 do_write_image_or_movie(re, bmain, scene, NULL, name);
2131                         }
2132                 }
2133
2134                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2135         }
2136
2137         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2138
2139         /* UGLY WARNING */
2140         G.is_rendering = FALSE;
2141 }
2142
2143 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override)
2144 {
2145         char name[FILE_MAX];
2146         RenderResult rres;
2147         Object *camera = RE_GetCamera(re);
2148         int ok = 1;
2149         
2150         RE_AcquireResultImage(re, &rres);
2151
2152         /* write movie or image */
2153         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2154                 int do_free = FALSE;
2155                 ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
2156
2157                 /* note; the way it gets 32 bits rects is weak... */
2158                 if (ibuf->rect == NULL) {
2159                         ibuf->rect = MEM_mapallocN(sizeof(int) * rres.rectx * rres.recty, "temp 32 bits rect");
2160                         ibuf->mall |= IB_rect;
2161                         RE_ResultGet32(re, ibuf->rect);
2162                         do_free = TRUE;
2163                 }
2164
2165
2166                 IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2167                                                     &scene->display_settings, &scene->r.im_format);
2168
2169                 ok = mh->append_movie(&re->r, scene->r.sfra, scene->r.cfra, (int *) ibuf->rect,
2170                                       ibuf->x, ibuf->y, re->reports);
2171                 if (do_free) {
2172                         MEM_freeN(ibuf->rect);
2173                         ibuf->rect = NULL;
2174                         ibuf->mall &= ~IB_rect;
2175                 }
2176
2177                 /* imbuf knows which rects are not part of ibuf */
2178                 IMB_freeImBuf(ibuf);
2179
2180                 printf("Append frame %d", scene->r.cfra);
2181         }
2182         else {
2183                 if (name_override)
2184                         BLI_strncpy(name, name_override, sizeof(name));
2185                 else
2186                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, &scene->r.im_format, scene->r.scemode & R_EXTENSION, TRUE);
2187                 
2188                 if (re->r.im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
2189                         if (re->result) {
2190                                 RE_WriteRenderResult(re->reports, re->result, name, scene->r.im_format.exr_codec);
2191                                 printf("Saved: %s", name);
2192                         }
2193                 }
2194                 else {
2195                         ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
2196
2197                         IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2198                                                             &scene->display_settings, &scene->r.im_format);
2199
2200                         ok = BKE_imbuf_write_stamp(scene, camera, ibuf, name, &scene->r.im_format);
2201                         
2202                         if (ok == 0) {
2203                                 printf("Render error: cannot save %s\n", name);
2204                         }
2205                         else printf("Saved: %s", name);
2206                         
2207                         /* optional preview images for exr */
2208                         if (ok && scene->r.im_format.imtype == R_IMF_IMTYPE_OPENEXR && (scene->r.im_format.flag & R_IMF_FLAG_PREVIEW_JPG)) {
2209                                 ImageFormatData imf = scene->r.im_format;
2210                                 imf.imtype = R_IMF_IMTYPE_JPEG90;
2211
2212                                 if (BLI_testextensie(name, ".exr"))
2213                                         name[strlen(name) - 4] = 0;
2214                                 BKE_add_image_extension(name, &imf);
2215                                 ibuf->planes = 24;
2216
2217                                 IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2218                                                                     &scene->display_settings, &imf);
2219
2220                                 BKE_imbuf_write_stamp(scene, camera, ibuf, name, &imf);
2221                                 printf("\nSaved: %s", name);
2222                         }
2223                         
2224                         /* imbuf knows which rects are not part of ibuf */
2225                         IMB_freeImBuf(ibuf);
2226                 }
2227         }
2228         
2229         RE_ReleaseResultImage(re);
2230
2231         BLI_timestr(re->i.lastframetime, name);
2232         printf(" Time: %s", name);
2233
2234         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
2235
2236         fputc('\n', stdout);
2237         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2238
2239         return ok;
2240 }
2241
2242 /* saves images to disk */
2243 void RE_BlenderAnim(Render *re, Main *bmain, Scene *scene, Object *camera_override, unsigned int lay, int sfra, int efra, int tfra)
2244 {
2245         bMovieHandle *mh = BKE_movie_handle_get(scene->r.im_format.imtype);
2246         int cfrao = scene->r.cfra;
2247         int nfra, totrendered = 0, totskipped = 0;
2248         
2249         /* do not fully call for each frame, it initializes & pops output window */
2250         if (!render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 0, 1))
2251                 return;
2252         
2253         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2254         /* is also set by caller renderwin.c */
2255         G.is_rendering = TRUE;
2256
2257         re->flag |= R_ANIMATION;
2258
2259         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2260                 if (!mh->start_movie(scene, &re->r, re->rectx, re->recty, re->reports))
2261                         G.is_break = TRUE;
2262
2263         if (mh->get_next_frame) {
2264                 while (!(G.is_break == 1)) {
2265                         int nf = mh->get_next_frame(&re->r, re->reports);
2266                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2267                                 scene->r.cfra = re->r.cfra = nf;
2268
2269                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2270
2271                                 do_render_all_options(re);
2272                                 totrendered++;
2273
2274                                 if (re->test_break(re->tbh) == 0) {
2275                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2276                                                 G.is_break = TRUE;
2277                                 }
2278
2279                                 if (G.is_break == FALSE) {
2280                                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2281                                 }
2282                         }
2283                         else {
2284                                 if (re->test_break(re->tbh)) {
2285                                         G.is_break = TRUE;
2286                                 }
2287                         }
2288                 }
2289         }
2290         else {
2291                 for (nfra = sfra, scene->r.cfra = sfra; scene->r.cfra <= efra; scene->r.cfra++) {
2292                         char name[FILE_MAX];
2293                         
2294                         /* only border now, todo: camera lens. (ton) */
2295                         render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 1, 0);
2296
2297                         if (nfra != scene->r.cfra) {
2298                                 /*
2299                                  * Skip this frame, but update for physics and particles system.
2300                                  * From convertblender.c:
2301                                  * in localview, lamps are using normal layers, objects only local bits.
2302                                  */
2303                                 unsigned int updatelay;
2304
2305                                 if (re->lay & 0xFF000000)
2306                                         updatelay = re->lay & 0xFF000000;
2307                                 else
2308                                         updatelay = re->lay;
2309
2310                                 BKE_scene_update_for_newframe(bmain, scene, updatelay);
2311                                 continue;
2312                         }
2313                         else
2314                                 nfra += tfra;
2315
2316                         /* Touch/NoOverwrite options are only valid for image's */
2317                         if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2318                                 if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2319                                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, &scene->r.im_format, scene->r.scemode & R_EXTENSION, TRUE);
2320
2321                                 if (scene->r.mode & R_NO_OVERWRITE && BLI_exists(name)) {
2322                                         printf("skipping existing frame \"%s\"\n", name);
2323                                         totskipped++;
2324                                         continue;
2325                                 }
2326                                 if (scene->r.mode & R_TOUCH && !BLI_exists(name)) {
2327                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2328                                         BLI_file_touch(name);
2329                                 }
2330                         }
2331
2332                         re->r.cfra = scene->r.cfra;     /* weak.... */
2333
2334                         /* run callbacs before rendering, before the scene is updated */
2335                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2336
2337                         
2338                         do_render_all_options(re);
2339                         totrendered++;
2340                         
2341                         if (re->test_break(re->tbh) == 0) {
2342                                 if (!G.is_break)
2343                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2344                                                 G.is_break = TRUE;
2345                         }
2346                         else
2347                                 G.is_break = TRUE;
2348                 
2349                         if (G.is_break == TRUE) {
2350                                 /* remove touched file */
2351                                 if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2352                                         if (scene->r.mode & R_TOUCH && BLI_exists(name) && BLI_file_size(name) == 0) {
2353                                                 BLI_delete(name, 0, 0);
2354                                         }
2355                                 }
2356                                 
2357                                 break;
2358                         }
2359
2360                         if (G.is_break == FALSE) {
2361                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2362                         }
2363                 }
2364         }
2365         
2366         /* end movie */
2367         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2368                 mh->end_movie();
2369         
2370         if (totskipped && totrendered == 0)
2371                 BKE_report(re->reports, RPT_INFO, "No frames rendered, skipped to not overwrite");
2372
2373         scene->r.cfra = cfrao;
2374
2375         re->flag &= ~R_ANIMATION;
2376
2377         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2378
2379         /* UGLY WARNING */
2380         G.is_rendering = FALSE;
2381 }
2382
2383 void RE_PreviewRender(Render *re, Main *bmain, Scene *sce)
2384 {
2385         Object *camera;
2386         int winx, winy;
2387
2388         winx = (sce->r.size * sce->r.xsch) / 100;
2389         winy = (sce->r.size * sce->r.ysch) / 100;
2390
2391         RE_InitState(re, NULL, &sce->r, NULL, winx, winy, NULL);
2392
2393         re->pool = BKE_image_pool_new();
2394
2395         re->main = bmain;
2396         re->scene = sce;
2397         re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
2398         re->lay = sce->lay;
2399
2400         camera = RE_GetCamera(re);
2401         RE_SetCamera(re, camera);
2402
2403         do_render_3d(re);
2404
2405         BKE_image_pool_free(re->pool);
2406         re->pool = NULL;
2407 }
2408
2409 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2410
2411 /* only the temp file! */
2412 int RE_ReadRenderResult(Scene *scene, Scene *scenode)
2413 {
2414         Render *re;
2415         int winx, winy, success;
2416         rcti disprect;
2417         
2418         /* calculate actual render result and display size */
2419         winx = (scene->r.size * scene->r.xsch) / 100;
2420         winy = (scene->r.size * scene->r.ysch) / 100;
2421         
2422         /* only in movie case we render smaller part */
2423         if (scene->r.mode & R_BORDER) {
2424                 disprect.xmin = scene->r.border.xmin * winx;
2425                 disprect.xmax = scene->r.border.xmax * winx;
2426                 
2427                 disprect.ymin = scene->r.border.ymin * winy;
2428                 disprect.ymax = scene->r.border.ymax * winy;
2429         }
2430         else {
2431                 disprect.xmin = disprect.ymin = 0;
2432                 disprect.xmax = winx;
2433                 disprect.ymax = winy;
2434         }
2435         
2436         if (scenode)
2437                 scene = scenode;
2438         
2439         /* get render: it can be called from UI with draw callbacks */
2440         re = RE_GetRender(scene->id.name);
2441         if (re == NULL)
2442                 re = RE_NewRender(scene->id.name);
2443         RE_InitState(re, NULL, &scene->r, NULL, winx, winy, &disprect);
2444         re->scene = scene;
2445         re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
2446         
2447         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2448         success = render_result_exr_file_read(re, 0);
2449         BLI_rw_mutex_unlock(&re->resultmutex);
2450
2451         return success;
2452 }
2453
2454 void RE_set_max_threads(int threads)
2455 {
2456         if (threads == 0) {
2457                 RenderGlobal.threads = BLI_system_thread_count();
2458         }
2459         else if (threads >= 1 && threads <= BLENDER_MAX_THREADS) {
2460                 RenderGlobal.threads = threads;
2461         }
2462         else {
2463                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2464         }
2465 }
2466
2467 void RE_init_threadcount(Render *re) 
2468 {
2469         if (RenderGlobal.threads >= 1) { /* only set as an arg in background mode */
2470                 re->r.threads = MIN2(RenderGlobal.threads, BLENDER_MAX_THREADS);
2471         }
2472         else if ((re->r.mode & R_FIXED_THREADS) == 0 || RenderGlobal.threads == 0) { /* Automatic threads */
2473                 re->r.threads = BLI_system_thread_count();
2474         }
2475 }
2476
2477 /* loads in image into a result, size must match
2478  * x/y offsets are only used on a partial copy when dimensions don't match */
2479 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, const char *filename, int x, int y)
2480 {
2481         /* OCIO_TODO: assume layer was saved in defaule color space */
2482         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect, NULL);
2483
2484         if (ibuf && (ibuf->rect || ibuf->rect_float)) {
2485                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
2486                         if (ibuf->rect_float == NULL)
2487                                 IMB_float_from_rect(ibuf);
2488
2489                         memcpy(layer->rectf, ibuf->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2490                 }
2491                 else {
2492                         if ((ibuf->x - x >= layer->rectx) && (ibuf->y - y >= layer->recty)) {
2493                                 ImBuf *ibuf_clip;
2494
2495                                 if (ibuf->rect_float == NULL)
2496                                         IMB_float_from_rect(ibuf);
2497
2498                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat);
2499                                 if (ibuf_clip) {
2500                                         IMB_rectcpy(ibuf_clip, ibuf, 0, 0, x, y, layer->rectx, layer->recty);
2501
2502                                         memcpy(layer->rectf, ibuf_clip->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2503                                         IMB_freeImBuf(ibuf_clip);
2504                                 }
2505                                 else {
2506                                         BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'", filename);
2507                                 }
2508                         }
2509                         else {
2510                                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'", filename);
2511                         }
2512                 }
2513
2514                 IMB_freeImBuf(ibuf);
2515         }
2516         else {
2517                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
2518         }
2519 }
2520
2521 void RE_result_load_from_file(RenderResult *result, ReportList *reports, const char *filename)
2522 {
2523         if (!render_result_exr_file_read_path(result, NULL, filename)) {
2524                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
2525                 return;
2526         }
2527 }
2528
2529 const float default_envmap_layout[] = { 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1 };
2530
2531 int RE_WriteEnvmapResult(struct ReportList *reports, Scene *scene, EnvMap *env, const char *relpath, const char imtype, float layout[12])
2532 {
2533         ImageFormatData imf;
2534         ImBuf *ibuf = NULL;
2535         int ok;
2536         int dx;
2537         int maxX = 0, maxY = 0, i = 0;
2538         char filepath[FILE_MAX];
2539
2540         if (env->cube[1] == NULL) {
2541                 BKE_report(reports, RPT_ERROR, "There is no generated environment map available to save");
2542                 return 0;
2543         }
2544
2545         imf = scene->r.im_format;
2546         imf.imtype = imtype;
2547
2548         dx = env->cube[1]->x;
2549
2550         if (env->type == ENV_CUBE) {
2551                 for (i = 0; i < 12; i += 2) {
2552                         maxX = max_ii(maxX, (int)layout[i] + 1);
2553                         maxY = max_ii(maxY, (int)layout[i + 1] + 1);
2554                 }
2555
2556                 ibuf = IMB_allocImBuf(maxX * dx, maxY * dx, 24, IB_rectfloat);
2557
2558                 for (i = 0; i < 12; i += 2)
2559                         if (layout[i] > -1 && layout[i + 1] > -1)
2560                                 IMB_rectcpy(ibuf, env->cube[i / 2], layout[i] * dx, layout[i + 1] * dx, 0, 0, dx, dx);
2561         }
2562         else if (env->type == ENV_PLANE) {
2563                 ibuf = IMB_allocImBuf(dx, dx, 24, IB_rectfloat);
2564                 IMB_rectcpy(ibuf, env->cube[1], 0, 0, 0, 0, dx, dx);
2565         }
2566         else {
2567                 BKE_report(reports, RPT_ERROR, "Invalid environment map type");
2568                 return 0;
2569         }
2570
2571         IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings, &scene->display_settings, &imf);
2572
2573         /* to save, we first get absolute path */
2574         BLI_strncpy(filepath, relpath, sizeof(filepath));
2575         BLI_path_abs(filepath, G.main->name);
2576
2577         ok = BKE_imbuf_write(ibuf, filepath, &imf);
2578
2579         IMB_freeImBuf(ibuf);
2580
2581         if (ok) {
2582                 return TRUE;
2583         }
2584         else {
2585                 BKE_report(reports, RPT_ERROR, "Error writing environment map");
2586                 return FALSE;
2587         }
2588 }
2589