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