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