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