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