1a33a1abb8dd1eb7f8af4f49566fce2cb153dd20
[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_utildefines.h"
68
69 #include "PIL_time.h"
70 #include "IMB_imbuf.h"
71 #include "IMB_imbuf_types.h"
72
73 #include "intern/openexr/openexr_multi.h"
74
75 #include "RE_pipeline.h"
76
77 /* internal */
78 #include "render_types.h"
79 #include "renderpipeline.h"
80 #include "renderdatabase.h"
81 #include "rendercore.h"
82 #include "envmap.h"
83 #include "initrender.h"
84 #include "shadbuf.h"
85 #include "pixelblending.h"
86 #include "zbuf.h"
87
88
89 /* render flow
90
91 1) Initialize state
92 - state data, tables
93 - movie/image file init
94 - everything that doesn't change during animation
95
96 2) Initialize data
97 - camera, world, matrices
98 - make render verts, faces, halos, strands
99 - everything can change per frame/field
100
101 3) Render Processor
102 - multiple layers
103 - tiles, rect, baking
104 - layers/tiles optionally to disk or directly in Render Result
105
106 4) Composite Render Result
107 - also read external files etc
108
109 5) Image Files
110 - save file or append in movie
111
112 */
113
114
115 /* ********* globals ******** */
116
117 /* here we store all renders */
118 static struct {
119         ListBase renderlist;
120
121         /* commandline thread override */
122         int threads;
123 } RenderGlobal = {{NULL, NULL}, -1}; 
124
125 /* hardcopy of current render, used while rendering for speed */
126 Render R;
127
128 /* ********* alloc and free ******** */
129
130 static int do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh, ReportList *reports, const char *name_override);
131
132 static volatile int g_break= 0;
133 static int thread_break(void *UNUSED(arg))
134 {
135         return g_break;
136 }
137
138 /* default callbacks, set in each new render */
139 static void result_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr)) {}
140 static void result_rcti_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect)) {}
141 static void stats_nothing(void *UNUSED(arg), RenderStats *UNUSED(rs)) {}
142 static void float_nothing(void *UNUSED(arg), float UNUSED(val)) {}
143 static void print_error(void *UNUSED(arg), const char *str) {printf("ERROR: %s\n", str);}
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         re->error= print_error;
1193         if(G.background)
1194                 re->stats_draw= stats_background;
1195         else
1196                 re->stats_draw= stats_nothing;
1197         /* clear callback handles */
1198         re->dih= re->dch= re->ddh= re->sdh= re->prh= re->tbh= re->erh= NULL;
1199 }
1200
1201 /* only call this while you know it will remove the link too */
1202 void RE_FreeRender(Render *re)
1203 {
1204         BLI_rw_mutex_end(&re->resultmutex);
1205         
1206         free_renderdata_tables(re);
1207         free_sample_tables(re);
1208         
1209         RE_FreeRenderResult(re->result);
1210         RE_FreeRenderResult(re->pushedresult);
1211         
1212         BLI_remlink(&RenderGlobal.renderlist, re);
1213         MEM_freeN(re);
1214 }
1215
1216 /* exit blender */
1217 void RE_FreeAllRender(void)
1218 {
1219         while(RenderGlobal.renderlist.first) {
1220                 RE_FreeRender(RenderGlobal.renderlist.first);
1221         }
1222 }
1223
1224 /* ********* initialize state ******** */
1225
1226
1227 /* what doesn't change during entire render sequence */
1228 /* disprect is optional, if NULL it assumes full window render */
1229 void RE_InitState(Render *re, Render *source, RenderData *rd, SceneRenderLayer *srl, int winx, int winy, rcti *disprect)
1230 {
1231         re->ok= TRUE;   /* maybe flag */
1232         
1233         re->i.starttime= PIL_check_seconds_timer();
1234         re->r= *rd;             /* hardcopy */
1235         
1236         re->winx= winx;
1237         re->winy= winy;
1238         if(disprect) {
1239                 re->disprect= *disprect;
1240                 re->rectx= disprect->xmax-disprect->xmin;
1241                 re->recty= disprect->ymax-disprect->ymin;
1242         }
1243         else {
1244                 re->disprect.xmin= re->disprect.ymin= 0;
1245                 re->disprect.xmax= winx;
1246                 re->disprect.ymax= winy;
1247                 re->rectx= winx;
1248                 re->recty= winy;
1249         }
1250         
1251         if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
1252                                                                                   (re->rectx < 16 || re->recty < 16) )) {
1253                 re->error(re->erh, "Image too small");
1254                 re->ok= 0;
1255                 return;
1256         }
1257
1258         if((re->r.mode & (R_OSA))==0)
1259                 re->r.scemode &= ~R_FULL_SAMPLE;
1260
1261 #ifdef WITH_OPENEXR
1262         if(re->r.scemode & R_FULL_SAMPLE)
1263                 re->r.scemode |= R_EXR_TILE_FILE;       /* enable automatic */
1264
1265         /* Until use_border is made compatible with save_buffers/full_sample, render without the later instead of not rendering at all.*/
1266         if(re->r.mode & R_BORDER) 
1267         {
1268                 re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1269         }
1270
1271 #else
1272         /* can't do this without openexr support */
1273         re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1274 #endif
1275         
1276         /* fullsample wants uniform osa levels */
1277         if(source && (re->r.scemode & R_FULL_SAMPLE)) {
1278                 /* but, if source has no full sample we disable it */
1279                 if((source->r.scemode & R_FULL_SAMPLE)==0)
1280                         re->r.scemode &= ~R_FULL_SAMPLE;
1281                 else
1282                         re->r.osa= re->osa= source->osa;
1283         }
1284         else {
1285                 /* check state variables, osa? */
1286                 if(re->r.mode & (R_OSA)) {
1287                         re->osa= re->r.osa;
1288                         if(re->osa>16) re->osa= 16;
1289                 }
1290                 else re->osa= 0;
1291         }
1292         
1293         if (srl) {
1294                 int index = BLI_findindex(&re->r.layers, srl);
1295                 if (index != -1) {
1296                         re->r.actlay = index;
1297                         re->r.scemode |= R_SINGLE_LAYER;
1298                 }
1299         }
1300                 
1301         /* always call, checks for gamma, gamma tables and jitter too */
1302         make_sample_tables(re); 
1303         
1304         /* if preview render, we try to keep old result */
1305         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1306
1307         if(re->r.scemode & R_PREVIEWBUTS) {
1308                 if(re->result && re->result->rectx==re->rectx && re->result->recty==re->recty);
1309                 else {
1310                         RE_FreeRenderResult(re->result);
1311                         re->result= NULL;
1312                 }
1313         }
1314         else {
1315                 
1316                 /* make empty render result, so display callbacks can initialize */
1317                 RE_FreeRenderResult(re->result);
1318                 re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1319                 re->result->rectx= re->rectx;
1320                 re->result->recty= re->recty;
1321         }
1322
1323         BLI_rw_mutex_unlock(&re->resultmutex);
1324         
1325         /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1326         re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1327         
1328         re->mblur_offs = re->field_offs = 0.f;
1329         
1330         RE_init_threadcount(re);
1331 }
1332
1333 /* part of external api, not called for regular render pipeline */
1334 void RE_SetDispRect (struct Render *re, rcti *disprect)
1335 {
1336         re->disprect= *disprect;
1337         re->rectx= disprect->xmax-disprect->xmin;
1338         re->recty= disprect->ymax-disprect->ymin;
1339         
1340         /* initialize render result */
1341         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1342
1343         RE_FreeRenderResult(re->result);
1344         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1345
1346         BLI_rw_mutex_unlock(&re->resultmutex);
1347 }
1348
1349 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1350 {
1351         /* re->ok flag? */
1352         
1353         re->viewplane= *viewplane;
1354         re->clipsta= clipsta;
1355         re->clipend= clipend;
1356         re->r.mode &= ~R_ORTHO;
1357
1358         perspective_m4( re->winmat,re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
1359         
1360 }
1361
1362 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1363 {
1364         /* re->ok flag? */
1365         
1366         re->viewplane= *viewplane;
1367         re->clipsta= clipsta;
1368         re->clipend= clipend;
1369         re->r.mode |= R_ORTHO;
1370
1371         orthographic_m4( re->winmat,re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
1372 }
1373
1374 void RE_SetView(Render *re, float mat[][4])
1375 {
1376         /* re->ok flag? */
1377         copy_m4_m4(re->viewmat, mat);
1378         invert_m4_m4(re->viewinv, re->viewmat);
1379 }
1380
1381 /* image and movie output has to move to either imbuf or kernel */
1382 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1383 {
1384         re->display_init= f;
1385         re->dih= handle;
1386 }
1387 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1388 {
1389         re->display_clear= f;
1390         re->dch= handle;
1391 }
1392 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
1393 {
1394         re->display_draw= f;
1395         re->ddh= handle;
1396 }
1397 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
1398 {
1399         re->stats_draw= f;
1400         re->sdh= handle;
1401 }
1402 void RE_progress_cb(Render *re, void *handle, void (*f)(void *handle, float))
1403 {
1404         re->progress= f;
1405         re->prh= handle;
1406 }
1407
1408 void RE_draw_lock_cb(Render *re, void *handle, void (*f)(void *handle, int i))
1409 {
1410         re->draw_lock= f;
1411         re->tbh= handle;
1412 }
1413
1414 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
1415 {
1416         re->test_break= f;
1417         re->tbh= handle;
1418 }
1419 void RE_error_cb(Render *re, void *handle, void (*f)(void *handle, const char *str))
1420 {
1421         re->error= f;
1422         re->erh= handle;
1423 }
1424
1425
1426 /* ********* add object data (later) ******** */
1427
1428 /* object is considered fully prepared on correct time etc */
1429 /* includes lights */
1430 void RE_AddObject(Render *UNUSED(re), Object *UNUSED(ob))
1431 {
1432         
1433 }
1434
1435 /* *************************************** */
1436
1437 static int render_display_draw_enabled(Render *re)
1438 {
1439         /* don't show preprocess for previewrender sss */
1440         if(re->sss_points)
1441                 return !(re->r.scemode & R_PREVIEWBUTS);
1442         else
1443                 return 1;
1444 }
1445
1446 /* allocate osa new results for samples */
1447 static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
1448 {
1449         int a;
1450         
1451         if(re->osa==0)
1452                 return new_render_result(re, partrct, crop, RR_USEMEM);
1453         
1454         for(a=0; a<re->osa; a++) {
1455                 RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
1456                 BLI_addtail(lb, rr);
1457                 rr->sample_nr= a;
1458         }
1459         
1460         return lb->first;
1461 }
1462
1463
1464 /* the main thread call, renders an entire part */
1465 static void *do_part_thread(void *pa_v)
1466 {
1467         RenderPart *pa= pa_v;
1468         
1469         /* need to return nicely all parts on esc */
1470         if(R.test_break(R.tbh)==0) {
1471                 
1472                 if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
1473                         pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
1474                 else
1475                         pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1476
1477                 if(R.sss_points)
1478                         zbufshade_sss_tile(pa);
1479                 else if(R.osa)
1480                         zbufshadeDA_tile(pa);
1481                 else
1482                         zbufshade_tile(pa);
1483                 
1484                 /* merge too on break! */
1485                 if(R.result->exrhandle) {
1486                         RenderResult *rr, *rrpart;
1487                         
1488                         for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
1489                                 save_render_result_tile(rr, rrpart);
1490                         
1491                 }
1492                 else if(render_display_draw_enabled(&R)) {
1493                         /* on break, don't merge in result for preview renders, looks nicer */
1494                         if(R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS));
1495                         else merge_render_result(R.result, pa->result);
1496                 }
1497         }
1498         
1499         pa->ready= 1;
1500         
1501         return NULL;
1502 }
1503
1504 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1505 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1506 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1507 float panorama_pixel_rot(Render *re)
1508 {
1509         float psize, phi, xfac;
1510         float borderfac= (float)(re->disprect.xmax - re->disprect.xmin) / (float)re->winx;
1511         
1512         /* size of 1 pixel mapped to viewplane coords */
1513         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)(re->winx);
1514         /* angle of a pixel */
1515         phi= atan(psize/re->clipsta);
1516         
1517         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1518         xfac= borderfac*((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1519         xfac= atan(0.5f*xfac/re->clipsta); 
1520         /* and how much the same viewplane angle is wrapped */
1521         psize= 0.5f*phi*((float)re->partx);
1522         
1523         /* the ratio applied to final per-pixel angle */
1524         phi*= xfac/psize;
1525         
1526         return phi;
1527 }
1528
1529 /* call when all parts stopped rendering, to find the next Y slice */
1530 /* if slice found, it rotates the dbase */
1531 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1532 {
1533         RenderPart *pa, *best= NULL;
1534         
1535         *minx= re->winx;
1536         
1537         /* most left part of the non-rendering parts */
1538         for(pa= re->parts.first; pa; pa= pa->next) {
1539                 if(pa->ready==0 && pa->nr==0) {
1540                         if(pa->disprect.xmin < *minx) {
1541                                 best= pa;
1542                                 *minx= pa->disprect.xmin;
1543                         }
1544                 }
1545         }
1546                         
1547         if(best) {
1548                 float phi= panorama_pixel_rot(re);
1549
1550                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1551                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)(re->winx);
1552
1553                 /* shift viewplane */
1554                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1555                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1556                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1557                 copy_m4_m4(R.winmat, re->winmat);
1558                 
1559                 /* rotate database according to part coordinates */
1560                 project_renderdata(re, projectverto, 1, -R.panodxp*phi, 1);
1561                 R.panosi= sin(R.panodxp*phi);
1562                 R.panoco= cos(R.panodxp*phi);
1563         }
1564         return best;
1565 }
1566
1567 static RenderPart *find_next_part(Render *re, int minx)
1568 {
1569         RenderPart *pa, *best= NULL;
1570
1571         /* long long int's needed because of overflow [#24414] */
1572         long long int centx=re->winx/2, centy=re->winy/2, tot=1;
1573         long long int mindist= (long long int)re->winx * (long long int)re->winy;
1574         
1575         /* find center of rendered parts, image center counts for 1 too */
1576         for(pa= re->parts.first; pa; pa= pa->next) {
1577                 if(pa->ready) {
1578                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1579                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1580                         tot++;
1581                 }
1582         }
1583         centx/=tot;
1584         centy/=tot;
1585         
1586         /* closest of the non-rendering parts */
1587         for(pa= re->parts.first; pa; pa= pa->next) {
1588                 if(pa->ready==0 && pa->nr==0) {
1589                         long long int distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1590                         long long int disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1591                         distx= (long long int)sqrt(distx*distx + disty*disty);
1592                         if(distx<mindist) {
1593                                 if(re->r.mode & R_PANORAMA) {
1594                                         if(pa->disprect.xmin==minx) {
1595                                                 best= pa;
1596                                                 mindist= distx;
1597                                         }
1598                                 }
1599                                 else {
1600                                         best= pa;
1601                                         mindist= distx;
1602                                 }
1603                         }
1604                 }
1605         }
1606         return best;
1607 }
1608
1609 static void print_part_stats(Render *re, RenderPart *pa)
1610 {
1611         char str[64];
1612         
1613         BLI_snprintf(str, sizeof(str), "%s, Part %d-%d", re->scene->id.name+2, pa->nr, re->i.totpart);
1614         re->i.infostr= str;
1615         re->stats_draw(re->sdh, &re->i);
1616         re->i.infostr= NULL;
1617 }
1618
1619 /* make osa new results for samples */
1620 static RenderResult *new_full_sample_buffers_exr(Render *re)
1621 {
1622         int a;
1623         
1624         for(a=0; a<re->osa; a++) {
1625                 RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
1626                 BLI_addtail(&re->fullresult, rr);
1627                 rr->sample_nr= a;
1628         }
1629         
1630         return re->fullresult.first;
1631 }
1632
1633 static void threaded_tile_processor(Render *re)
1634 {
1635         ListBase threads;
1636         RenderPart *pa, *nextpa;
1637         rctf viewplane= re->viewplane;
1638         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1639         
1640         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1641
1642         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
1643         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
1644                 RE_FreeRenderResult(re->result);
1645         
1646                 if(re->sss_points && render_display_draw_enabled(re))
1647                         re->result= new_render_result(re, &re->disprect, 0, 0);
1648                 else if(re->r.scemode & R_FULL_SAMPLE)
1649                         re->result= new_full_sample_buffers_exr(re);
1650                 else
1651                         re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
1652         }
1653
1654         BLI_rw_mutex_unlock(&re->resultmutex);
1655         
1656         if(re->result==NULL)
1657                 return;
1658         
1659         /* warning; no return here without closing exr file */
1660         
1661         initparts(re);
1662
1663         if(re->result->exrhandle) {
1664                 RenderResult *rr;
1665                 char str[FILE_MAX];
1666                 
1667                 for(rr= re->result; rr; rr= rr->next) {
1668                         render_unique_exr_name(re, str, rr->sample_nr);
1669                 
1670                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1671                         IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1672                 }
1673         }
1674         
1675         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1676         
1677         /* assuming no new data gets added to dbase... */
1678         R= *re;
1679         
1680         /* set threadsafe break */
1681         R.test_break= thread_break;
1682         
1683         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1684         if(re->r.mode & R_PANORAMA)
1685                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1686         else
1687                 nextpa= find_next_part(re, 0);
1688         
1689         while(rendering) {
1690                 
1691                 if(re->test_break(re->tbh))
1692                         PIL_sleep_ms(50);
1693                 else if(nextpa && BLI_available_threads(&threads)) {
1694                         drawtimer= 0;
1695                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1696                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1697                         BLI_insert_thread(&threads, nextpa);
1698
1699                         nextpa= find_next_part(re, minx);
1700                 }
1701                 else if(re->r.mode & R_PANORAMA) {
1702                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1703                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1704                         else {
1705                                 PIL_sleep_ms(50);
1706                                 drawtimer++;
1707                         }
1708                 }
1709                 else {
1710                         PIL_sleep_ms(50);
1711                         drawtimer++;
1712                 }
1713                 
1714                 /* check for ready ones to display, and if we need to continue */
1715                 rendering= 0;
1716                 hasdrawn= 0;
1717                 for(pa= re->parts.first; pa; pa= pa->next) {
1718                         if(pa->ready) {
1719                                 
1720                                 BLI_remove_thread(&threads, pa);
1721                                 
1722                                 if(pa->result) {
1723                                         if(render_display_draw_enabled(re))
1724                                                 re->display_draw(re->ddh, pa->result, NULL);
1725                                         print_part_stats(re, pa);
1726                                         
1727                                         free_render_result(&pa->fullresult, pa->result);
1728                                         pa->result= NULL;
1729                                         re->i.partsdone++;
1730                                         re->progress(re->prh, re->i.partsdone / (float)re->i.totpart);
1731                                         hasdrawn= 1;
1732                                 }
1733                         }
1734                         else {
1735                                 rendering= 1;
1736                                 if(pa->nr && pa->result && drawtimer>20) {
1737                                         if(render_display_draw_enabled(re))
1738                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
1739                                         hasdrawn= 1;
1740                                 }
1741                         }
1742                 }
1743                 if(hasdrawn)
1744                         drawtimer= 0;
1745
1746                 /* on break, wait for all slots to get freed */
1747                 if( (g_break=re->test_break(re->tbh)) && BLI_available_threads(&threads)==re->r.threads)
1748                         rendering= 0;
1749                 
1750         }
1751         
1752         if(re->result->exrhandle) {
1753                 RenderResult *rr;
1754
1755                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1756                 save_empty_result_tiles(re);
1757                 
1758                 for(rr= re->result; rr; rr= rr->next) {
1759                         IMB_exr_close(rr->exrhandle);
1760                         rr->exrhandle= NULL;
1761                 }
1762                 
1763                 free_render_result(&re->fullresult, re->result);
1764                 re->result= NULL;
1765
1766                 BLI_rw_mutex_unlock(&re->resultmutex);
1767                 
1768                 read_render_result(re, 0);
1769         }
1770         
1771         /* unset threadsafety */
1772         g_break= 0;
1773         
1774         BLI_end_threads(&threads);
1775         freeparts(re);
1776         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1777 }
1778
1779 /* currently only called by preview renders and envmap */
1780 void RE_TileProcessor(Render *re)
1781 {
1782         threaded_tile_processor(re);
1783 }
1784
1785 /* ************  This part uses API, for rendering Blender scenes ********** */
1786
1787 static int external_render_3d(Render *re, int do_all);
1788
1789 static void do_render_3d(Render *re)
1790 {
1791         /* try external */
1792         if(external_render_3d(re, 0))
1793                 return;
1794
1795         /* internal */
1796         
1797 //      re->cfra= cfra; /* <- unused! */
1798         re->scene->r.subframe = re->mblur_offs + re->field_offs;
1799         
1800         /* lock drawing in UI during data phase */
1801         if(re->draw_lock)
1802                 re->draw_lock(re->dlh, 1);
1803         
1804         /* make render verts/faces/halos/lamps */
1805         if(render_scene_needs_vector(re))
1806                 RE_Database_FromScene_Vectors(re, re->main, re->scene, re->lay);
1807         else
1808            RE_Database_FromScene(re, re->main, re->scene, re->lay, 1);
1809         
1810         /* clear UI drawing locks */
1811         if(re->draw_lock)
1812                 re->draw_lock(re->dlh, 0);
1813         
1814         threaded_tile_processor(re);
1815         
1816         /* do left-over 3d post effects (flares) */
1817         if(re->flag & R_HALO)
1818                 if(!re->test_break(re->tbh))
1819                         add_halo_flare(re);
1820         
1821         /* free all render verts etc */
1822         RE_Database_Free(re);
1823         
1824         re->scene->r.subframe = 0.f;
1825 }
1826
1827 /* called by blur loop, accumulate RGBA key alpha */
1828 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
1829 {
1830         float mfac= 1.0f - blurfac;
1831         int a, b, stride= 4*rr->rectx;
1832         int len= stride*sizeof(float);
1833         
1834         for(a=0; a<rr->recty; a++) {
1835                 if(blurfac==1.0f) {
1836                         memcpy(rectf, rectf1, len);
1837                 }
1838                 else {
1839                         float *rf= rectf, *rf1= rectf1;
1840                         
1841                         for( b= rr->rectx; b>0; b--, rf+=4, rf1+=4) {
1842                                 if(rf1[3]<0.01f)
1843                                         rf[3]= mfac*rf[3];
1844                                 else if(rf[3]<0.01f) {
1845                                         rf[0]= rf1[0];
1846                                         rf[1]= rf1[1];
1847                                         rf[2]= rf1[2];
1848                                         rf[3]= blurfac*rf1[3];
1849                                 }
1850                                 else {
1851                                         rf[0]= mfac*rf[0] + blurfac*rf1[0];
1852                                         rf[1]= mfac*rf[1] + blurfac*rf1[1];
1853                                         rf[2]= mfac*rf[2] + blurfac*rf1[2];
1854                                         rf[3]= mfac*rf[3] + blurfac*rf1[3];
1855                                 }                               
1856                         }
1857                 }
1858                 rectf+= stride;
1859                 rectf1+= stride;
1860         }
1861 }
1862
1863 /* called by blur loop, accumulate renderlayers */
1864 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1865 {
1866         float mfac= 1.0f - blurfac;
1867         int a, b, stride= channels*rr->rectx;
1868         int len= stride*sizeof(float);
1869         
1870         for(a=0; a<rr->recty; a++) {
1871                 if(blurfac==1.0f) {
1872                         memcpy(rectf, rectf1, len);
1873                 }
1874                 else {
1875                         float *rf= rectf, *rf1= rectf1;
1876                         
1877                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1878                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1879                         }
1880                 }
1881                 rectf+= stride;
1882                 rectf1+= stride;
1883         }
1884 }
1885
1886
1887 /* called by blur loop, accumulate renderlayers */
1888 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1889 {
1890         RenderLayer *rl, *rl1;
1891         RenderPass *rpass, *rpass1;
1892         
1893         rl1= brr->layers.first;
1894         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1895                 
1896                 /* combined */
1897                 if(rl->rectf && rl1->rectf) {
1898                         if(key_alpha)
1899                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1900                         else
1901                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1902                 }
1903                 
1904                 /* passes are allocated in sync */
1905                 rpass1= rl1->passes.first;
1906                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1907                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1908                 }
1909         }
1910 }
1911
1912 /* main blur loop, can be called by fields too */
1913 static void do_render_blur_3d(Render *re)
1914 {
1915         RenderResult *rres;
1916         float blurfac;
1917         int blur= re->r.mblur_samples;
1918         
1919         /* create accumulation render result */
1920         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1921         
1922         /* do the blur steps */
1923         while(blur--) {
1924                 re->mblur_offs = re->r.blurfac*((float)(re->r.mblur_samples-blur))/(float)re->r.mblur_samples;
1925                 
1926                 re->i.curblur= re->r.mblur_samples-blur;        /* stats */
1927                 
1928                 do_render_3d(re);
1929                 
1930                 blurfac= 1.0f/(float)(re->r.mblur_samples-blur);
1931                 
1932                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1933                 if(re->test_break(re->tbh)) break;
1934         }
1935         
1936         /* swap results */
1937         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1938         RE_FreeRenderResult(re->result);
1939         re->result= rres;
1940         BLI_rw_mutex_unlock(&re->resultmutex);
1941         
1942         re->mblur_offs = 0.0f;
1943         re->i.curblur= 0;       /* stats */
1944         
1945         /* weak... the display callback wants an active renderlayer pointer... */
1946         re->result->renlay= render_get_active_layer(re, re->result);
1947         re->display_draw(re->ddh, re->result, NULL);    
1948 }
1949
1950
1951 /* function assumes rectf1 and rectf2 to be half size of rectf */
1952 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1953 {
1954         int a, stride= channels*rr->rectx;
1955         int len= stride*sizeof(float);
1956         
1957         for(a=0; a<rr->recty; a+=2) {
1958                 memcpy(rectf, rectf1, len);
1959                 rectf+= stride;
1960                 rectf1+= stride;
1961                 memcpy(rectf, rectf2, len);
1962                 rectf+= stride;
1963                 rectf2+= stride;
1964         }
1965 }
1966
1967 /* merge render results of 2 fields */
1968 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1969 {
1970         RenderLayer *rl, *rl1, *rl2;
1971         RenderPass *rpass, *rpass1, *rpass2;
1972         
1973         rl1= rr1->layers.first;
1974         rl2= rr2->layers.first;
1975         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1976                 
1977                 /* combined */
1978                 if(rl->rectf && rl1->rectf && rl2->rectf)
1979                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1980                 
1981                 /* passes are allocated in sync */
1982                 rpass1= rl1->passes.first;
1983                 rpass2= rl2->passes.first;
1984                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1985                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1986                 }
1987         }
1988 }
1989
1990
1991 /* interleaves 2 frames */
1992 static void do_render_fields_3d(Render *re)
1993 {
1994         Object *camera= RE_GetCamera(re);
1995         RenderResult *rr1, *rr2= NULL;
1996         
1997         /* no render result was created, we can safely halve render y */
1998         re->winy /= 2;
1999         re->recty /= 2;
2000         re->disprect.ymin /= 2;
2001         re->disprect.ymax /= 2;
2002         
2003         re->i.curfield= 1;      /* stats */
2004         
2005         /* first field, we have to call camera routine for correct aspect and subpixel offset */
2006         RE_SetCamera(re, camera);
2007         if(re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE)==0)
2008                 do_render_blur_3d(re);
2009         else
2010                 do_render_3d(re);
2011
2012         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2013         rr1= re->result;
2014         re->result= NULL;
2015         BLI_rw_mutex_unlock(&re->resultmutex);
2016         
2017         /* second field */
2018         if(!re->test_break(re->tbh)) {
2019                 
2020                 re->i.curfield= 2;      /* stats */
2021                 
2022                 re->flag |= R_SEC_FIELD;
2023                 if((re->r.mode & R_FIELDSTILL)==0) {
2024                         re->field_offs = 0.5f;
2025                 }
2026                 RE_SetCamera(re, camera);
2027                 if(re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE)==0)
2028                         do_render_blur_3d(re);
2029                 else
2030                         do_render_3d(re);
2031                 re->flag &= ~R_SEC_FIELD;
2032                 
2033                 re->field_offs = 0.0f;
2034                 
2035                 rr2= re->result;
2036         }
2037         
2038         /* allocate original height new buffers */
2039         re->winy *= 2;
2040         re->recty *= 2;
2041         re->disprect.ymin *= 2;
2042         re->disprect.ymax *= 2;
2043
2044         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2045         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2046
2047         if(rr2) {
2048                 if(re->r.mode & R_ODDFIELD)
2049                         merge_renderresult_fields(re->result, rr2, rr1);
2050                 else
2051                         merge_renderresult_fields(re->result, rr1, rr2);
2052                 
2053                 RE_FreeRenderResult(rr2);
2054         }
2055
2056         RE_FreeRenderResult(rr1);
2057         
2058         re->i.curfield= 0;      /* stats */
2059         
2060         /* weak... the display callback wants an active renderlayer pointer... */
2061         re->result->renlay= render_get_active_layer(re, re->result);
2062
2063         BLI_rw_mutex_unlock(&re->resultmutex);
2064
2065         re->display_draw(re->ddh, re->result, NULL);
2066 }
2067
2068 static void load_backbuffer(Render *re)
2069 {
2070         if(re->r.alphamode == R_ADDSKY) {
2071                 ImBuf *ibuf;
2072                 char name[256];
2073                 
2074                 BLI_strncpy(name, re->r.backbuf, sizeof(name));
2075                 BLI_path_abs(name, re->main->name);
2076                 BLI_path_frame(name, re->r.cfra, 0);
2077                 
2078                 if(re->backbuf) {
2079                         re->backbuf->id.us--;
2080                         if(re->backbuf->id.us<1)
2081                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
2082                 }
2083                 
2084                 re->backbuf= BKE_add_image_file(name);
2085                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
2086                 if(ibuf==NULL) {
2087                         // error() doesnt work with render window open
2088                         //error("No backbuf there!");
2089                         printf("Error: No backbuf %s\n", name);
2090                 }
2091                 else {
2092                         if (re->r.mode & R_FIELDS)
2093                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
2094                 }
2095         }
2096 }
2097
2098 /* main render routine, no compositing */
2099 static void do_render_fields_blur_3d(Render *re)
2100 {
2101         Object *camera= RE_GetCamera(re);
2102         /* also check for camera here */
2103         if(camera == NULL) {
2104                 printf("ERROR: Cannot render, no camera\n");
2105                 G.afbreek= 1;
2106                 return;
2107         }
2108         
2109         /* backbuffer initialize */
2110         if(re->r.bufflag & 1)
2111                 load_backbuffer(re);
2112
2113         /* now use renderdata and camera to set viewplane */
2114         RE_SetCamera(re, camera);
2115         
2116         if(re->r.mode & R_FIELDS)
2117                 do_render_fields_3d(re);
2118         else if(re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE)==0)
2119                 do_render_blur_3d(re);
2120         else
2121                 do_render_3d(re);
2122         
2123         /* when border render, check if we have to insert it in black */
2124         if(re->result) {
2125                 if(re->r.mode & R_BORDER) {
2126                         if((re->r.mode & R_CROP)==0) {
2127                                 RenderResult *rres;
2128                                 
2129                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2130
2131                                 /* sub-rect for merge call later on */
2132                                 re->result->tilerect= re->disprect;
2133                                 
2134                                 /* this copying sequence could become function? */
2135                                 /* weak is: it chances disprect from border */
2136                                 re->disprect.xmin= re->disprect.ymin= 0;
2137                                 re->disprect.xmax= re->winx;
2138                                 re->disprect.ymax= re->winy;
2139                                 re->rectx= re->winx;
2140                                 re->recty= re->winy;
2141                                 
2142                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2143                                 
2144                                 merge_render_result(rres, re->result);
2145                                 RE_FreeRenderResult(re->result);
2146                                 re->result= rres;
2147                                 
2148                                 /* weak... the display callback wants an active renderlayer pointer... */
2149                                 re->result->renlay= render_get_active_layer(re, re->result);
2150                                 
2151                                 BLI_rw_mutex_unlock(&re->resultmutex);
2152                 
2153                                 re->display_init(re->dih, re->result);
2154                                 re->display_draw(re->ddh, re->result, NULL);
2155                         }
2156                         else {
2157                                 /* set offset (again) for use in compositor, disprect was manipulated. */
2158                                 re->result->xof= 0;
2159                                 re->result->yof= 0;
2160                         }
2161                 }
2162         }
2163 }
2164
2165
2166 /* within context of current Render *re, render another scene.
2167    it uses current render image size and disprect, but doesn't execute composite
2168 */
2169 static void render_scene(Render *re, Scene *sce, int cfra)
2170 {
2171         Render *resc= RE_NewRender(sce->id.name);
2172         int winx= re->winx, winy= re->winy;
2173         
2174         sce->r.cfra= cfra;
2175
2176         scene_camera_switch_update(sce);
2177
2178         /* exception: scene uses own size (unfinished code) */
2179         if(0) {
2180                 winx= (sce->r.size*sce->r.xsch)/100;
2181                 winy= (sce->r.size*sce->r.ysch)/100;
2182         }
2183         
2184         /* initial setup */
2185         RE_InitState(resc, re, &sce->r, NULL, winx, winy, &re->disprect);
2186         
2187         /* still unsure entity this... */
2188         resc->main= re->main;
2189         resc->scene= sce;
2190         resc->lay= sce->lay;
2191         
2192         /* ensure scene has depsgraph, base flags etc OK */
2193         set_scene_bg(re->main, sce);
2194
2195         /* copy callbacks */
2196         resc->display_draw= re->display_draw;
2197         resc->ddh= re->ddh;
2198         resc->test_break= re->test_break;
2199         resc->tbh= re->tbh;
2200         resc->stats_draw= re->stats_draw;
2201         resc->sdh= re->sdh;
2202         
2203         do_render_fields_blur_3d(resc);
2204 }
2205
2206 static void tag_scenes_for_render(Render *re)
2207 {
2208         bNode *node;
2209         Scene *sce;
2210         
2211         for(sce= re->main->scene.first; sce; sce= sce->id.next)
2212                 sce->id.flag &= ~LIB_DOIT;
2213         
2214         re->scene->id.flag |= LIB_DOIT;
2215         
2216         if(re->scene->nodetree==NULL) return;
2217         
2218         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
2219         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2220                 if(node->type==CMP_NODE_R_LAYERS) {
2221                         if(node->id) {
2222                                 if(node->id != (ID *)re->scene)
2223                                         node->id->flag |= LIB_DOIT;
2224                         }
2225                 }
2226         }
2227         
2228 }
2229
2230 static void ntree_render_scenes(Render *re)
2231 {
2232         bNode *node;
2233         int cfra= re->scene->r.cfra;
2234         int restore_scene= 0;
2235         
2236         if(re->scene->nodetree==NULL) return;
2237         
2238         tag_scenes_for_render(re);
2239         
2240         /* now foreach render-result node tagged we do a full render */
2241         /* results are stored in a way compisitor will find it */
2242         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2243                 if(node->type==CMP_NODE_R_LAYERS) {
2244                         if(node->id && node->id != (ID *)re->scene) {
2245                                 if(node->id->flag & LIB_DOIT) {
2246                                         Scene *scene = (Scene*)node->id;
2247
2248                                         render_scene(re, scene, cfra);
2249                                         restore_scene= (scene != re->scene);
2250                                         node->id->flag &= ~LIB_DOIT;
2251                                 }
2252                         }
2253                 }
2254         }
2255
2256         /* restore scene if we rendered another last */
2257         if(restore_scene)
2258                 set_scene_bg(re->main, re->scene);
2259 }
2260
2261 /* helper call to detect if theres a composite with render-result node */
2262 static int composite_needs_render(Scene *sce)
2263 {
2264         bNodeTree *ntree= sce->nodetree;
2265         bNode *node;
2266         
2267         if(ntree==NULL) return 1;
2268         if(sce->use_nodes==0) return 1;
2269         if((sce->r.scemode & R_DOCOMP)==0) return 1;
2270                 
2271         for(node= ntree->nodes.first; node; node= node->next) {
2272                 if(node->type==CMP_NODE_R_LAYERS)
2273                         if(node->id==NULL || node->id==&sce->id)
2274                                 return 1;
2275         }
2276         return 0;
2277 }
2278
2279 /* bad call... need to think over proper method still */
2280 static void render_composit_stats(void *UNUSED(arg), char *str)
2281 {
2282         R.i.infostr= str;
2283         R.stats_draw(R.sdh, &R.i);
2284         R.i.infostr= NULL;
2285 }
2286
2287
2288 /* reads all buffers, calls optional composite, merges in first result->rectf */
2289 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
2290 {
2291         float *rectf, filt[3][3];
2292         int sample;
2293         
2294         /* filtmask needs it */
2295         R= *re;
2296         
2297         /* we accumulate in here */
2298         rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
2299         
2300         for(sample=0; sample<re->r.osa; sample++) {
2301                 RenderResult rres;
2302                 int x, y, mask;
2303                 
2304                 /* set all involved renders on the samplebuffers (first was done by render itself) */
2305                 /* also function below assumes this */
2306                 if(sample) {
2307                         Render *re1;
2308                         
2309                         tag_scenes_for_render(re);
2310                         for(re1= RenderGlobal.renderlist.first; re1; re1= re1->next) {
2311                                 if(re1->scene->id.flag & LIB_DOIT) {
2312                                         if(re1->r.scemode & R_FULL_SAMPLE) {
2313                                                 read_render_result(re1, sample);
2314                                                 ntreeCompositTagRender(re1->scene); /* ensure node gets exec to put buffers on stack */
2315                                         }
2316                                 }
2317                         }
2318                 }
2319
2320                 /* composite */
2321                 if(ntree) {
2322                         ntreeCompositTagRender(re->scene);
2323                         ntreeCompositTagAnimated(ntree);
2324                         
2325                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2326                 }
2327                 
2328                 /* ensure we get either composited result or the active layer */
2329                 RE_AcquireResultImage(re, &rres);
2330                 
2331                 /* accumulate with filter, and clip */
2332                 mask= (1<<sample);
2333                 mask_array(mask, filt);
2334
2335                 for(y=0; y<re->recty; y++) {
2336                         float *rf= rectf + 4*y*re->rectx;
2337                         float *col= rres.rectf + 4*y*re->rectx;
2338                                 
2339                         for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
2340                                 /* clamping to 1.0 is needed for correct AA */
2341                                 if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
2342                                 if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
2343                                 if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
2344                                 
2345                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
2346                         }
2347                 }
2348                 
2349                 RE_ReleaseResultImage(re);
2350
2351                 /* show stuff */
2352                 if(sample!=re->osa-1) {
2353                         /* weak... the display callback wants an active renderlayer pointer... */
2354                         re->result->renlay= render_get_active_layer(re, re->result);
2355                         re->display_draw(re->ddh, re->result, NULL);
2356                 }
2357                 
2358                 if(re->test_break(re->tbh))
2359                         break;
2360         }
2361         
2362         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2363         if(re->result->rectf) 
2364                 MEM_freeN(re->result->rectf);
2365         re->result->rectf= rectf;
2366         BLI_rw_mutex_unlock(&re->resultmutex);
2367 }
2368
2369 /* called externally, via compositor */
2370 void RE_MergeFullSample(Render *re, Main *bmain, Scene *sce, bNodeTree *ntree)
2371 {
2372         Scene *scene;
2373         bNode *node;
2374
2375         /* default start situation */
2376         G.afbreek= 0;
2377         
2378         re->main= bmain;
2379         re->scene= sce;
2380         
2381         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
2382         
2383         /* tag scenes unread */
2384         for(scene= re->main->scene.first; scene; scene= scene->id.next) 
2385                 scene->id.flag |= LIB_DOIT;
2386         
2387         for(node= ntree->nodes.first; node; node= node->next) {
2388                 if(node->type==CMP_NODE_R_LAYERS) {
2389                         Scene *nodescene= (Scene *)node->id;
2390                         
2391                         if(nodescene==NULL) nodescene= sce;
2392                         if(nodescene->id.flag & LIB_DOIT) {
2393                                 nodescene->r.mode |= R_OSA;     /* render struct needs tables */
2394                                 RE_ReadRenderResult(sce, nodescene);
2395                                 nodescene->id.flag &= ~LIB_DOIT;
2396                         }
2397                 }
2398         }
2399         
2400         /* own render result should be read/allocated */
2401         if(re->scene->id.flag & LIB_DOIT)
2402                 RE_ReadRenderResult(re->scene, re->scene);
2403         
2404         /* and now we can draw (result is there) */
2405         re->display_init(re->dih, re->result);
2406         re->display_clear(re->dch, re->result);
2407         
2408         do_merge_fullsample(re, ntree);
2409 }
2410
2411 /* returns fully composited render-result on given time step (in RenderData) */
2412 static void do_render_composite_fields_blur_3d(Render *re)
2413 {
2414         bNodeTree *ntree= re->scene->nodetree;
2415         int update_newframe=0;
2416         
2417         /* INIT seeding, compositor can use random texture */
2418         BLI_srandom(re->r.cfra);
2419         
2420         if(composite_needs_render(re->scene)) {
2421                 /* save memory... free all cached images */
2422                 ntreeFreeCache(ntree);
2423                 
2424                 do_render_fields_blur_3d(re);
2425         } else {
2426                 /* scene render process already updates animsys */
2427                 update_newframe = 1;
2428         }
2429         
2430         /* swap render result */
2431         if(re->r.scemode & R_SINGLE_LAYER)
2432                 pop_render_result(re);
2433         
2434         if(!re->test_break(re->tbh)) {
2435                 
2436                 if(ntree) {
2437                         ntreeCompositTagRender(re->scene);
2438                         ntreeCompositTagAnimated(ntree);
2439                 }
2440                 
2441                 if(ntree && re->r.scemode & R_DOCOMP) {
2442                         /* checks if there are render-result nodes that need scene */
2443                         if((re->r.scemode & R_SINGLE_LAYER)==0)
2444                                 ntree_render_scenes(re);
2445                         
2446                         if(!re->test_break(re->tbh)) {
2447                                 ntree->stats_draw= render_composit_stats;
2448                                 ntree->test_break= re->test_break;
2449                                 ntree->progress= re->progress;
2450                                 ntree->sdh= re->sdh;
2451                                 ntree->tbh= re->tbh;
2452                                 ntree->prh= re->prh;
2453                                 
2454                                 /* in case it was never initialized */
2455                                 R.sdh= re->sdh;
2456                                 R.stats_draw= re->stats_draw;
2457                                 
2458                                 if (update_newframe)
2459                                         scene_update_for_newframe(re->main, re->scene, re->lay);
2460                                 
2461                                 if(re->r.scemode & R_FULL_SAMPLE) 
2462                                         do_merge_fullsample(re, ntree);
2463                                 else {
2464                                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2465                                 }
2466                                 
2467                                 ntree->stats_draw= NULL;
2468                                 ntree->test_break= NULL;
2469                                 ntree->progress= NULL;
2470                                 ntree->tbh= ntree->sdh= ntree->prh= NULL;
2471                         }
2472                 }
2473                 else if(re->r.scemode & R_FULL_SAMPLE)
2474                         do_merge_fullsample(re, NULL);
2475         }
2476
2477         /* weak... the display callback wants an active renderlayer pointer... */
2478         re->result->renlay= render_get_active_layer(re, re->result);
2479         re->display_draw(re->ddh, re->result, NULL);
2480 }
2481
2482 static void renderresult_stampinfo(Render *re)
2483 {
2484         RenderResult rres;
2485
2486         /* this is the basic trick to get the displayed float or char rect from render result */
2487         RE_AcquireResultImage(re, &rres);
2488         BKE_stamp_buf(re->scene, RE_GetCamera(re), (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
2489         RE_ReleaseResultImage(re);
2490 }
2491
2492 static int seq_render_active(Render *re)
2493 {
2494         Editing *ed;
2495         Sequence *seq;
2496
2497         ed = re->scene->ed;
2498         
2499         if (!(re->r.scemode & R_DOSEQ) || !ed || !ed->seqbase.first)
2500                 return 0;
2501         
2502         for (seq= ed->seqbase.first; seq; seq= seq->next) {
2503                 if (seq->type != SEQ_SOUND)
2504                         return 1;
2505         }
2506         
2507         return 0;
2508 }
2509
2510 static void do_render_seq(Render * re)
2511 {
2512         static int recurs_depth = 0;
2513         struct ImBuf *ibuf;
2514         RenderResult *rr; /* don't assign re->result here as it might change during give_ibuf_seq */
2515         int cfra = re->r.cfra;
2516         SeqRenderData context;
2517
2518         re->i.cfra= cfra;
2519
2520         if(recurs_depth==0) {
2521                 /* otherwise sequencer animation isnt updated */
2522                 BKE_animsys_evaluate_all_animation(re->main, (float)cfra); // XXX, was BKE_curframe(re->scene)
2523         }
2524
2525         recurs_depth++;
2526
2527         context = seq_new_render_data(re->main, re->scene,
2528                                       re->result->rectx, re->result->recty, 
2529                                       100);
2530
2531         ibuf = give_ibuf_seq(context, cfra, 0);
2532
2533         recurs_depth--;
2534
2535         rr = re->result;
2536         
2537         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2538
2539         if(ibuf) {
2540                 if(ibuf->rect_float) {
2541                         if (!rr->rectf)
2542                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
2543                         
2544                         /* color management: when off ensure rectf is non-lin, since thats what the internal
2545                          * render engine delivers */
2546                         if(re->r.color_mgt_flag & R_COLOR_MANAGEMENT) {
2547                                 if(ibuf->profile == IB_PROFILE_LINEAR_RGB)
2548                                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2549                                 else
2550                                         srgb_to_linearrgb_rgba_rgba_buf(rr->rectf, ibuf->rect_float, rr->rectx*rr->recty);
2551                                         
2552                         }
2553                         else {
2554                                 if(ibuf->profile != IB_PROFILE_LINEAR_RGB)
2555                                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2556                                 else
2557                                         linearrgb_to_srgb_rgba_rgba_buf(rr->rectf, ibuf->rect_float, rr->rectx*rr->recty);
2558                         }
2559                         
2560                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
2561                            can hang around when sequence render has rendered a 32 bits one before */
2562                         if(rr->rect32) {
2563                                 MEM_freeN(rr->rect32);
2564                                 rr->rect32= NULL;
2565                         }
2566                 }
2567                 else if(ibuf->rect) {
2568                         if (!rr->rect32)
2569                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2570
2571                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
2572
2573                         /* if (ibuf->zbuf) { */
2574                         /*      if (R.rectz) freeN(R.rectz); */
2575                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
2576                         /* } */
2577
2578                         /* Same things as above, old rectf can hang around from previous render. */
2579                         if(rr->rectf) {
2580                                 MEM_freeN(rr->rectf);
2581                                 rr->rectf= NULL;
2582                         }
2583                 }
2584                 
2585                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
2586                         Editing * ed = re->scene->ed;
2587                         if (ed) {
2588                                 free_imbuf_seq(re->scene, &ed->seqbase, TRUE, TRUE);
2589                         }
2590                 }
2591                 IMB_freeImBuf(ibuf);
2592         }
2593         else {
2594                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
2595                 if (rr->rectf)
2596                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
2597                 else if (rr->rect32)
2598                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
2599                 else
2600                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2601         }
2602
2603         BLI_rw_mutex_unlock(&re->resultmutex);
2604
2605         /* just in case this flag went missing at some point */
2606         re->r.scemode |= R_DOSEQ;
2607 }
2608
2609 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2610
2611 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2612 static void do_render_all_options(Render *re)
2613 {
2614         scene_camera_switch_update(re->scene);
2615
2616         re->i.starttime= PIL_check_seconds_timer();
2617
2618         /* ensure no images are in memory from previous animated sequences */
2619         BKE_image_all_free_anim_ibufs(re->r.cfra);
2620
2621         if(external_render_3d(re, 1)) {
2622                 /* in this case external render overrides all */
2623         }
2624         else if(seq_render_active(re)) {
2625                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2626                 if(!re->test_break(re->tbh)) 
2627                         do_render_seq(re);
2628                 
2629                 re->stats_draw(re->sdh, &re->i);
2630                 re->display_draw(re->ddh, re->result, NULL);
2631         }
2632         else {
2633                 do_render_composite_fields_blur_3d(re);
2634         }
2635         
2636         /* for UI only */
2637         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2638         renderresult_add_names(re->result);
2639         BLI_rw_mutex_unlock(&re->resultmutex);
2640         
2641         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2642         
2643         re->stats_draw(re->sdh, &re->i);
2644         
2645         /* stamp image info here */
2646         if((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
2647                 renderresult_stampinfo(re);
2648                 re->display_draw(re->ddh, re->result, NULL);
2649         }
2650 }
2651
2652 static int check_valid_camera(Scene *scene, Object *camera_override)
2653 {
2654         int check_comp= 1;
2655
2656         if (camera_override == NULL && scene->camera == NULL)
2657                 scene->camera= scene_find_camera(scene);
2658
2659         if(scene->r.scemode&R_DOSEQ) {
2660                 if(scene->ed) {
2661                         Sequence *seq= scene->ed->seqbase.first;
2662
2663                         check_comp= 0;
2664
2665                         while(seq) {
2666                                 if(seq->type == SEQ_SCENE) {
2667                                         if(!seq->scene_camera) {
2668                                                 if(!seq->scene->camera && !scene_find_camera(seq->scene)) {
2669                                                         if(seq->scene == scene) {
2670                                                                 /* for current scene camera could be unneeded due to compisite nodes */
2671                                                                 check_comp= 1;
2672                                                         } else {
2673                                                                 /* for other scenes camera is necessary */
2674                                                                 return 0;
2675                                                         }
2676                                                 }
2677                                         }
2678                                 }
2679
2680                                 seq= seq->next;
2681                         }
2682                 }
2683         }
2684
2685         if(check_comp) { /* no sequencer or sequencer depends on compositor */
2686                 if(scene->r.scemode&R_DOCOMP && scene->use_nodes) {
2687                         bNode *node= scene->nodetree->nodes.first;
2688
2689                         while(node) {
2690                                 if(node->type == CMP_NODE_R_LAYERS) {
2691                                         Scene *sce= node->id ? (Scene*)node->id : scene;
2692
2693                                         if(!sce->camera && !scene_find_camera(sce)) {
2694                                                 /* all render layers nodes need camera */
2695                                                 return 0;
2696                                         }
2697                                 }
2698
2699                                 node= node->next;
2700                         }
2701                 } else {
2702                         return (camera_override != NULL || scene->camera != NULL);
2703                 }
2704         }
2705
2706         return 1;
2707 }
2708
2709 int RE_is_rendering_allowed(Scene *scene, Object *camera_override, void *erh, void (*error)(void *handle, const char *str))
2710 {
2711         SceneRenderLayer *srl;
2712         
2713         if(scene->r.mode & R_BORDER) {
2714                 if(scene->r.border.xmax <= scene->r.border.xmin ||
2715                    scene->r.border.ymax <= scene->r.border.ymin) {
2716                         error(erh, "No border area selected.");
2717                         return 0;
2718                 }
2719         }
2720         
2721         if(scene->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2722                 char str[FILE_MAX];
2723                 
2724                 scene_unique_exr_name(scene, str, 0);
2725                 
2726                 if (BLI_is_writable(str)==0) {
2727                         error(erh, "Can not save render buffers, check the temp default path");
2728                         return 0;
2729                 }
2730                 
2731                 /* no fullsample and edge */
2732                 if((scene->r.scemode & R_FULL_SAMPLE) && (scene->r.mode & R_EDGE)) {
2733                         error(erh, "Full Sample doesn't support Edge Enhance");
2734                         return 0;
2735                 }
2736                 
2737         }
2738         else
2739                 scene->r.scemode &= ~R_FULL_SAMPLE;     /* clear to be sure */
2740         
2741         if(scene->r.scemode & R_DOCOMP) {
2742                 if(scene->use_nodes) {
2743                         bNodeTree *ntree= scene->nodetree;
2744                         bNode *node;
2745                 
2746                         if(ntree==NULL) {
2747                                 error(erh, "No Nodetree in Scene");
2748                                 return 0;
2749                         }
2750                         
2751                         for(node= ntree->nodes.first; node; node= node->next)
2752                                 if(node->type==CMP_NODE_COMPOSITE)
2753                                         break;
2754                         
2755                         if(node==NULL) {
2756                                 error(erh, "No Render Output Node in Scene");
2757                                 return 0;
2758                         }
2759                         
2760                         if(scene->r.scemode & R_FULL_SAMPLE) {
2761                                 if(composite_needs_render(scene)==0) {
2762                                         error(erh, "Full Sample AA not supported without 3d rendering");
2763                                         return 0;
2764                                 }
2765                         }
2766                 }
2767         }
2768         
2769          /* check valid camera, without camera render is OK (compo, seq) */
2770         if(!check_valid_camera(scene, camera_override)) {
2771                 error(erh, "No camera");
2772                 return 0;
2773         }
2774         
2775         /* get panorama & ortho, only after camera is set */
2776         object_camera_mode(&scene->r, camera_override ? camera_override : scene->camera);
2777
2778         /* forbidden combinations */
2779         if(scene->r.mode & R_PANORAMA) {
2780                 if(scene->r.mode & R_ORTHO) {
2781                         error(erh, "No Ortho render possible for Panorama");
2782                         return 0;
2783                 }
2784         }
2785
2786         /* layer flag tests */
2787         if(scene->r.scemode & R_SINGLE_LAYER) {
2788                 srl= BLI_findlink(&scene->r.layers, scene->r.actlay);
2789                 /* force layer to be enabled */
2790                 srl->layflag &= ~SCE_LAY_DISABLE;
2791         }
2792         
2793         for(srl= scene->r.layers.first; srl; srl= srl->next)
2794                 if(!(srl->layflag & SCE_LAY_DISABLE))
2795                         break;
2796         if(srl==NULL) {
2797                 error(erh, "All RenderLayers are disabled");
2798                 return 0;
2799         }
2800         
2801         /* renderer */
2802         if(!ELEM(scene->r.renderer, R_INTERN, R_YAFRAY)) {
2803                 error(erh, "Unknown render engine set");
2804                 return 0;
2805         }
2806
2807         return 1;
2808 }
2809
2810 static void validate_render_settings(Render *re)
2811 {
2812         if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2813                 /* no osa + fullsample won't work... */
2814                 if(re->r.osa==0)
2815                         re->r.scemode &= ~R_FULL_SAMPLE;
2816         } else re->r.scemode &= ~R_FULL_SAMPLE; /* clear to be sure */
2817 }
2818
2819 static void update_physics_cache(Render *re, Scene *scene, int UNUSED(anim_init))
2820 {
2821         PTCacheBaker baker;
2822
2823         baker.main = re->main;
2824         baker.scene = scene;
2825         baker.pid = NULL;
2826         baker.bake = 0;
2827         baker.render = 1;
2828         baker.anim_init = 1;
2829         baker.quick_step = 1;
2830         baker.break_test = re->test_break;
2831         baker.break_data = re->tbh;
2832         baker.progressbar = NULL;
2833
2834         BKE_ptcache_bake(&baker);
2835 }
2836 /* evaluating scene options for general Blender render */
2837 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)
2838 {
2839         int winx, winy;
2840         rcti disprect;
2841         
2842         /* r.xsch and r.ysch has the actual view window size
2843                 r.border is the clipping rect */
2844         
2845         /* calculate actual render result and display size */
2846         winx= (scene->r.size*scene->r.xsch)/100;
2847         winy= (scene->r.size*scene->r.ysch)/100;
2848         
2849         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2850         if(scene->r.mode & R_BORDER) {
2851                 disprect.xmin= scene->r.border.xmin*winx;
2852                 disprect.xmax= scene->r.border.xmax*winx;
2853                 
2854                 disprect.ymin= scene->r.border.ymin*winy;
2855                 disprect.ymax= scene->r.border.ymax*winy;
2856         }
2857         else {
2858                 disprect.xmin= disprect.ymin= 0;
2859                 disprect.xmax= winx;
2860                 disprect.ymax= winy;
2861         }
2862         
2863         re->main= bmain;
2864         re->scene= scene;
2865         re->camera_override= camera_override;
2866         re->lay= lay;
2867         
2868         /* not too nice, but it survives anim-border render */
2869         if(anim) {
2870                 re->disprect= disprect;
2871                 return 1;
2872         }
2873         
2874         /* check all scenes involved */
2875         tag_scenes_for_render(re);
2876
2877         /*
2878          * Disabled completely for now,
2879          * can be later set as render profile option
2880          * and default for background render.
2881         */
2882         if(0) {
2883                 /* make sure dynamics are up to date */
2884                 update_physics_cache(re, scene, anim_init);
2885         }
2886         
2887         if(srl || scene->r.scemode & R_SINGLE_LAYER)
2888                 push_render_result(re);
2889         
2890         RE_InitState(re, NULL, &scene->r, srl, winx, winy, &disprect);
2891         if(!re->ok)  /* if an error was printed, abort */
2892                 return 0;
2893         
2894         /* initstate makes new result, have to send changed tags around */
2895         ntreeCompositTagRender(re->scene);
2896
2897         validate_render_settings(re);
2898
2899         re->display_init(re->dih, re->result);
2900         re->display_clear(re->dch, re->result);
2901         
2902         return 1;
2903 }
2904
2905 /* general Blender frame render call */
2906 void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int frame, const short write_still)
2907 {
2908         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2909         G.rendering= 1;
2910         
2911         scene->r.cfra= frame;
2912         
2913         if(render_initialize_from_main(re, bmain, scene, srl, camera_override, lay, 0, 0)) {
2914                 MEM_reset_peak_memory();
2915                 do_render_all_options(re);
2916
2917                 if(write_still && !G.afbreek) {
2918                         if(BKE_imtype_is_movie(scene->r.imtype)) {
2919                                 /* operator checks this but incase its called from elsewhere */
2920                                 printf("Error: cant write single images with a movie format!\n");
2921                         }
2922                         else {
2923                                 char name[FILE_MAX];
2924                                 BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype, scene->r.scemode & R_EXTENSION, FALSE);
2925         
2926                                 /* reports only used for Movie */
2927                                 do_write_image_or_movie(re, scene, NULL, NULL, name);
2928                         }
2929                 }
2930         }
2931
2932         /* UGLY WARNING */
2933         G.rendering= 0;
2934 }
2935
2936 static int do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh, ReportList *reports, const char *name_override)
2937 {
2938         char name[FILE_MAX];
2939         RenderResult rres;
2940         Object *camera= RE_GetCamera(re);
2941         int ok= 1;
2942         
2943         RE_AcquireResultImage(re, &rres);
2944
2945         /* write movie or image */
2946         if(BKE_imtype_is_movie(scene->r.imtype)) {
2947                 int dofree = 0;
2948                 /* note; the way it gets 32 bits rects is weak... */
2949                 if(rres.rect32==NULL) {
2950                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2951                         dofree = 1;
2952                 }
2953                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
2954                 ok= mh->append_movie(&re->r, scene->r.cfra, rres.rect32, rres.rectx, rres.recty, reports);
2955                 if(dofree) {
2956                         MEM_freeN(rres.rect32);
2957                 }
2958                 printf("Append frame %d", scene->r.cfra);
2959         } 
2960         else {
2961                 if(name_override)
2962                         BLI_strncpy(name, name_override, sizeof(name));
2963                 else
2964                         BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype, scene->r.scemode & R_EXTENSION, TRUE);
2965                 
2966                 if(re->r.imtype==R_MULTILAYER) {
2967                         if(re->result) {
2968                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2969                                 printf("Saved: %s", name);
2970                         }
2971                 }
2972                 else {
2973                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0);
2974                         
2975                         /* if not exists, BKE_write_ibuf makes one */
2976                         ibuf->rect= (unsigned int *)rres.rect32;    
2977                         ibuf->rect_float= rres.rectf;
2978                         ibuf->zbuf_float= rres.rectz;
2979                         
2980                         /* float factor for random dither, imbuf takes care of it */
2981                         ibuf->dither= scene->r.dither_intensity;
2982                         
2983                         /* prepare to gamma correct to sRGB color space */
2984                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) {
2985                                 /* sequence editor can generate 8bpc render buffers */
2986                                 if (ibuf->rect) {
2987                                         ibuf->profile = IB_PROFILE_SRGB;
2988                                         if (ELEM(scene->r.imtype, R_OPENEXR, R_RADHDR))
2989                                                 IMB_float_from_rect(ibuf);
2990                                 } else {                                
2991                                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2992                                 }
2993                         }
2994
2995                         ok= BKE_write_ibuf_stamp(scene, camera, ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2996                         
2997                         if(ok==0) {
2998                                 printf("Render error: cannot save %s\n", name);
2999                         }
3000                         else printf("Saved: %s", name);
3001                         
3002                         /* optional preview images for exr */
3003                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
3004                                 if(BLI_testextensie(name, ".exr")) 
3005                                         name[strlen(name)-4]= 0;
3006                                 BKE_add_image_extension(name, R_JPEG90);
3007                                 ibuf->depth= 24; 
3008                                 BKE_write_ibuf_stamp(scene, camera, ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
3009                                 printf("\nSaved: %s", name);
3010                         }
3011                         
3012                                         /* imbuf knows which rects are not part of ibuf */
3013                         IMB_freeImBuf(ibuf);
3014                 }
3015         }
3016         
3017         RE_ReleaseResultImage(re);
3018
3019         BLI_timestr(re->i.lastframetime, name);
3020         printf(" Time: %s\n", name);
3021         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
3022
3023         return ok;
3024 }
3025
3026 /* saves images to disk */
3027 void RE_BlenderAnim(Render *re, Main *bmain, Scene *scene, Object *camera_override, unsigned int lay, int sfra, int efra, int tfra, ReportList *reports)
3028 {
3029         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
3030         int cfrao= scene->r.cfra;
3031         int nfra;
3032         
3033         /* do not fully call for each frame, it initializes & pops output window */
3034         if(!render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 0, 1))
3035                 return;
3036         
3037         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
3038         /* is also set by caller renderwin.c */
3039         G.rendering= 1;
3040         
3041         if(BKE_imtype_is_movie(scene->r.imtype))
3042                 if(!mh->start_movie(scene, &re->r, re->rectx, re->recty, reports))
3043                         G.afbreek= 1;
3044
3045         if (mh->get_next_frame) {
3046                 while (!(G.afbreek == 1)) {
3047                         int nf = mh->get_next_frame(&re->r, reports);
3048                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
3049                                 scene->r.cfra = re->r.cfra = nf;
3050                                 
3051                                 do_render_all_options(re);
3052
3053                                 if(re->test_break(re->tbh) == 0) {
3054                                         if(!do_write_image_or_movie(re, scene, mh, reports, NULL))
3055                                                 G.afbreek= 1;
3056                                 }
3057                         } else {
3058                                 if(re->test_break(re->tbh))
3059                                         G.afbreek= 1;
3060                         }
3061                 }
3062         } else {
3063                 for(nfra= sfra, scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
3064                         char name[FILE_MAX];
3065                         
3066                         /* only border now, todo: camera lens. (ton) */
3067                         render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 1, 0);
3068
3069                         if(nfra!=scene->r.cfra) {