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