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