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