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