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