Corrections to alpha pipeline do_versions
[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 bool rlayer_node_uses_alpha(bNodeTree *ntree, bNode *node)
1359 {
1360         bNodeSocket *sock;
1361
1362         for (sock = node->outputs.first; sock; sock = sock->next) {
1363                 /* Weak! but how to make it better? */
1364                 if (!strcmp(sock->name, "Alpha") && nodeCountSocketLinks(ntree, sock) > 0)
1365                         return true;
1366         }
1367
1368         return false;
1369 }
1370
1371 static void tag_scenes_for_render(Render *re)
1372 {
1373         bNode *node;
1374         Scene *sce;
1375         
1376         for (sce = re->main->scene.first; sce; sce = sce->id.next)
1377                 sce->id.flag &= ~LIB_DOIT;
1378         
1379         if (RE_GetCamera(re) && composite_needs_render(re->scene, 1))
1380                 re->scene->id.flag |= LIB_DOIT;
1381         
1382         if (re->scene->nodetree == NULL) return;
1383         
1384         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
1385         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1386                 if (node->type == CMP_NODE_R_LAYERS) {
1387                         if (node->id) {
1388                                 if (!MAIN_VERSION_ATLEAST(re->main, 265, 5)) {
1389                                         if (rlayer_node_uses_alpha(re->scene->nodetree, node)) {
1390                                                 Scene *scene = (Scene*) node->id;
1391
1392                                                 if (scene->r.alphamode != R_ALPHAPREMUL) {
1393                                                         BKE_reportf(re->reports, RPT_WARNING, "Setting scene %s alpha mode to Premul\n", scene->id.name + 2);
1394
1395                                                         /* also print, so feedback is immediate */
1396                                                         printf("2.66 versioning fix: setting scene %s alpha mode to Premul\n", scene->id.name + 2);
1397
1398                                                         scene->r.alphamode = R_ALPHAPREMUL;
1399                                                 }
1400                                         }
1401                                 }
1402
1403                                 if (node->id != (ID *)re->scene)
1404                                         node->id->flag |= LIB_DOIT;
1405                         }
1406                 }
1407         }
1408         
1409 }
1410
1411 static void ntree_render_scenes(Render *re)
1412 {
1413         bNode *node;
1414         int cfra = re->scene->r.cfra;
1415         int restore_scene = 0;
1416         
1417         if (re->scene->nodetree == NULL) return;
1418         
1419         tag_scenes_for_render(re);
1420         
1421         /* now foreach render-result node tagged we do a full render */
1422         /* results are stored in a way compisitor will find it */
1423         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1424                 if (node->type == CMP_NODE_R_LAYERS) {
1425                         if (node->id && node->id != (ID *)re->scene) {
1426                                 if (node->id->flag & LIB_DOIT) {
1427                                         Scene *scene = (Scene *)node->id;
1428
1429                                         render_scene(re, scene, cfra);
1430                                         restore_scene = (scene != re->scene);
1431                                         node->id->flag &= ~LIB_DOIT;
1432                                         
1433                                         nodeUpdate(re->scene->nodetree, node);
1434                                 }
1435                         }
1436                 }
1437         }
1438
1439         /* restore scene if we rendered another last */
1440         if (restore_scene)
1441                 BKE_scene_set_background(re->main, re->scene);
1442 }
1443
1444 /* bad call... need to think over proper method still */
1445 static void render_composit_stats(void *UNUSED(arg), char *str)
1446 {
1447         R.i.infostr = str;
1448         R.stats_draw(R.sdh, &R.i);
1449         R.i.infostr = NULL;
1450 }
1451
1452
1453 /* reads all buffers, calls optional composite, merges in first result->rectf */
1454 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
1455 {
1456         float *rectf, filt[3][3];
1457         int x, y, sample;
1458         
1459         /* interaction callbacks */
1460         if (ntree) {
1461                 ntree->stats_draw = render_composit_stats;
1462                 ntree->test_break = re->test_break;
1463                 ntree->progress = re->progress;
1464                 ntree->sdh = re->sdh;
1465                 ntree->tbh = re->tbh;
1466                 ntree->prh = re->prh;
1467         }
1468         
1469         /* filtmask needs it */
1470         R = *re;
1471         
1472         /* we accumulate in here */
1473         rectf = MEM_mapallocN(re->rectx * re->recty * sizeof(float) * 4, "fullsample rgba");
1474         
1475         for (sample = 0; sample < re->r.osa; sample++) {
1476                 Render *re1;
1477                 RenderResult rres;
1478                 int mask;
1479                 
1480                 /* enable full sample print */
1481                 R.i.curfsa = sample + 1;
1482                 
1483                 /* set all involved renders on the samplebuffers (first was done by render itself, but needs tagged) */
1484                 /* also function below assumes this */
1485                         
1486                 tag_scenes_for_render(re);
1487                 for (re1 = RenderGlobal.renderlist.first; re1; re1 = re1->next) {
1488                         if (re1->scene->id.flag & LIB_DOIT) {
1489                                 if (re1->r.scemode & R_FULL_SAMPLE) {
1490                                         if (sample) {
1491                                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1492                                                 render_result_exr_file_read(re1, sample);
1493                                                 BLI_rw_mutex_unlock(&re->resultmutex);
1494                                         }
1495                                         ntreeCompositTagRender(re1->scene); /* ensure node gets exec to put buffers on stack */
1496                                 }
1497                         }
1498                 }
1499                 
1500                 /* composite */
1501                 if (ntree) {
1502                         ntreeCompositTagRender(re->scene);
1503                         ntreeCompositTagAnimated(ntree);
1504                         
1505                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0, &re->scene->view_settings, &re->scene->display_settings);
1506                 }
1507                 
1508                 /* ensure we get either composited result or the active layer */
1509                 RE_AcquireResultImage(re, &rres);
1510                 
1511                 /* accumulate with filter, and clip */
1512                 mask = (1 << sample);
1513                 mask_array(mask, filt);
1514
1515                 for (y = 0; y < re->recty; y++) {
1516                         float *rf = rectf + 4 * y * re->rectx;
1517                         float *col = rres.rectf + 4 * y * re->rectx;
1518                                 
1519                         for (x = 0; x < re->rectx; x++, rf += 4, col += 4) {
1520                                 /* clamping to 1.0 is needed for correct AA */
1521                                 if (col[0] < 0.0f) col[0] = 0.0f; else if (col[0] > 1.0f) col[0] = 1.0f;
1522                                 if (col[1] < 0.0f) col[1] = 0.0f; else if (col[1] > 1.0f) col[1] = 1.0f;
1523                                 if (col[2] < 0.0f) col[2] = 0.0f; else if (col[2] > 1.0f) col[2] = 1.0f;
1524                                 
1525                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
1526                         }
1527                 }
1528                 
1529                 RE_ReleaseResultImage(re);
1530
1531                 /* show stuff */
1532                 if (sample != re->osa - 1) {
1533                         /* weak... the display callback wants an active renderlayer pointer... */
1534                         re->result->renlay = render_get_active_layer(re, re->result);
1535                         re->display_draw(re->ddh, re->result, NULL);
1536                 }
1537                 
1538                 if (re->test_break(re->tbh))
1539                         break;
1540         }
1541
1542         /* clamp alpha and RGB to 0..1 and 0..inf, can go outside due to filter */
1543         for (y = 0; y < re->recty; y++) {
1544                 float *rf = rectf + 4 * y * re->rectx;
1545                         
1546                 for (x = 0; x < re->rectx; x++, rf += 4) {
1547                         rf[0] = MAX2(rf[0], 0.0f);
1548                         rf[1] = MAX2(rf[1], 0.0f);
1549                         rf[2] = MAX2(rf[2], 0.0f);
1550                         CLAMP(rf[3], 0.0f, 1.0f);
1551                 }
1552         }
1553         
1554         /* clear interaction callbacks */
1555         if (ntree) {
1556                 ntree->stats_draw = NULL;
1557                 ntree->test_break = NULL;
1558                 ntree->progress = NULL;
1559                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1560         }
1561         
1562         /* disable full sample print */
1563         R.i.curfsa = 0;
1564         
1565         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1566         if (re->result->rectf)
1567                 MEM_freeN(re->result->rectf);
1568         re->result->rectf = rectf;
1569         BLI_rw_mutex_unlock(&re->resultmutex);
1570 }
1571
1572 /* called externally, via compositor */
1573 void RE_MergeFullSample(Render *re, Main *bmain, Scene *sce, bNodeTree *ntree)
1574 {
1575         Scene *scene;
1576         bNode *node;
1577
1578         /* default start situation */
1579         G.is_break = FALSE;
1580         
1581         re->main = bmain;
1582         re->scene = sce;
1583         re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
1584         
1585         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
1586         
1587         /* tag scenes unread */
1588         for (scene = re->main->scene.first; scene; scene = scene->id.next)
1589                 scene->id.flag |= LIB_DOIT;
1590         
1591         for (node = ntree->nodes.first; node; node = node->next) {
1592                 if (node->type == CMP_NODE_R_LAYERS) {
1593                         Scene *nodescene = (Scene *)node->id;
1594                         
1595                         if (nodescene == NULL) nodescene = sce;
1596                         if (nodescene->id.flag & LIB_DOIT) {
1597                                 nodescene->r.mode |= R_OSA; /* render struct needs tables */
1598                                 RE_ReadRenderResult(sce, nodescene);
1599                                 nodescene->id.flag &= ~LIB_DOIT;
1600                         }
1601                 }
1602         }
1603         
1604         /* own render result should be read/allocated */
1605         if (re->scene->id.flag & LIB_DOIT) {
1606                 RE_ReadRenderResult(re->scene, re->scene);
1607                 re->scene->id.flag &= ~LIB_DOIT;
1608         }
1609         
1610         /* and now we can draw (result is there) */
1611         re->display_init(re->dih, re->result);
1612         re->display_clear(re->dch, re->result);
1613         
1614         do_merge_fullsample(re, ntree);
1615 }
1616
1617 /* returns fully composited render-result on given time step (in RenderData) */
1618 static void do_render_composite_fields_blur_3d(Render *re)
1619 {
1620         bNodeTree *ntree = re->scene->nodetree;
1621         int update_newframe = 0;
1622         
1623         /* INIT seeding, compositor can use random texture */
1624         BLI_srandom(re->r.cfra);
1625         
1626         if (composite_needs_render(re->scene, 1)) {
1627                 /* save memory... free all cached images */
1628                 ntreeFreeCache(ntree);
1629                 
1630                 do_render_fields_blur_3d(re);
1631         }
1632         else {
1633                 /* ensure new result gets added, like for regular renders */
1634                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1635                 
1636                 render_result_free(re->result);
1637                 re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1638
1639                 BLI_rw_mutex_unlock(&re->resultmutex);
1640                 
1641                 /* scene render process already updates animsys */
1642                 update_newframe = 1;
1643         }
1644         
1645         /* swap render result */
1646         if (re->r.scemode & R_SINGLE_LAYER) {
1647                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1648                 render_result_single_layer_end(re);
1649                 BLI_rw_mutex_unlock(&re->resultmutex);
1650         }
1651         
1652         if (!re->test_break(re->tbh)) {
1653                 
1654                 if (ntree) {
1655                         ntreeCompositTagRender(re->scene);
1656                         ntreeCompositTagAnimated(ntree);
1657                 }
1658                 
1659                 if (ntree && re->scene->use_nodes && re->r.scemode & R_DOCOMP) {
1660                         /* checks if there are render-result nodes that need scene */
1661                         if ((re->r.scemode & R_SINGLE_LAYER) == 0)
1662                                 ntree_render_scenes(re);
1663                         
1664                         if (!re->test_break(re->tbh)) {
1665                                 ntree->stats_draw = render_composit_stats;
1666                                 ntree->test_break = re->test_break;
1667                                 ntree->progress = re->progress;
1668                                 ntree->sdh = re->sdh;
1669                                 ntree->tbh = re->tbh;
1670                                 ntree->prh = re->prh;
1671                                 
1672                                 /* in case it was never initialized */
1673                                 R.sdh = re->sdh;
1674                                 R.stats_draw = re->stats_draw;
1675                                 
1676                                 if (update_newframe)
1677                                         BKE_scene_update_for_newframe(re->main, re->scene, re->lay);
1678                                 
1679                                 if (re->r.scemode & R_FULL_SAMPLE)
1680                                         do_merge_fullsample(re, ntree);
1681                                 else {
1682                                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0, &re->scene->view_settings, &re->scene->display_settings);
1683                                 }
1684                                 
1685                                 ntree->stats_draw = NULL;
1686                                 ntree->test_break = NULL;
1687                                 ntree->progress = NULL;
1688                                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1689                         }
1690                 }
1691                 else if (re->r.scemode & R_FULL_SAMPLE)
1692                         do_merge_fullsample(re, NULL);
1693         }
1694
1695         /* weak... the display callback wants an active renderlayer pointer... */
1696         re->result->renlay = render_get_active_layer(re, re->result);
1697         re->display_draw(re->ddh, re->result, NULL);
1698 }
1699
1700 static void renderresult_stampinfo(Render *re)
1701 {
1702         RenderResult rres;
1703
1704         /* this is the basic trick to get the displayed float or char rect from render result */
1705         RE_AcquireResultImage(re, &rres);
1706         BKE_stamp_buf(re->scene, RE_GetCamera(re), (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
1707         RE_ReleaseResultImage(re);
1708 }
1709
1710 int RE_seq_render_active(Scene *scene, RenderData *rd)
1711 {
1712         Editing *ed;
1713         Sequence *seq;
1714
1715         ed = scene->ed;
1716         
1717         if (!(rd->scemode & R_DOSEQ) || !ed || !ed->seqbase.first)
1718                 return 0;
1719         
1720         for (seq = ed->seqbase.first; seq; seq = seq->next) {
1721                 if (seq->type != SEQ_TYPE_SOUND_RAM)
1722                         return 1;
1723         }
1724         
1725         return 0;
1726 }
1727
1728 static void do_render_seq(Render *re)
1729 {
1730         static int recurs_depth = 0;
1731         struct ImBuf *ibuf, *out;
1732         RenderResult *rr; /* don't assign re->result here as it might change during give_ibuf_seq */
1733         int cfra = re->r.cfra;
1734         SeqRenderData context;
1735
1736         re->i.cfra = cfra;
1737
1738         if (recurs_depth == 0) {
1739                 /* otherwise sequencer animation isn't updated */
1740                 BKE_animsys_evaluate_all_animation(re->main, re->scene, (float)cfra); // XXX, was BKE_scene_frame_get(re->scene)
1741         }
1742
1743         recurs_depth++;
1744
1745         if ((re->r.mode & R_BORDER) && (re->r.mode & R_CROP) == 0) {
1746                 /* if border rendering is used and cropping is disabled, final buffer should
1747                  * be as large as the whole frame */
1748                 context = BKE_sequencer_new_render_data(re->main, re->scene,
1749                                               re->winx, re->winy,
1750                                               100);
1751         }
1752         else {
1753                 context = BKE_sequencer_new_render_data(re->main, re->scene,
1754                                               re->result->rectx, re->result->recty,
1755                                               100);
1756         }
1757
1758         out = BKE_sequencer_give_ibuf(context, cfra, 0);
1759
1760         if (out) {
1761                 ibuf = IMB_dupImBuf(out);
1762                 IMB_freeImBuf(out);
1763                 BKE_sequencer_imbuf_from_sequencer_space(re->scene, ibuf);
1764         }
1765         else {
1766                 ibuf = NULL;
1767         }
1768
1769         recurs_depth--;
1770
1771         rr = re->result;
1772         
1773         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1774
1775         if (ibuf) {
1776                 /* copy ibuf into combined pixel rect */
1777                 render_result_rect_from_ibuf(rr, &re->r, ibuf);
1778                 
1779                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
1780                         Editing *ed = re->scene->ed;
1781                         if (ed)
1782                                 BKE_sequencer_free_imbuf(re->scene, &ed->seqbase, TRUE);
1783                 }
1784                 IMB_freeImBuf(ibuf);
1785         }
1786         else {
1787                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
1788                 render_result_rect_fill_zero(rr);
1789         }
1790
1791         BLI_rw_mutex_unlock(&re->resultmutex);
1792
1793         /* just in case this flag went missing at some point */
1794         re->r.scemode |= R_DOSEQ;
1795
1796         /* set overall progress of sequence rendering */
1797         if (re->r.efra != re->r.sfra)
1798                 re->progress(re->prh, (float)(cfra - re->r.sfra) / (re->r.efra - re->r.sfra));
1799         else
1800                 re->progress(re->prh, 1.0f);
1801
1802         /* would mark display buffers as invalid */
1803         re->display_draw(re->ddh, re->result, NULL);
1804 }
1805
1806 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1807
1808 /* main loop: doing sequence + fields + blur + 3d render + compositing */
1809 static void do_render_all_options(Render *re)
1810 {
1811         BKE_scene_camera_switch_update(re->scene);
1812
1813         re->i.starttime = PIL_check_seconds_timer();
1814
1815         /* ensure no images are in memory from previous animated sequences */
1816         BKE_image_all_free_anim_ibufs(re->r.cfra);
1817
1818         if (RE_engine_render(re, 1)) {
1819                 /* in this case external render overrides all */
1820         }
1821         else if (RE_seq_render_active(re->scene, &re->r)) {
1822                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
1823                 if (!re->test_break(re->tbh))
1824                         do_render_seq(re);
1825                 
1826                 re->stats_draw(re->sdh, &re->i);
1827                 re->display_draw(re->ddh, re->result, NULL);
1828         }
1829         else {
1830                 re->pool = BKE_image_pool_new();
1831
1832                 do_render_composite_fields_blur_3d(re);
1833
1834                 BKE_image_pool_free(re->pool);
1835                 re->pool = NULL;
1836         }
1837         
1838         re->i.lastframetime = PIL_check_seconds_timer() - re->i.starttime;
1839         
1840         re->stats_draw(re->sdh, &re->i);
1841         
1842         /* stamp image info here */
1843         if ((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
1844                 renderresult_stampinfo(re);
1845                 re->display_draw(re->ddh, re->result, NULL);
1846         }
1847 }
1848
1849 static int check_valid_camera(Scene *scene, Object *camera_override)
1850 {
1851         int check_comp = 1;
1852
1853         if (camera_override == NULL && scene->camera == NULL)
1854                 scene->camera = BKE_scene_camera_find(scene);
1855
1856         if (scene->r.scemode & R_DOSEQ) {
1857                 if (scene->ed) {
1858                         Sequence *seq = scene->ed->seqbase.first;
1859
1860                         check_comp = 0;
1861
1862                         while (seq) {
1863                                 if (seq->type == SEQ_TYPE_SCENE && seq->scene) {
1864                                         if (!seq->scene_camera) {
1865                                                 if (!seq->scene->camera && !BKE_scene_camera_find(seq->scene)) {
1866                                                         if (seq->scene == scene) {
1867                                                                 /* for current scene camera could be unneeded due to compisite nodes */
1868                                                                 check_comp = 1;
1869                                                         }
1870                                                         else {
1871                                                                 /* for other scenes camera is necessary */
1872                                                                 return 0;
1873                                                         }
1874                                                 }
1875                                         }
1876                                 }
1877
1878                                 seq = seq->next;
1879                         }
1880                 }
1881         }
1882
1883         if (check_comp) { /* no sequencer or sequencer depends on compositor */
1884                 if (scene->r.scemode & R_DOCOMP && scene->use_nodes) {
1885                         bNode *node = scene->nodetree->nodes.first;
1886
1887                         while (node) {
1888                                 if (node->type == CMP_NODE_R_LAYERS) {
1889                                         Scene *sce = node->id ? (Scene *)node->id : scene;
1890
1891                                         if (!sce->camera && !BKE_scene_camera_find(sce)) {
1892                                                 /* all render layers nodes need camera */
1893                                                 return 0;
1894                                         }
1895                                 }
1896
1897                                 node = node->next;
1898                         }
1899                 }
1900                 else {
1901                         return (camera_override != NULL || scene->camera != NULL);
1902                 }
1903         }
1904
1905         return 1;
1906 }
1907
1908 static int node_tree_has_composite_output(bNodeTree *ntree)
1909 {
1910         bNode *node;
1911
1912         for (node = ntree->nodes.first; node; node = node->next) {
1913                 if (node->type == CMP_NODE_COMPOSITE) {
1914                         return TRUE;
1915                 }
1916                 else if (node->type == NODE_GROUP) {
1917                         if (node->id) {
1918                                 if (node_tree_has_composite_output((bNodeTree *)node->id)) {
1919                                         return TRUE;
1920                                 }
1921                         }
1922                 }
1923         }
1924
1925         return FALSE;
1926 }
1927
1928 static int check_composite_output(Scene *scene)
1929 {
1930         return node_tree_has_composite_output(scene->nodetree);
1931 }
1932
1933 int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *reports)
1934 {
1935         SceneRenderLayer *srl;
1936         
1937         if (scene->r.mode & R_BORDER) {
1938                 if (scene->r.border.xmax <= scene->r.border.xmin ||
1939                     scene->r.border.ymax <= scene->r.border.ymin)
1940                 {
1941                         BKE_report(reports, RPT_ERROR, "No border area selected");
1942                         return 0;
1943                 }
1944         }
1945         
1946         if (scene->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
1947                 char str[FILE_MAX];
1948                 
1949                 render_result_exr_file_path(scene, "", 0, str);
1950                 
1951                 if (BLI_file_is_writable(str) == 0) {
1952                         BKE_report(reports, RPT_ERROR, "Cannot save render buffers, check the temp default path");
1953                         return 0;
1954                 }
1955                 
1956                 /* no fullsample and edge */
1957                 if ((scene->r.scemode & R_FULL_SAMPLE) && (scene->r.mode & R_EDGE)) {
1958                         BKE_report(reports, RPT_ERROR, "Full sample does not support edge enhance");
1959                         return 0;
1960                 }
1961                 
1962         }
1963         else
1964                 scene->r.scemode &= ~R_FULL_SAMPLE;  /* clear to be sure */
1965         
1966         if (scene->r.scemode & R_DOCOMP) {
1967                 if (scene->use_nodes) {
1968                         if (!scene->nodetree) {
1969                                 BKE_report(reports, RPT_ERROR, "No node tree in scene");
1970                                 return 0;
1971                         }
1972                         
1973                         if (!check_composite_output(scene)) {
1974                                 BKE_report(reports, RPT_ERROR, "No render output node in scene");
1975                                 return 0;
1976                         }
1977                         
1978                         if (scene->r.scemode & R_FULL_SAMPLE) {
1979                                 if (composite_needs_render(scene, 0) == 0) {
1980                                         BKE_report(reports, RPT_ERROR, "Full sample AA not supported without 3D rendering");
1981                                         return 0;
1982                                 }
1983                         }
1984                 }
1985         }
1986         
1987         /* check valid camera, without camera render is OK (compo, seq) */
1988         if (!check_valid_camera(scene, camera_override)) {
1989                 BKE_report(reports, RPT_ERROR, "No camera");
1990                 return 0;
1991         }
1992         
1993         /* get panorama & ortho, only after camera is set */
1994         BKE_camera_object_mode(&scene->r, camera_override ? camera_override : scene->camera);
1995
1996         /* forbidden combinations */
1997         if (scene->r.mode & R_PANORAMA) {
1998                 if (scene->r.mode & R_ORTHO) {
1999                         BKE_report(reports, RPT_ERROR, "No ortho render possible for panorama");
2000                         return 0;
2001                 }
2002         }
2003
2004         /* layer flag tests */
2005         if (scene->r.scemode & R_SINGLE_LAYER) {
2006                 srl = BLI_findlink(&scene->r.layers, scene->r.actlay);
2007                 /* force layer to be enabled */
2008                 srl->layflag &= ~SCE_LAY_DISABLE;
2009         }
2010         
2011         for (srl = scene->r.layers.first; srl; srl = srl->next)
2012                 if (!(srl->layflag & SCE_LAY_DISABLE))
2013                         break;
2014         if (srl == NULL) {
2015                 BKE_report(reports, RPT_ERROR, "All render layers are disabled");
2016                 return 0;
2017         }
2018
2019         return 1;
2020 }
2021
2022 static void validate_render_settings(Render *re)
2023 {
2024         if (re->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
2025                 /* no osa + fullsample won't work... */
2026                 if (re->r.osa == 0)
2027                         re->r.scemode &= ~R_FULL_SAMPLE;
2028         }
2029         else re->r.scemode &= ~R_FULL_SAMPLE;   /* clear to be sure */
2030
2031         if (RE_engine_is_external(re)) {
2032                 /* not supported yet */
2033                 re->r.scemode &= ~(R_FULL_SAMPLE);
2034                 re->r.mode &= ~(R_FIELDS | R_MBLUR);
2035         }
2036 }
2037
2038 static void update_physics_cache(Render *re, Scene *scene, int UNUSED(anim_init))
2039 {
2040         PTCacheBaker baker;
2041
2042         baker.main = re->main;
2043         baker.scene = scene;
2044         baker.pid = NULL;
2045         baker.bake = 0;
2046         baker.render = 1;
2047         baker.anim_init = 1;
2048         baker.quick_step = 1;
2049         baker.break_test = re->test_break;
2050         baker.break_data = re->tbh;
2051         baker.progressbar = NULL;
2052
2053         BKE_ptcache_bake(&baker);
2054 }
2055 /* evaluating scene options for general Blender render */
2056 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)
2057 {
2058         int winx, winy;
2059         rcti disprect;
2060         
2061         /* r.xsch and r.ysch has the actual view window size
2062          * r.border is the clipping rect */
2063         
2064         /* calculate actual render result and display size */
2065         winx = (scene->r.size * scene->r.xsch) / 100;
2066         winy = (scene->r.size * scene->r.ysch) / 100;
2067         
2068         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2069         if (scene->r.mode & R_BORDER) {
2070                 disprect.xmin = scene->r.border.xmin * winx;
2071                 disprect.xmax = scene->r.border.xmax * winx;
2072                 
2073                 disprect.ymin = scene->r.border.ymin * winy;
2074                 disprect.ymax = scene->r.border.ymax * winy;
2075         }
2076         else {
2077                 disprect.xmin = disprect.ymin = 0;
2078                 disprect.xmax = winx;
2079                 disprect.ymax = winy;
2080         }
2081         
2082         re->main = bmain;
2083         re->scene = scene;
2084         re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
2085         re->camera_override = camera_override;
2086         re->lay = lay;
2087         
2088         /* not too nice, but it survives anim-border render */
2089         if (anim) {
2090                 re->disprect = disprect;
2091                 return 1;
2092         }
2093         
2094         /* check all scenes involved */
2095         tag_scenes_for_render(re);
2096
2097         /*
2098          * Disabled completely for now,
2099          * can be later set as render profile option
2100          * and default for background render.
2101          */
2102         if (0) {
2103                 /* make sure dynamics are up to date */
2104                 update_physics_cache(re, scene, anim_init);
2105         }
2106         
2107         if (srl || scene->r.scemode & R_SINGLE_LAYER) {
2108                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2109                 render_result_single_layer_begin(re);
2110                 BLI_rw_mutex_unlock(&re->resultmutex);
2111         }
2112         
2113         RE_InitState(re, NULL, &scene->r, srl, winx, winy, &disprect);
2114         if (!re->ok)  /* if an error was printed, abort */
2115                 return 0;
2116         
2117         /* initstate makes new result, have to send changed tags around */
2118         ntreeCompositTagRender(re->scene);
2119
2120         validate_render_settings(re);
2121
2122         re->display_init(re->dih, re->result);
2123         re->display_clear(re->dch, re->result);
2124         
2125         return 1;
2126 }
2127
2128 void RE_SetReports(Render *re, ReportList *reports)
2129 {
2130         re->reports = reports;
2131 }
2132
2133 /* general Blender frame render call */
2134 void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int frame, const short write_still)
2135 {
2136         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2137         G.is_rendering = TRUE;
2138         
2139         scene->r.cfra = frame;
2140         
2141         if (render_initialize_from_main(re, bmain, scene, srl, camera_override, lay, 0, 0)) {
2142                 MEM_reset_peak_memory();
2143
2144                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2145
2146                 do_render_all_options(re);
2147
2148                 if (write_still && !G.is_break) {
2149                         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2150                                 /* operator checks this but in case its called from elsewhere */
2151                                 printf("Error: cant write single images with a movie format!\n");
2152                         }
2153                         else {
2154                                 char name[FILE_MAX];
2155                                 BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, &scene->r.im_format, scene->r.scemode & R_EXTENSION, FALSE);
2156
2157                                 /* reports only used for Movie */
2158                                 do_write_image_or_movie(re, bmain, scene, NULL, name);
2159                         }
2160                 }
2161
2162                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2163         }
2164
2165         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2166
2167         /* UGLY WARNING */
2168         G.is_rendering = FALSE;
2169 }
2170
2171 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override)
2172 {
2173         char name[FILE_MAX];
2174         RenderResult rres;
2175         Object *camera = RE_GetCamera(re);
2176         int ok = 1;
2177         
2178         RE_AcquireResultImage(re, &rres);
2179
2180         /* write movie or image */
2181         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2182                 int do_free = FALSE;
2183                 ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
2184
2185                 /* note; the way it gets 32 bits rects is weak... */
2186                 if (ibuf->rect == NULL) {
2187                         ibuf->rect = MEM_mapallocN(sizeof(int) * rres.rectx * rres.recty, "temp 32 bits rect");
2188                         ibuf->mall |= IB_rect;
2189                         RE_ResultGet32(re, ibuf->rect);
2190                         do_free = TRUE;
2191                 }
2192
2193
2194                 IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2195                                                     &scene->display_settings, &scene->r.im_format);
2196
2197                 ok = mh->append_movie(&re->r, scene->r.sfra, scene->r.cfra, (int *) ibuf->rect,
2198                                       ibuf->x, ibuf->y, re->reports);
2199                 if (do_free) {
2200                         MEM_freeN(ibuf->rect);
2201                         ibuf->rect = NULL;
2202                         ibuf->mall &= ~IB_rect;
2203                 }
2204
2205                 /* imbuf knows which rects are not part of ibuf */
2206                 IMB_freeImBuf(ibuf);
2207
2208                 printf("Append frame %d", scene->r.cfra);
2209         }
2210         else {
2211                 if (name_override)
2212                         BLI_strncpy(name, name_override, sizeof(name));
2213                 else
2214                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, &scene->r.im_format, scene->r.scemode & R_EXTENSION, TRUE);
2215                 
2216                 if (re->r.im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
2217                         if (re->result) {
2218                                 RE_WriteRenderResult(re->reports, re->result, name, scene->r.im_format.exr_codec);
2219                                 printf("Saved: %s", name);
2220                         }
2221                 }
2222                 else {
2223                         ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
2224
2225                         IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2226                                                             &scene->display_settings, &scene->r.im_format);
2227
2228                         ok = BKE_imbuf_write_stamp(scene, camera, ibuf, name, &scene->r.im_format);
2229                         
2230                         if (ok == 0) {
2231                                 printf("Render error: cannot save %s\n", name);
2232                         }
2233                         else printf("Saved: %s", name);
2234                         
2235                         /* optional preview images for exr */
2236                         if (ok && scene->r.im_format.imtype == R_IMF_IMTYPE_OPENEXR && (scene->r.im_format.flag & R_IMF_FLAG_PREVIEW_JPG)) {
2237                                 ImageFormatData imf = scene->r.im_format;
2238                                 imf.imtype = R_IMF_IMTYPE_JPEG90;
2239
2240                                 if (BLI_testextensie(name, ".exr"))
2241                                         name[strlen(name) - 4] = 0;
2242                                 BKE_add_image_extension(name, &imf);
2243                                 ibuf->planes = 24;
2244
2245                                 IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2246                                                                     &scene->display_settings, &imf);
2247
2248                                 BKE_imbuf_write_stamp(scene, camera, ibuf, name, &imf);
2249                                 printf("\nSaved: %s", name);
2250                         }
2251                         
2252                         /* imbuf knows which rects are not part of ibuf */
2253                         IMB_freeImBuf(ibuf);
2254                 }
2255         }
2256         
2257         RE_ReleaseResultImage(re);
2258
2259         BLI_timestr(re->i.lastframetime, name);
2260         printf(" Time: %s", name);
2261
2262         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
2263
2264         fputc('\n', stdout);
2265         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2266
2267         return ok;
2268 }
2269
2270 /* saves images to disk */
2271 void RE_BlenderAnim(Render *re, Main *bmain, Scene *scene, Object *camera_override, unsigned int lay, int sfra, int efra, int tfra)
2272 {
2273         bMovieHandle *mh = BKE_movie_handle_get(scene->r.im_format.imtype);
2274         int cfrao = scene->r.cfra;
2275         int nfra, totrendered = 0, totskipped = 0;
2276         
2277         /* do not fully call for each frame, it initializes & pops output window */
2278         if (!render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 0, 1))
2279                 return;
2280         
2281         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2282         /* is also set by caller renderwin.c */
2283         G.is_rendering = TRUE;
2284
2285         re->flag |= R_ANIMATION;
2286
2287         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2288                 if (!mh->start_movie(scene, &re->r, re->rectx, re->recty, re->reports))
2289                         G.is_break = TRUE;
2290
2291         if (mh->get_next_frame) {
2292                 while (!(G.is_break == 1)) {
2293                         int nf = mh->get_next_frame(&re->r, re->reports);
2294                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2295                                 scene->r.cfra = re->r.cfra = nf;
2296
2297                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2298
2299                                 do_render_all_options(re);
2300                                 totrendered++;
2301
2302                                 if (re->test_break(re->tbh) == 0) {
2303                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2304                                                 G.is_break = TRUE;
2305                                 }
2306
2307                                 if (G.is_break == FALSE) {
2308                                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2309                                 }
2310                         }
2311                         else {
2312                                 if (re->test_break(re->tbh)) {
2313                                         G.is_break = TRUE;
2314                                 }
2315                         }
2316                 }
2317         }
2318         else {
2319                 for (nfra = sfra, scene->r.cfra = sfra; scene->r.cfra <= efra; scene->r.cfra++) {
2320                         char name[FILE_MAX];
2321                         
2322                         /* only border now, todo: camera lens. (ton) */
2323                         render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 1, 0);
2324
2325                         if (nfra != scene->r.cfra) {
2326                                 /*
2327                                  * Skip this frame, but update for physics and particles system.
2328                                  * From convertblender.c:
2329                                  * in localview, lamps are using normal layers, objects only local bits.
2330                                  */
2331                                 unsigned int updatelay;
2332
2333                                 if (re->lay & 0xFF000000)
2334                                         updatelay = re->lay & 0xFF000000;
2335                                 else
2336                                         updatelay = re->lay;
2337
2338                                 BKE_scene_update_for_newframe(bmain, scene, updatelay);
2339                                 continue;
2340                         }
2341                         else
2342                                 nfra += tfra;
2343
2344                         /* Touch/NoOverwrite options are only valid for image's */
2345                         if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2346                                 if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2347                                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, &scene->r.im_format, scene->r.scemode & R_EXTENSION, TRUE);
2348
2349                                 if (scene->r.mode & R_NO_OVERWRITE && BLI_exists(name)) {
2350                                         printf("skipping existing frame \"%s\"\n", name);
2351                                         totskipped++;
2352                                         continue;
2353                                 }
2354                                 if (scene->r.mode & R_TOUCH && !BLI_exists(name)) {
2355                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2356                                         BLI_file_touch(name);
2357                                 }
2358                         }
2359
2360                         re->r.cfra = scene->r.cfra;     /* weak.... */
2361
2362                         /* run callbacs before rendering, before the scene is updated */
2363                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2364
2365                         
2366                         do_render_all_options(re);
2367                         totrendered++;
2368                         
2369                         if (re->test_break(re->tbh) == 0) {
2370                                 if (!G.is_break)
2371                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2372                                                 G.is_break = TRUE;
2373                         }
2374                         else
2375                                 G.is_break = TRUE;
2376                 
2377                         if (G.is_break == TRUE) {
2378                                 /* remove touched file */
2379                                 if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2380                                         if (scene->r.mode & R_TOUCH && BLI_exists(name) && BLI_file_size(name) == 0) {
2381                                                 BLI_delete(name, 0, 0);
2382                                         }
2383                                 }
2384                                 
2385                                 break;
2386                         }
2387
2388                         if (G.is_break == FALSE) {
2389                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2390                         }
2391                 }
2392         }
2393         
2394         /* end movie */
2395         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2396                 mh->end_movie();
2397         
2398         if (totskipped && totrendered == 0)
2399                 BKE_report(re->reports, RPT_INFO, "No frames rendered, skipped to not overwrite");
2400
2401         scene->r.cfra = cfrao;
2402
2403         re->flag &= ~R_ANIMATION;
2404
2405         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2406
2407         /* UGLY WARNING */
2408         G.is_rendering = FALSE;
2409 }
2410
2411 void RE_PreviewRender(Render *re, Main *bmain, Scene *sce)
2412 {
2413         Object *camera;
2414         int winx, winy;
2415
2416         winx = (sce->r.size * sce->r.xsch) / 100;
2417         winy = (sce->r.size * sce->r.ysch) / 100;
2418
2419         RE_InitState(re, NULL, &sce->r, NULL, winx, winy, NULL);
2420
2421         re->pool = BKE_image_pool_new();
2422
2423         re->main = bmain;
2424         re->scene = sce;
2425         re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
2426         re->lay = sce->lay;
2427
2428         camera = RE_GetCamera(re);
2429         RE_SetCamera(re, camera);
2430
2431         do_render_3d(re);
2432
2433         BKE_image_pool_free(re->pool);
2434         re->pool = NULL;
2435 }
2436
2437 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2438
2439 /* only the temp file! */
2440 int RE_ReadRenderResult(Scene *scene, Scene *scenode)
2441 {
2442         Render *re;
2443         int winx, winy, success;
2444         rcti disprect;
2445         
2446         /* calculate actual render result and display size */
2447         winx = (scene->r.size * scene->r.xsch) / 100;
2448         winy = (scene->r.size * scene->r.ysch) / 100;
2449         
2450         /* only in movie case we render smaller part */
2451         if (scene->r.mode & R_BORDER) {
2452                 disprect.xmin = scene->r.border.xmin * winx;
2453                 disprect.xmax = scene->r.border.xmax * winx;
2454                 
2455                 disprect.ymin = scene->r.border.ymin * winy;
2456                 disprect.ymax = scene->r.border.ymax * winy;
2457         }
2458         else {
2459                 disprect.xmin = disprect.ymin = 0;
2460                 disprect.xmax = winx;
2461                 disprect.ymax = winy;
2462         }
2463         
2464         if (scenode)
2465                 scene = scenode;
2466         
2467         /* get render: it can be called from UI with draw callbacks */
2468         re = RE_GetRender(scene->id.name);
2469         if (re == NULL)
2470                 re = RE_NewRender(scene->id.name);
2471         RE_InitState(re, NULL, &scene->r, NULL, winx, winy, &disprect);
2472         re->scene = scene;
2473         re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
2474         
2475         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2476         success = render_result_exr_file_read(re, 0);
2477         BLI_rw_mutex_unlock(&re->resultmutex);
2478
2479         return success;
2480 }
2481
2482 void RE_set_max_threads(int threads)
2483 {
2484         if (threads == 0) {
2485                 RenderGlobal.threads = BLI_system_thread_count();
2486         }
2487         else if (threads >= 1 && threads <= BLENDER_MAX_THREADS) {
2488                 RenderGlobal.threads = threads;
2489         }
2490         else {
2491                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2492         }
2493 }
2494
2495 void RE_init_threadcount(Render *re) 
2496 {
2497         if (RenderGlobal.threads >= 1) { /* only set as an arg in background mode */
2498                 re->r.threads = MIN2(RenderGlobal.threads, BLENDER_MAX_THREADS);
2499         }
2500         else if ((re->r.mode & R_FIXED_THREADS) == 0 || RenderGlobal.threads == 0) { /* Automatic threads */
2501                 re->r.threads = BLI_system_thread_count();
2502         }
2503 }
2504
2505 /* loads in image into a result, size must match
2506  * x/y offsets are only used on a partial copy when dimensions don't match */
2507 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, const char *filename, int x, int y)
2508 {
2509         /* OCIO_TODO: assume layer was saved in defaule color space */
2510         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect, NULL);
2511
2512         if (ibuf && (ibuf->rect || ibuf->rect_float)) {
2513                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
2514                         if (ibuf->rect_float == NULL)
2515                                 IMB_float_from_rect(ibuf);
2516
2517                         memcpy(layer->rectf, ibuf->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2518                 }
2519                 else {
2520                         if ((ibuf->x - x >= layer->rectx) && (ibuf->y - y >= layer->recty)) {
2521                                 ImBuf *ibuf_clip;
2522
2523                                 if (ibuf->rect_float == NULL)
2524                                         IMB_float_from_rect(ibuf);
2525
2526                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat);
2527                                 if (ibuf_clip) {
2528                                         IMB_rectcpy(ibuf_clip, ibuf, 0, 0, x, y, layer->rectx, layer->recty);
2529
2530                                         memcpy(layer->rectf, ibuf_clip->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2531                                         IMB_freeImBuf(ibuf_clip);
2532                                 }
2533                                 else {
2534                                         BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'", filename);
2535                                 }
2536                         }
2537                         else {
2538                                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'", filename);
2539                         }
2540                 }
2541
2542                 IMB_freeImBuf(ibuf);
2543         }
2544         else {
2545                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
2546         }
2547 }
2548
2549 void RE_result_load_from_file(RenderResult *result, ReportList *reports, const char *filename)
2550 {
2551         if (!render_result_exr_file_read_path(result, NULL, filename)) {
2552                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
2553                 return;
2554         }
2555 }
2556
2557 const float default_envmap_layout[] = { 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1 };
2558
2559 int RE_WriteEnvmapResult(struct ReportList *reports, Scene *scene, EnvMap *env, const char *relpath, const char imtype, float layout[12])
2560 {
2561         ImageFormatData imf;
2562         ImBuf *ibuf = NULL;
2563         int ok;
2564         int dx;
2565         int maxX = 0, maxY = 0, i = 0;
2566         char filepath[FILE_MAX];
2567
2568         if (env->cube[1] == NULL) {
2569                 BKE_report(reports, RPT_ERROR, "There is no generated environment map available to save");
2570                 return 0;
2571         }
2572
2573         imf = scene->r.im_format;
2574         imf.imtype = imtype;
2575
2576         dx = env->cube[1]->x;
2577
2578         if (env->type == ENV_CUBE) {
2579                 for (i = 0; i < 12; i += 2) {
2580                         maxX = max_ii(maxX, (int)layout[i] + 1);
2581                         maxY = max_ii(maxY, (int)layout[i + 1] + 1);
2582                 }
2583
2584                 ibuf = IMB_allocImBuf(maxX * dx, maxY * dx, 24, IB_rectfloat);
2585
2586                 for (i = 0; i < 12; i += 2)
2587                         if (layout[i] > -1 && layout[i + 1] > -1)
2588                                 IMB_rectcpy(ibuf, env->cube[i / 2], layout[i] * dx, layout[i + 1] * dx, 0, 0, dx, dx);
2589         }
2590         else if (env->type == ENV_PLANE) {
2591                 ibuf = IMB_allocImBuf(dx, dx, 24, IB_rectfloat);
2592                 IMB_rectcpy(ibuf, env->cube[1], 0, 0, 0, 0, dx, dx);
2593         }
2594         else {
2595                 BKE_report(reports, RPT_ERROR, "Invalid environment map type");
2596                 return 0;
2597         }
2598
2599         IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings, &scene->display_settings, &imf);
2600
2601         /* to save, we first get absolute path */
2602         BLI_strncpy(filepath, relpath, sizeof(filepath));
2603         BLI_path_abs(filepath, G.main->name);
2604
2605         ok = BKE_imbuf_write(ibuf, filepath, &imf);
2606
2607         IMB_freeImBuf(ibuf);
2608
2609         if (ok) {
2610                 return TRUE;
2611         }
2612         else {
2613                 BKE_report(reports, RPT_ERROR, "Error writing environment map");
2614                 return FALSE;
2615         }
2616 }
2617