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