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