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