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