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