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