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