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