Fix for bug #9687: crash with FSA when compiling with openexr support.
[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 unsigned long 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 Render *RE_NewRender(const char *name)
997 {
998         Render *re;
999         
1000         /* only one render per name exists */
1001         re= RE_GetRender(name);
1002         if(re==NULL) {
1003                 
1004                 /* new render data struct */
1005                 re= MEM_callocN(sizeof(Render), "new render");
1006                 BLI_addtail(&RenderList, re);
1007                 strncpy(re->name, name, RE_MAXNAME);
1008         }
1009         
1010         /* set default empty callbacks */
1011         re->display_init= result_nothing;
1012         re->display_clear= result_nothing;
1013         re->display_draw= result_rcti_nothing;
1014         re->timecursor= int_nothing;
1015         re->test_break= void_nothing;
1016         re->test_return= void_nothing;
1017         re->error= print_error;
1018         if(G.background)
1019                 re->stats_draw= stats_background;
1020         else
1021                 re->stats_draw= stats_nothing;
1022         
1023         /* init some variables */
1024         re->ycor= 1.0f;
1025         
1026         return re;
1027 }
1028
1029 /* only call this while you know it will remove the link too */
1030 void RE_FreeRender(Render *re)
1031 {
1032         
1033         free_renderdata_tables(re);
1034         free_sample_tables(re);
1035         
1036         RE_FreeRenderResult(re->result);
1037         RE_FreeRenderResult(re->pushedresult);
1038         
1039         BLI_remlink(&RenderList, re);
1040         MEM_freeN(re);
1041 }
1042
1043 /* exit blender */
1044 void RE_FreeAllRender(void)
1045 {
1046         while(RenderList.first) {
1047                 RE_FreeRender(RenderList.first);
1048         }
1049 }
1050
1051 /* ********* initialize state ******** */
1052
1053
1054 /* what doesn't change during entire render sequence */
1055 /* disprect is optional, if NULL it assumes full window render */
1056 void RE_InitState(Render *re, Render *source, RenderData *rd, int winx, int winy, rcti *disprect)
1057 {
1058         re->ok= TRUE;   /* maybe flag */
1059         
1060         re->i.starttime= PIL_check_seconds_timer();
1061         re->r= *rd;             /* hardcopy */
1062         
1063         re->winx= winx;
1064         re->winy= winy;
1065         if(disprect) {
1066                 re->disprect= *disprect;
1067                 re->rectx= disprect->xmax-disprect->xmin;
1068                 re->recty= disprect->ymax-disprect->ymin;
1069         }
1070         else {
1071                 re->disprect.xmin= re->disprect.ymin= 0;
1072                 re->disprect.xmax= winx;
1073                 re->disprect.ymax= winy;
1074                 re->rectx= winx;
1075                 re->recty= winy;
1076         }
1077         
1078         if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
1079                                                                                   (re->rectx < 16 || re->recty < 16) )) {
1080                 re->error("Image too small");
1081                 re->ok= 0;
1082         }
1083         else {
1084 #ifndef WITH_OPENEXR
1085                 /* can't do this without openexr support */
1086                 re->r.scemode &= ~R_EXR_TILE_FILE;
1087 #endif
1088                 
1089                 if(!(re->r.scemode & R_EXR_TILE_FILE))
1090                         re->r.scemode &= ~R_FULL_SAMPLE;        /* clear, so we can use this flag for test both */
1091                 
1092                 /* fullsample wants uniform osa levels */
1093                 if(source && (re->r.scemode & R_FULL_SAMPLE)) {
1094                         /* but, if source has no full sample we disable it */
1095                         if((source->r.scemode & R_FULL_SAMPLE)==0)
1096                                 re->r.scemode &= ~R_FULL_SAMPLE;
1097                         else
1098                                 re->r.osa= re->osa= source->osa;
1099                 }
1100                 else {
1101                         /* check state variables, osa? */
1102                         if(re->r.mode & (R_OSA)) {
1103                                 re->osa= re->r.osa;
1104                                 if(re->osa>16) re->osa= 16;
1105                         }
1106                         else re->osa= 0;
1107                 }
1108
1109                 /* always call, checks for gamma, gamma tables and jitter too */
1110                 make_sample_tables(re); 
1111                 
1112                 /* make empty render result, so display callbacks can initialize */
1113                 RE_FreeRenderResult(re->result);
1114                 re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1115                 re->result->rectx= re->rectx;
1116                 re->result->recty= re->recty;
1117                 
1118                 /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1119                 re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1120                 
1121                 if ((rd->mode & R_FIXED_THREADS)==0 || commandline_threads == 0) { /* Automatic threads */
1122                         re->r.threads = BLI_system_thread_count();
1123                 } else if(commandline_threads >= 1 && commandline_threads<=BLENDER_MAX_THREADS) {
1124                         re->r.threads= commandline_threads;
1125                 }
1126         }
1127 }
1128
1129 /* part of external api, not called for regular render pipeline */
1130 void RE_SetDispRect (struct Render *re, rcti *disprect)
1131 {
1132         re->disprect= *disprect;
1133         re->rectx= disprect->xmax-disprect->xmin;
1134         re->recty= disprect->ymax-disprect->ymin;
1135         
1136         /* initialize render result */
1137         RE_FreeRenderResult(re->result);
1138         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1139 }
1140
1141 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1142 {
1143         /* re->ok flag? */
1144         
1145         re->viewplane= *viewplane;
1146         re->clipsta= clipsta;
1147         re->clipend= clipend;
1148         re->r.mode &= ~R_ORTHO;
1149
1150         i_window(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1151         
1152 }
1153
1154 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1155 {
1156         /* re->ok flag? */
1157         
1158         re->viewplane= *viewplane;
1159         re->clipsta= clipsta;
1160         re->clipend= clipend;
1161         re->r.mode |= R_ORTHO;
1162
1163         i_ortho(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1164 }
1165
1166 void RE_SetView(Render *re, float mat[][4])
1167 {
1168         /* re->ok flag? */
1169         Mat4CpyMat4(re->viewmat, mat);
1170         Mat4Invert(re->viewinv, re->viewmat);
1171 }
1172
1173 /* image and movie output has to move to either imbuf or kernel */
1174 void RE_display_init_cb(Render *re, void (*f)(RenderResult *rr))
1175 {
1176         re->display_init= f;
1177 }
1178 void RE_display_clear_cb(Render *re, void (*f)(RenderResult *rr))
1179 {
1180         re->display_clear= f;
1181 }
1182 void RE_display_draw_cb(Render *re, void (*f)(RenderResult *rr, volatile rcti *rect))
1183 {
1184         re->display_draw= f;
1185 }
1186
1187 void RE_stats_draw_cb(Render *re, void (*f)(RenderStats *rs))
1188 {
1189         re->stats_draw= f;
1190 }
1191 void RE_timecursor_cb(Render *re, void (*f)(int))
1192 {
1193         re->timecursor= f;
1194 }
1195
1196 void RE_test_break_cb(Render *re, int (*f)(void))
1197 {
1198         re->test_break= f;
1199 }
1200 void RE_test_return_cb(Render *re, int (*f)(void))
1201 {
1202         re->test_return= f;
1203 }
1204 void RE_error_cb(Render *re, void (*f)(char *str))
1205 {
1206         re->error= f;
1207 }
1208
1209
1210 /* ********* add object data (later) ******** */
1211
1212 /* object is considered fully prepared on correct time etc */
1213 /* includes lights */
1214 void RE_AddObject(Render *re, Object *ob)
1215 {
1216         
1217 }
1218
1219 /* *************************************** */
1220
1221 static int render_display_draw_enabled(Render *re)
1222 {
1223         /* don't show preprocess for previewrender sss */
1224         if(re->sss_points)
1225                 return !(re->r.scemode & R_PREVIEWBUTS);
1226         else
1227                 return 1;
1228 }
1229
1230 /* allocate osa new results for samples */
1231 static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
1232 {
1233         int a;
1234         
1235         if(re->osa==0)
1236                 return new_render_result(re, partrct, crop, RR_USEMEM);
1237         
1238         for(a=0; a<re->osa; a++) {
1239                 RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
1240                 BLI_addtail(lb, rr);
1241                 rr->sample_nr= a;
1242         }
1243         
1244         return lb->first;
1245 }
1246
1247
1248 /* the main thread call, renders an entire part */
1249 static void *do_part_thread(void *pa_v)
1250 {
1251         RenderPart *pa= pa_v;
1252         
1253         /* need to return nicely all parts on esc */
1254         if(R.test_break()==0) {
1255                 
1256                 if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
1257                         pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
1258                 else
1259                         pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1260
1261                 if(R.sss_points)
1262                         zbufshade_sss_tile(pa);
1263                 else if(R.osa)
1264                         zbufshadeDA_tile(pa);
1265                 else
1266                         zbufshade_tile(pa);
1267                 
1268                 /* merge too on break! */
1269                 if(R.result->exrhandle) {
1270                         RenderResult *rr, *rrpart;
1271                         
1272                         for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
1273                                 save_render_result_tile(rr, rrpart);
1274                         
1275                 }
1276                 else if(render_display_draw_enabled(&R))
1277                         merge_render_result(R.result, pa->result);
1278         }
1279         
1280         pa->ready= 1;
1281         
1282         return NULL;
1283 }
1284
1285 /* returns with render result filled, not threaded, used for preview now only */
1286 static void render_tile_processor(Render *re, int firsttile)
1287 {
1288         RenderPart *pa;
1289         
1290         if(re->test_break())
1291                 return;
1292
1293         /* hrmf... exception, this is used for preview render, re-entrant, so render result has to be re-used */
1294         if(re->result==NULL || re->result->layers.first==NULL) {
1295                 if(re->result) RE_FreeRenderResult(re->result);
1296                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1297         }
1298         
1299         re->stats_draw(&re->i);
1300  
1301         if(re->result==NULL)
1302                 return;
1303         
1304         initparts(re);
1305         
1306         /* assuming no new data gets added to dbase... */
1307         R= *re;
1308         
1309         for(pa= re->parts.first; pa; pa= pa->next) {
1310                 if(firsttile) {
1311                         re->i.partsdone++;      /* was reset in initparts */
1312                         firsttile--;
1313                 }
1314                 else {
1315                         do_part_thread(pa);
1316                         
1317                         if(pa->result) {
1318                                 if(!re->test_break()) {
1319                                         if(render_display_draw_enabled(re))
1320                                                 re->display_draw(pa->result, NULL);
1321                                         
1322                                         re->i.partsdone++;
1323                                         re->stats_draw(&re->i);
1324                                 }
1325                                 RE_FreeRenderResult(pa->result);
1326                                 pa->result= NULL;
1327                         }               
1328                         if(re->test_break())
1329                                 break;
1330                 }
1331         }
1332         
1333         freeparts(re);
1334 }
1335
1336 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1337 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1338 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1339 float panorama_pixel_rot(Render *re)
1340 {
1341         float psize, phi, xfac;
1342         
1343         /* size of 1 pixel mapped to viewplane coords */
1344         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
1345         /* angle of a pixel */
1346         phi= atan(psize/re->clipsta);
1347         
1348         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1349         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1350         xfac= atan(0.5f*xfac/re->clipsta); 
1351         /* and how much the same viewplane angle is wrapped */
1352         psize= 0.5f*phi*((float)re->partx);
1353         
1354         /* the ratio applied to final per-pixel angle */
1355         phi*= xfac/psize;
1356         
1357         return phi;
1358 }
1359
1360 /* call when all parts stopped rendering, to find the next Y slice */
1361 /* if slice found, it rotates the dbase */
1362 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1363 {
1364         RenderPart *pa, *best= NULL;
1365         
1366         *minx= re->winx;
1367         
1368         /* most left part of the non-rendering parts */
1369         for(pa= re->parts.first; pa; pa= pa->next) {
1370                 if(pa->ready==0 && pa->nr==0) {
1371                         if(pa->disprect.xmin < *minx) {
1372                                 best= pa;
1373                                 *minx= pa->disprect.xmin;
1374                         }
1375                 }
1376         }
1377                         
1378         if(best) {
1379                 float phi= panorama_pixel_rot(re);
1380
1381                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1382                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
1383                 
1384                 /* shift viewplane */
1385                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1386                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1387                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1388                 Mat4CpyMat4(R.winmat, re->winmat);
1389                 
1390                 /* rotate database according to part coordinates */
1391                 project_renderdata(re, projectverto, 1, -R.panodxp*phi, 1);
1392                 R.panosi= sin(R.panodxp*phi);
1393                 R.panoco= cos(R.panodxp*phi);
1394         }
1395         return best;
1396 }
1397
1398 static RenderPart *find_next_part(Render *re, int minx)
1399 {
1400         RenderPart *pa, *best= NULL;
1401         int centx=re->winx/2, centy=re->winy/2, tot=1;
1402         int mindist, distx, disty;
1403         
1404         /* find center of rendered parts, image center counts for 1 too */
1405         for(pa= re->parts.first; pa; pa= pa->next) {
1406                 if(pa->ready) {
1407                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1408                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1409                         tot++;
1410                 }
1411         }
1412         centx/=tot;
1413         centy/=tot;
1414         
1415         /* closest of the non-rendering parts */
1416         mindist= re->winx*re->winy;
1417         for(pa= re->parts.first; pa; pa= pa->next) {
1418                 if(pa->ready==0 && pa->nr==0) {
1419                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1420                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1421                         distx= (int)sqrt(distx*distx + disty*disty);
1422                         if(distx<mindist) {
1423                                 if(re->r.mode & R_PANORAMA) {
1424                                         if(pa->disprect.xmin==minx) {
1425                                                 best= pa;
1426                                                 mindist= distx;
1427                                         }
1428                                 }
1429                                 else {
1430                                         best= pa;
1431                                         mindist= distx;
1432                                 }
1433                         }
1434                 }
1435         }
1436         return best;
1437 }
1438
1439 static void print_part_stats(Render *re, RenderPart *pa)
1440 {
1441         char str[64];
1442         
1443         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1444         re->i.infostr= str;
1445         re->stats_draw(&re->i);
1446         re->i.infostr= NULL;
1447 }
1448
1449 /* make osa new results for samples */
1450 static RenderResult *new_full_sample_buffers_exr(Render *re)
1451 {
1452         int a;
1453         
1454         for(a=0; a<re->osa; a++) {
1455                 RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
1456                 BLI_addtail(&re->fullresult, rr);
1457                 rr->sample_nr= a;
1458         }
1459         
1460         return re->fullresult.first;
1461 }
1462
1463 static void threaded_tile_processor(Render *re)
1464 {
1465         ListBase threads;
1466         RenderPart *pa, *nextpa;
1467         rctf viewplane= re->viewplane;
1468         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1469         
1470         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
1471         RE_FreeRenderResult(re->result);
1472         
1473         if(re->sss_points)
1474                 re->result= new_render_result(re, &re->disprect, 0, 0);
1475         else if(re->r.scemode & R_FULL_SAMPLE)
1476                 re->result= new_full_sample_buffers_exr(re);
1477         else
1478                 re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & R_EXR_TILE_FILE);
1479         
1480         if(re->result==NULL)
1481                 return;
1482         
1483         /* warning; no return here without closing exr file */
1484         
1485         initparts(re);
1486         
1487         if(re->result->exrhandle) {
1488                 RenderResult *rr;
1489                 char str[FILE_MAX];
1490                 
1491                 for(rr= re->result; rr; rr= rr->next) {
1492                         render_unique_exr_name(re, str, rr->sample_nr);
1493                 
1494                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1495                         IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1496                 }
1497         }
1498         
1499         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1500         
1501         /* assuming no new data gets added to dbase... */
1502         R= *re;
1503         
1504         /* set threadsafe break */
1505         R.test_break= thread_break;
1506         
1507         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1508         if(re->r.mode & R_PANORAMA)
1509                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1510         else
1511                 nextpa= find_next_part(re, 0);
1512         
1513         while(rendering) {
1514                 
1515                 if(re->test_break())
1516                         PIL_sleep_ms(50);
1517                 else if(nextpa && BLI_available_threads(&threads)) {
1518                         drawtimer= 0;
1519                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1520                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1521                         BLI_insert_thread(&threads, nextpa);
1522
1523                         nextpa= find_next_part(re, minx);
1524                 }
1525                 else if(re->r.mode & R_PANORAMA) {
1526                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1527                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1528                         else {
1529                                 PIL_sleep_ms(50);
1530                                 drawtimer++;
1531                         }
1532                 }
1533                 else {
1534                         PIL_sleep_ms(50);
1535                         drawtimer++;
1536                 }
1537                 
1538                 /* check for ready ones to display, and if we need to continue */
1539                 rendering= 0;
1540                 hasdrawn= 0;
1541                 for(pa= re->parts.first; pa; pa= pa->next) {
1542                         if(pa->ready) {
1543                                 
1544                                 BLI_remove_thread(&threads, pa);
1545                                 
1546                                 if(pa->result) {
1547                                         if(render_display_draw_enabled(re))
1548                                                 re->display_draw(pa->result, NULL);
1549                                         print_part_stats(re, pa);
1550                                         
1551                                         free_render_result(&pa->fullresult, pa->result);
1552                                         pa->result= NULL;
1553                                         re->i.partsdone++;
1554                                         hasdrawn= 1;
1555                                 }
1556                         }
1557                         else {
1558                                 rendering= 1;
1559                                 if(pa->nr && pa->result && drawtimer>20) {
1560                                         if(render_display_draw_enabled(re))
1561                                                 re->display_draw(pa->result, &pa->result->renrect);
1562                                         hasdrawn= 1;
1563                                 }
1564                         }
1565                 }
1566                 if(hasdrawn)
1567                         drawtimer= 0;
1568
1569                 /* on break, wait for all slots to get freed */
1570                 if( (g_break=re->test_break()) && BLI_available_threads(&threads)==re->r.threads)
1571                         rendering= 0;
1572                 
1573         }
1574         
1575         if(re->result->exrhandle) {
1576                 RenderResult *rr;
1577
1578                 save_empty_result_tiles(re);
1579                 
1580                 for(rr= re->result; rr; rr= rr->next) {
1581                         IMB_exr_close(rr->exrhandle);
1582                         rr->exrhandle= NULL;
1583                 }
1584                 
1585                 free_render_result(&re->fullresult, re->result);
1586                 re->result= NULL;
1587                 
1588                 read_render_result(re, 0);
1589         }
1590         
1591         /* unset threadsafety */
1592         g_break= 0;
1593         
1594         BLI_end_threads(&threads);
1595         freeparts(re);
1596         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1597 }
1598
1599 /* currently only called by preview renders and envmap */
1600 void RE_TileProcessor(Render *re, int firsttile, int threaded)
1601 {
1602         /* the partsdone variable has to be reset to firsttile, to survive esc before it was set to zero */
1603         
1604         re->i.partsdone= firsttile;
1605
1606         if(!re->sss_points)
1607                 re->i.starttime= PIL_check_seconds_timer();
1608
1609         if(threaded)
1610                 threaded_tile_processor(re);
1611         else
1612                 render_tile_processor(re, firsttile);
1613                 
1614         if(!re->sss_points)
1615                 re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1616         re->stats_draw(&re->i);
1617 }
1618
1619
1620 /* ************  This part uses API, for rendering Blender scenes ********** */
1621
1622 static void do_render_3d(Render *re)
1623 {
1624         
1625 //      re->cfra= cfra; /* <- unused! */
1626         
1627         /* make render verts/faces/halos/lamps */
1628         if(render_scene_needs_vector(re))
1629                 RE_Database_FromScene_Vectors(re, re->scene);
1630         else
1631            RE_Database_FromScene(re, re->scene, 1);
1632         
1633         threaded_tile_processor(re);
1634         
1635         /* do left-over 3d post effects (flares) */
1636         if(re->flag & R_HALO)
1637                 if(!re->test_break())
1638                         add_halo_flare(re);
1639
1640         
1641         /* free all render verts etc */
1642         RE_Database_Free(re);
1643 }
1644
1645 /* called by blur loop, accumulate renderlayers */
1646 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1647 {
1648         float mfac= 1.0f - blurfac;
1649         int a, b, stride= channels*rr->rectx;
1650         int len= stride*sizeof(float);
1651         
1652         for(a=0; a<rr->recty; a++) {
1653                 if(blurfac==1.0f) {
1654                         memcpy(rectf, rectf1, len);
1655                 }
1656                 else {
1657                         float *rf= rectf, *rf1= rectf1;
1658                         
1659                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1660                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1661                         }
1662                 }
1663                 rectf+= stride;
1664                 rectf1+= stride;
1665         }
1666 }
1667
1668 /* called by blur loop, accumulate renderlayers */
1669 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac)
1670 {
1671         RenderLayer *rl, *rl1;
1672         RenderPass *rpass, *rpass1;
1673         
1674         rl1= brr->layers.first;
1675         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1676                 
1677                 /* combined */
1678                 if(rl->rectf && rl1->rectf)
1679                         addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1680                 
1681                 /* passes are allocated in sync */
1682                 rpass1= rl1->passes.first;
1683                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1684                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1685                 }
1686         }
1687 }
1688
1689 /* main blur loop, can be called by fields too */
1690 static void do_render_blur_3d(Render *re)
1691 {
1692         RenderResult *rres;
1693         float blurfac;
1694         int blur= re->r.osa;
1695         
1696         /* create accumulation render result */
1697         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1698         
1699         /* do the blur steps */
1700         while(blur--) {
1701                 set_mblur_offs( re->r.blurfac*((float)(re->r.osa-blur))/(float)re->r.osa );
1702                 
1703                 re->i.curblur= re->r.osa-blur;  /* stats */
1704                 
1705                 do_render_3d(re);
1706                 
1707                 blurfac= 1.0f/(float)(re->r.osa-blur);
1708                 
1709                 merge_renderresult_blur(rres, re->result, blurfac);
1710                 if(re->test_break()) break;
1711         }
1712         
1713         /* swap results */
1714         RE_FreeRenderResult(re->result);
1715         re->result= rres;
1716         
1717         set_mblur_offs(0.0f);
1718         re->i.curblur= 0;       /* stats */
1719         
1720         /* weak... the display callback wants an active renderlayer pointer... */
1721         re->result->renlay= render_get_active_layer(re, re->result);
1722         re->display_draw(re->result, NULL);     
1723 }
1724
1725
1726 /* function assumes rectf1 and rectf2 to be half size of rectf */
1727 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1728 {
1729         int a, stride= channels*rr->rectx;
1730         int len= stride*sizeof(float);
1731         
1732         for(a=0; a<rr->recty; a+=2) {
1733                 memcpy(rectf, rectf1, len);
1734                 rectf+= stride;
1735                 rectf1+= stride;
1736                 memcpy(rectf, rectf2, len);
1737                 rectf+= stride;
1738                 rectf2+= stride;
1739         }
1740 }
1741
1742 /* merge render results of 2 fields */
1743 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1744 {
1745         RenderLayer *rl, *rl1, *rl2;
1746         RenderPass *rpass, *rpass1, *rpass2;
1747         
1748         rl1= rr1->layers.first;
1749         rl2= rr2->layers.first;
1750         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1751                 
1752                 /* combined */
1753                 if(rl->rectf && rl1->rectf && rl2->rectf)
1754                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1755                 
1756                 /* passes are allocated in sync */
1757                 rpass1= rl1->passes.first;
1758                 rpass2= rl2->passes.first;
1759                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1760                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1761                 }
1762         }
1763 }
1764
1765
1766 /* interleaves 2 frames */
1767 static void do_render_fields_3d(Render *re)
1768 {
1769         RenderResult *rr1, *rr2= NULL;
1770         
1771         /* no render result was created, we can safely halve render y */
1772         re->winy /= 2;
1773         re->recty /= 2;
1774         re->disprect.ymin /= 2;
1775         re->disprect.ymax /= 2;
1776         
1777         re->i.curfield= 1;      /* stats */
1778         
1779         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1780         RE_SetCamera(re, re->scene->camera);
1781         if(re->r.mode & R_MBLUR)
1782                 do_render_blur_3d(re);
1783         else
1784                 do_render_3d(re);
1785         rr1= re->result;
1786         re->result= NULL;
1787         
1788         /* second field */
1789         if(!re->test_break()) {
1790                 
1791                 re->i.curfield= 2;      /* stats */
1792                 
1793                 re->flag |= R_SEC_FIELD;
1794                 if((re->r.mode & R_FIELDSTILL)==0) 
1795                         set_field_offs(0.5f);
1796                 RE_SetCamera(re, re->scene->camera);
1797                 if(re->r.mode & R_MBLUR)
1798                         do_render_blur_3d(re);
1799                 else
1800                         do_render_3d(re);
1801                 re->flag &= ~R_SEC_FIELD;
1802                 set_field_offs(0.0f);
1803                 
1804                 rr2= re->result;
1805         }
1806         
1807         /* allocate original height new buffers */
1808         re->winy *= 2;
1809         re->recty *= 2;
1810         re->disprect.ymin *= 2;
1811         re->disprect.ymax *= 2;
1812         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1813         
1814         if(rr2) {
1815                 if(re->r.mode & R_ODDFIELD)
1816                         merge_renderresult_fields(re->result, rr2, rr1);
1817                 else
1818                         merge_renderresult_fields(re->result, rr1, rr2);
1819                 
1820                 RE_FreeRenderResult(rr2);
1821         }
1822         RE_FreeRenderResult(rr1);
1823         
1824         re->i.curfield= 0;      /* stats */
1825         
1826         /* weak... the display callback wants an active renderlayer pointer... */
1827         re->result->renlay= render_get_active_layer(re, re->result);
1828         re->display_draw(re->result, NULL);
1829 }
1830
1831 static void load_backbuffer(Render *re)
1832 {
1833         if(re->r.alphamode == R_ADDSKY) {
1834                 ImBuf *ibuf;
1835                 char name[256];
1836                 
1837                 strcpy(name, re->r.backbuf);
1838                 BLI_convertstringcode(name, G.sce, re->r.cfra);
1839                 
1840                 if(re->backbuf) {
1841                         re->backbuf->id.us--;
1842                         if(re->backbuf->id.us<1)
1843                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
1844                 }
1845                 
1846                 re->backbuf= BKE_add_image_file(name);
1847                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
1848                 if(ibuf==NULL) {
1849                         // error() doesnt work with render window open
1850                         //error("No backbuf there!");
1851                         printf("Error: No backbuf %s\n", name);
1852                 }
1853                 else {
1854                         if (re->r.mode & R_FIELDS)
1855                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
1856                 }
1857         }
1858 }
1859
1860 /* main render routine, no compositing */
1861 static void do_render_fields_blur_3d(Render *re)
1862 {
1863         /* also check for camera here */
1864         if(re->scene->camera==NULL) {
1865                 printf("ERROR: Cannot render, no camera\n");
1866                 G.afbreek= 1;
1867                 return;
1868         }
1869         
1870         /* backbuffer initialize */
1871         if(re->r.bufflag & 1)
1872                 load_backbuffer(re);
1873
1874         /* now use renderdata and camera to set viewplane */
1875         RE_SetCamera(re, re->scene->camera);
1876         
1877         if(re->r.mode & R_FIELDS)
1878                 do_render_fields_3d(re);
1879         else if(re->r.mode & R_MBLUR)
1880                 do_render_blur_3d(re);
1881         else
1882                 do_render_3d(re);
1883         
1884         /* when border render, check if we have to insert it in black */
1885         if(re->result) {
1886                 if(re->r.mode & R_BORDER) {
1887                         if((re->r.mode & R_CROP)==0) {
1888                                 RenderResult *rres;
1889                                 
1890                                 /* sub-rect for merge call later on */
1891                                 re->result->tilerect= re->disprect;
1892                                 
1893                                 /* this copying sequence could become function? */
1894                                 re->disprect.xmin= re->disprect.ymin= 0;
1895                                 re->disprect.xmax= re->winx;
1896                                 re->disprect.ymax= re->winy;
1897                                 re->rectx= re->winx;
1898                                 re->recty= re->winy;
1899                                 
1900                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1901                                 
1902                                 merge_render_result(rres, re->result);
1903                                 RE_FreeRenderResult(re->result);
1904                                 re->result= rres;
1905                                 
1906                                 /* weak... the display callback wants an active renderlayer pointer... */
1907                                 re->result->renlay= render_get_active_layer(re, re->result);
1908                                 
1909                                 re->display_init(re->result);
1910                                 re->display_draw(re->result, NULL);
1911                         }
1912                 }
1913         }
1914 }
1915
1916
1917 /* within context of current Render *re, render another scene.
1918    it uses current render image size and disprect, but doesn't execute composite
1919 */
1920 static void render_scene(Render *re, Scene *sce, int cfra)
1921 {
1922         Render *resc= RE_NewRender(sce->id.name);
1923         int winx= re->winx, winy= re->winy;
1924         
1925         sce->r.cfra= cfra;
1926                 
1927         /* exception: scene uses own size (unfinished code) */
1928         if(0) {
1929                 winx= (sce->r.size*sce->r.xsch)/100;
1930                 winy= (sce->r.size*sce->r.ysch)/100;
1931         }
1932         
1933         /* initial setup */
1934         RE_InitState(resc, re, &sce->r, winx, winy, &re->disprect);
1935         
1936         /* still unsure entity this... */
1937         resc->scene= sce;
1938         
1939         /* ensure scene has depsgraph, base flags etc OK. Warning... also sets G.scene */
1940         set_scene_bg(sce);
1941
1942         /* copy callbacks */
1943         resc->display_draw= re->display_draw;
1944         resc->test_break= re->test_break;
1945         resc->stats_draw= re->stats_draw;
1946         
1947         do_render_fields_blur_3d(resc);
1948 }
1949
1950 static void tag_scenes_for_render(Render *re)
1951 {
1952         bNode *node;
1953         Scene *sce;
1954         
1955         for(sce= G.main->scene.first; sce; sce= sce->id.next)
1956                 sce->id.flag &= ~LIB_DOIT;
1957         
1958         re->scene->id.flag |= LIB_DOIT;
1959         
1960         if(re->scene->nodetree==NULL) return;
1961         
1962         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
1963         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1964                 if(node->type==CMP_NODE_R_LAYERS) {
1965                         if(node->id) {
1966                                 if(node->id != (ID *)re->scene)
1967                                         node->id->flag |= LIB_DOIT;
1968                         }
1969                 }
1970         }
1971         
1972 }
1973
1974 static void ntree_render_scenes(Render *re)
1975 {
1976         bNode *node;
1977         int cfra= re->scene->r.cfra;
1978         
1979         if(re->scene->nodetree==NULL) return;
1980         
1981         tag_scenes_for_render(re);
1982         
1983         /* now foreach render-result node tagged we do a full render */
1984         /* results are stored in a way compisitor will find it */
1985         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1986                 if(node->type==CMP_NODE_R_LAYERS) {
1987                         if(node->id && node->id != (ID *)re->scene) {
1988                                 if(node->id->flag & LIB_DOIT) {
1989                                         render_scene(re, (Scene *)node->id, cfra);
1990                                         node->id->flag &= ~LIB_DOIT;
1991                                 }
1992                         }
1993                 }
1994         }
1995         
1996         /* still the global... */
1997         if(G.scene!=re->scene)
1998                 set_scene_bg(re->scene);
1999         
2000 }
2001
2002 /* helper call to detect if theres a composite with render-result node */
2003 static int composite_needs_render(Scene *sce)
2004 {
2005         bNodeTree *ntree= sce->nodetree;
2006         bNode *node;
2007         
2008         if(ntree==NULL) return 1;
2009         if(sce->use_nodes==0) return 1;
2010         if((sce->r.scemode & R_DOCOMP)==0) return 1;
2011                 
2012         for(node= ntree->nodes.first; node; node= node->next) {
2013                 if(node->type==CMP_NODE_R_LAYERS)
2014                         if(node->id==NULL || node->id==&sce->id)
2015                                 return 1;
2016         }
2017         return 0;
2018 }
2019
2020 /* bad call... need to think over proper method still */
2021 static void render_composit_stats(char *str)
2022 {
2023         R.i.infostr= str;
2024         R.stats_draw(&R.i);
2025         R.i.infostr= NULL;
2026 }
2027
2028
2029 /* reads all buffers, calls optional composite, merges in first result->rectf */
2030 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
2031 {
2032         float *rectf, filt[3][3];
2033         int sample;
2034         
2035         /* filtmask needs it */
2036         R= *re;
2037         
2038         /* we accumulate in here */
2039         rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
2040         
2041         for(sample=0; sample<re->r.osa; sample++) {
2042                 RenderResult rres;
2043                 int x, y, mask;
2044                 
2045                 /* set all involved renders on the samplebuffers (first was done by render itself) */
2046                 /* also function below assumes this */
2047                 if(sample) {
2048                         Render *re1;
2049                         
2050                         tag_scenes_for_render(re);
2051                         for(re1= RenderList.first; re1; re1= re1->next) {
2052                                 if(re1->scene->id.flag & LIB_DOIT)
2053                                         if(re1->r.scemode & R_FULL_SAMPLE)
2054                                                 read_render_result(re1, sample);
2055                         }
2056                 }
2057
2058                 /* composite */
2059                 if(ntree) {
2060                         ntreeCompositTagRender(re->scene);
2061                         ntreeCompositTagAnimated(ntree);
2062                         
2063                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2064                 }
2065                 
2066                 /* ensure we get either composited result or the active layer */
2067                 RE_GetResultImage(re, &rres);
2068                 
2069                 /* accumulate with filter, and clip */
2070                 mask= (1<<sample);
2071                 mask_array(mask, filt);
2072
2073                 for(y=0; y<re->recty; y++) {
2074                         float *rf= rectf + 4*y*re->rectx;
2075                         float *col= rres.rectf + 4*y*re->rectx;
2076                                 
2077                         for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
2078                                 if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
2079                                 if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
2080                                 if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
2081                                 
2082                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
2083                         }
2084                 }
2085                 
2086                 /* show stuff */
2087                 if(sample!=re->osa-1) {
2088                         /* weak... the display callback wants an active renderlayer pointer... */
2089                         re->result->renlay= render_get_active_layer(re, re->result);
2090                         re->display_draw(re->result, NULL);
2091                 }
2092                 
2093                 if(re->test_break())
2094                         break;
2095         }
2096         
2097         if(re->result->rectf) 
2098                 MEM_freeN(re->result->rectf);
2099         re->result->rectf= rectf;
2100 }
2101
2102 void RE_MergeFullSample(Render *re, Scene *sce, bNodeTree *ntree)
2103 {
2104         Scene *scene;
2105         bNode *node;
2106         
2107         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
2108         
2109         /* tag scenes unread */
2110         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2111                 scene->id.flag |= LIB_DOIT;
2112         
2113         for(node= ntree->nodes.first; node; node= node->next) {
2114                 if(node->type==CMP_NODE_R_LAYERS) {
2115                         Scene *nodescene= (Scene *)node->id;
2116                         
2117                         if(nodescene==NULL) nodescene= sce;
2118                         if(nodescene->id.flag & LIB_DOIT) {
2119                                 nodescene->r.mode |= R_OSA;     /* render struct needs tables */
2120                                 RE_ReadRenderResult(sce, nodescene);
2121                                 nodescene->id.flag &= ~LIB_DOIT;
2122                         }
2123                 }
2124         }
2125         
2126         /* own render result should be read/allocated */
2127         if(G.scene->id.flag & LIB_DOIT)
2128                 RE_ReadRenderResult(G.scene, G.scene);
2129         
2130         /* and now we can draw (result is there) */
2131         re->display_init(re->result);
2132         re->display_clear(re->result);
2133         
2134         do_merge_fullsample(re, ntree);
2135 }
2136
2137 /* returns fully composited render-result on given time step (in RenderData) */
2138 static void do_render_composite_fields_blur_3d(Render *re)
2139 {
2140         bNodeTree *ntree= re->scene->nodetree;
2141         
2142         /* INIT seeding, compositor can use random texture */
2143         BLI_srandom(re->r.cfra);
2144         
2145         if(composite_needs_render(re->scene)) {
2146                 /* save memory... free all cached images */
2147                 ntreeFreeCache(ntree);
2148                 
2149                 do_render_fields_blur_3d(re);
2150         }
2151         
2152         /* swap render result */
2153         if(re->r.scemode & R_SINGLE_LAYER)
2154                 pop_render_result(re);
2155         
2156         if(!re->test_break()) {
2157                 
2158                 if(ntree) {
2159                         ntreeCompositTagRender(re->scene);
2160                         ntreeCompositTagAnimated(ntree);
2161                 }
2162                 
2163                 if(1 || !(re->r.scemode & R_COMP_RERENDER)) {
2164                         if(ntree && re->r.scemode & R_DOCOMP) {
2165                                 /* checks if there are render-result nodes that need scene */
2166                                 if((re->r.scemode & R_SINGLE_LAYER)==0)
2167                                         ntree_render_scenes(re);
2168                                 
2169                                 if(!re->test_break()) {
2170                                         ntree->stats_draw= render_composit_stats;
2171                                         ntree->test_break= re->test_break;
2172                                         /* in case it was never initialized */
2173                                         R.stats_draw= re->stats_draw;
2174                                         
2175                                         if(re->r.scemode & R_FULL_SAMPLE) 
2176                                                 do_merge_fullsample(re, ntree);
2177                                         else
2178                                                 ntreeCompositExecTree(ntree, &re->r, G.background==0);
2179                                         
2180                                         ntree->stats_draw= NULL;
2181                                         ntree->test_break= NULL;
2182                                 }
2183                         }
2184                         else if(re->r.scemode & R_FULL_SAMPLE)
2185                                 do_merge_fullsample(re, NULL);
2186                 }
2187         }
2188
2189         /* weak... the display callback wants an active renderlayer pointer... */
2190         re->result->renlay= render_get_active_layer(re, re->result);
2191         re->display_draw(re->result, NULL);
2192 }
2193
2194 #ifndef DISABLE_YAFRAY
2195 /* yafray: main yafray render/export call */
2196 static void yafrayRender(Render *re)
2197 {
2198         RE_FreeRenderResult(re->result);
2199         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2200         
2201         // need this too, for aspect/ortho/etc info
2202         RE_SetCamera(re, re->scene->camera);
2203
2204         // switch must be done before prepareScene()
2205         if (!re->r.YFexportxml)
2206                 YAF_switchFile();
2207         else
2208                 YAF_switchPlugin();
2209         
2210         printf("Starting scene conversion.\n");
2211         RE_Database_FromScene(re, re->scene, 1);
2212         printf("Scene conversion done.\n");
2213         
2214         re->i.starttime = PIL_check_seconds_timer();
2215         
2216         YAF_exportScene(re);
2217
2218         /* also needed for yafray border render, straight copy from do_render_fields_blur_3d() */
2219         /* when border render, check if we have to insert it in black */
2220         if(re->result) {
2221                 if(re->r.mode & R_BORDER) {
2222                         if((re->r.mode & R_CROP)==0) {
2223                                 RenderResult *rres;
2224                                 
2225                                 /* sub-rect for merge call later on */
2226                                 re->result->tilerect= re->disprect;
2227                                 
2228                                 /* this copying sequence could become function? */
2229                                 re->disprect.xmin= re->disprect.ymin= 0;
2230                                 re->disprect.xmax= re->winx;
2231                                 re->disprect.ymax= re->winy;
2232                                 re->rectx= re->winx;
2233                                 re->recty= re->winy;
2234                                 
2235                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2236                                 
2237                                 merge_render_result(rres, re->result);
2238                                 RE_FreeRenderResult(re->result);
2239                                 re->result= rres;
2240                                 
2241                                 re->display_init(re->result);
2242                                 re->display_draw(re->result, NULL);
2243                         }
2244                 }
2245         }
2246
2247         re->i.lastframetime = PIL_check_seconds_timer()- re->i.starttime;
2248         re->stats_draw(&re->i);
2249         
2250         RE_Database_Free(re);
2251 }
2252
2253
2254
2255 #endif /* disable yafray */
2256
2257 static void renderresult_stampinfo()
2258 {
2259         RenderResult rres;
2260         /* this is the basic trick to get the displayed float or char rect from render result */
2261         RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
2262         BKE_stamp_buf((unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
2263 }
2264
2265 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2266
2267 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2268 static void do_render_all_options(Render *re)
2269 {
2270         re->i.starttime= PIL_check_seconds_timer();
2271
2272         /* ensure no images are in memory from previous animated sequences */
2273         BKE_image_all_free_anim_ibufs(re->r.cfra);
2274         
2275         if(re->r.scemode & R_DOSEQ) {
2276                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2277                 if(!re->test_break()) 
2278                         do_render_seq(re->result, re->r.cfra);
2279                 
2280                 re->stats_draw(&re->i);
2281                 re->display_draw(re->result, NULL);
2282                 
2283         }
2284         else {
2285 #ifndef DISABLE_YAFRAY
2286                 if(re->r.renderer==R_YAFRAY)
2287                         yafrayRender(re);
2288                 else
2289                         do_render_composite_fields_blur_3d(re);
2290 #else
2291                 do_render_composite_fields_blur_3d(re);
2292 #endif
2293         }
2294         
2295         /* for UI only */
2296         renderresult_add_names(re->result);
2297         
2298         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2299         
2300         re->stats_draw(&re->i);
2301         
2302         /* stamp image info here */
2303         if((G.scene->r.scemode & R_STAMP_INFO) && (G.scene->r.stamp & R_STAMP_DRAW)) {
2304                 renderresult_stampinfo();
2305                 re->display_draw(re->result, NULL);
2306         }
2307 }
2308
2309 static int is_rendering_allowed(Render *re)
2310 {
2311         SceneRenderLayer *srl;
2312         
2313         /* forbidden combinations */
2314         if(re->r.mode & R_PANORAMA) {
2315                 if(re->r.mode & R_BORDER) {
2316                         re->error("No border supported for Panorama");
2317                         return 0;
2318                 }
2319                 if(re->r.mode & R_ORTHO) {
2320                         re->error("No Ortho render possible for Panorama");
2321                         return 0;
2322                 }
2323         }
2324         
2325         if(re->r.mode & R_BORDER) {
2326                 if(re->r.border.xmax <= re->r.border.xmin || 
2327                    re->r.border.ymax <= re->r.border.ymin) {
2328                         re->error("No border area selected.");
2329                         return 0;
2330                 }
2331                 if(re->r.scemode & R_EXR_TILE_FILE) {
2332                         re->error("Border render and Buffer-save not supported yet");
2333                         return 0;
2334                 }
2335         }
2336         
2337         if(re->r.scemode & R_EXR_TILE_FILE) {
2338                 char str[FILE_MAX];
2339                 
2340                 render_unique_exr_name(re, str, 0);
2341                 
2342                 if (BLI_is_writable(str)==0) {
2343                         re->error("Can not save render buffers, check the temp default path");
2344                         return 0;
2345                 }
2346                 
2347                 /* no osa + fullsample won't work... */
2348                 if(re->osa==0)
2349                         re->r.scemode &= ~R_FULL_SAMPLE;
2350                 
2351         }
2352         else
2353                 re->r.scemode &= ~R_FULL_SAMPLE;        /* clear to be sure */
2354         
2355         if(re->r.scemode & R_DOCOMP) {
2356                 if(re->scene->use_nodes) {
2357                         bNodeTree *ntree= re->scene->nodetree;
2358                         bNode *node;
2359                 
2360                         if(ntree==NULL) {
2361                                 re->error("No Nodetree in Scene");
2362                                 return 0;
2363                         }
2364                         
2365                         for(node= ntree->nodes.first; node; node= node->next)
2366                                 if(node->type==CMP_NODE_COMPOSITE)
2367                                         break;
2368                         
2369                         
2370                         if(node==NULL) {
2371                                 re->error("No Render Output Node in Scene");
2372                                 return 0;
2373                         }
2374                 }
2375         }
2376         
2377         /* check valid camera, without camera render is OK (compo, seq) */
2378         if(re->scene->camera==NULL)
2379                 re->scene->camera= scene_find_camera(re->scene);
2380         
2381         if(!(re->r.scemode & (R_DOSEQ|R_DOCOMP))) {
2382                 if(re->scene->camera==NULL) {
2383                         re->error("No camera");
2384                         return 0;
2385                 }
2386         }
2387         
2388         /* layer flag tests */
2389         if(re->r.scemode & R_SINGLE_LAYER) {
2390                 srl= BLI_findlink(&re->scene->r.layers, re->r.actlay);
2391                 /* force layer to be enabled */
2392                 srl->layflag &= ~SCE_LAY_DISABLE;
2393         }
2394         
2395         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
2396                 if(!(srl->layflag & SCE_LAY_DISABLE))
2397                         break;
2398         if(srl==NULL) {
2399                 re->error("All RenderLayers are disabled");
2400                 return 0;
2401         }
2402         
2403         /* renderer */
2404         if(!ELEM(re->r.renderer, R_INTERN, R_YAFRAY)) {
2405                 re->error("Unknown render engine set");
2406                 return 0;
2407         }
2408         return 1;
2409 }
2410
2411 /* evaluating scene options for general Blender render */
2412 static int render_initialize_from_scene(Render *re, Scene *scene)
2413 {
2414         int winx, winy;
2415         rcti disprect;
2416         
2417         /* r.xsch and r.ysch has the actual view window size
2418                 r.border is the clipping rect */
2419         
2420         /* calculate actual render result and display size */
2421         winx= (scene->r.size*scene->r.xsch)/100;
2422         winy= (scene->r.size*scene->r.ysch)/100;
2423         
2424         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2425         if(scene->r.mode & R_BORDER) {
2426                 disprect.xmin= scene->r.border.xmin*winx;
2427                 disprect.xmax= scene->r.border.xmax*winx;
2428                 
2429                 disprect.ymin= scene->r.border.ymin*winy;
2430                 disprect.ymax= scene->r.border.ymax*winy;
2431         }
2432         else {
2433                 disprect.xmin= disprect.ymin= 0;
2434                 disprect.xmax= winx;
2435                 disprect.ymax= winy;
2436         }
2437         
2438         re->scene= scene;
2439         
2440         /* check all scenes involved */
2441         tag_scenes_for_render(re);
2442         
2443         if(scene->r.scemode & R_SINGLE_LAYER)
2444                 push_render_result(re);
2445         
2446         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2447         if(!re->ok)  /* if an error was printed, abort */
2448                 return 0;
2449         
2450         /* initstate makes new result, have to send changed tags around */
2451         ntreeCompositTagRender(re->scene);
2452         
2453         if(!is_rendering_allowed(re))
2454                 return 0;
2455         
2456         re->display_init(re->result);
2457         re->display_clear(re->result);
2458         
2459         return 1;
2460 }
2461
2462 /* general Blender frame render call */
2463 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
2464 {
2465         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2466         /* is also set by caller renderwin.c */
2467         G.rendering= 1;
2468         
2469         scene->r.cfra= frame;
2470         
2471         if(render_initialize_from_scene(re, scene)) {
2472                 do_render_all_options(re);
2473         }
2474         
2475         /* UGLY WARNING */
2476         G.rendering= 0;
2477 }
2478
2479 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
2480 {
2481         char name[FILE_MAX];
2482         RenderResult rres;
2483         
2484         RE_GetResultImage(re, &rres);
2485
2486         /* write movie or image */
2487         if(BKE_imtype_is_movie(scene->r.imtype)) {
2488                 int dofree = 0;
2489                 /* note; the way it gets 32 bits rects is weak... */
2490                 if(rres.rect32==NULL) {
2491                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2492                         dofree = 1;
2493                 }
2494                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
2495                 mh->append_movie(scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
2496                 if(dofree) {
2497                         MEM_freeN(rres.rect32);
2498                 }
2499                 printf("Append frame %d", scene->r.cfra);
2500         } 
2501         else {
2502                 BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2503                 
2504                 if(re->r.imtype==R_MULTILAYER) {
2505                         if(re->result) {
2506                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2507                                 printf("Saved: %s", name);
2508                         }
2509                 }
2510                 else {
2511                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
2512                         int ok;
2513                         
2514                                         /* if not exists, BKE_write_ibuf makes one */
2515                         ibuf->rect= (unsigned int *)rres.rect32;    
2516                         ibuf->rect_float= rres.rectf;
2517                         ibuf->zbuf_float= rres.rectz;
2518                         
2519                         /* float factor for random dither, imbuf takes care of it */
2520                         ibuf->dither= scene->r.dither_intensity;
2521
2522                         ok= BKE_write_ibuf(ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2523                         
2524                         if(ok==0) {
2525                                 printf("Render error: cannot save %s\n", name);
2526                                 G.afbreek=1;
2527                         }
2528                         else printf("Saved: %s", name);
2529                         
2530                         /* optional preview images for exr */
2531                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
2532                                 if(BLI_testextensie(name, ".exr")) 
2533                                         name[strlen(name)-4]= 0;
2534                                 BKE_add_image_extension(name, R_JPEG90);
2535                                 ibuf->depth= 24; 
2536                                 BKE_write_ibuf(ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
2537                                 printf("\nSaved: %s", name);
2538                         }
2539                         
2540                                         /* imbuf knows which rects are not part of ibuf */
2541                         IMB_freeImBuf(ibuf);
2542                 }
2543         }
2544         
2545         BLI_timestr(re->i.lastframetime, name);
2546         printf(" Time: %s\n", name);
2547         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2548 }
2549
2550 /* saves images to disk */
2551 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
2552 {
2553         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
2554         int cfrao= scene->r.cfra;
2555         
2556         /* do not call for each frame, it initializes & pops output window */
2557         if(!render_initialize_from_scene(re, scene))
2558                 return;
2559         
2560         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2561         /* is also set by caller renderwin.c */
2562         G.rendering= 1;
2563         
2564         if(BKE_imtype_is_movie(scene->r.imtype))
2565                 mh->start_movie(&re->r, re->rectx, re->recty);
2566         
2567         if (mh->get_next_frame) {
2568                 while (!(G.afbreek == 1)) {
2569                         int nf = mh->get_next_frame();
2570                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2571                                 scene->r.cfra = re->r.cfra = nf;
2572                                 
2573                                 do_render_all_options(re);
2574
2575                                 if(re->test_break() == 0) {
2576                                         do_write_image_or_movie(re, scene, mh);
2577                                 }
2578                         } else {
2579                                 re->test_break();
2580                         }
2581                 }
2582         } else {
2583                 for(scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
2584                         char name[FILE_MAX];
2585                         if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH) ) {
2586                                 BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2587                         }
2588                         
2589                         if (scene->r.mode & R_NO_OVERWRITE && BLI_exist(name)) {
2590                                 printf("skipping existing frame \"%s\"\n", name);
2591                                 continue;
2592                         }
2593                         if (scene->r.mode & R_TOUCH && !BLI_exist(name)) {
2594                                 BLI_make_existing_file(name); /* makes the dir if its not there */
2595                                 BLI_touch(name);
2596                         }
2597
2598                         re->r.cfra= scene->r.cfra;         /* weak.... */
2599                         
2600                         do_render_all_options(re);
2601                         
2602                         if(re->test_break() == 0) {
2603                                 do_write_image_or_movie(re, scene, mh);
2604                         }
2605                 
2606                         if(G.afbreek==1) {
2607                                 /* remove touched file */
2608                                 if (scene->r.mode & R_TOUCH && BLI_exist(name) && BLI_filepathsize(name) == 0) {
2609                                         BLI_delete(name, 0, 0);
2610                                 }
2611                                 
2612                                 break;
2613                         }
2614                 }
2615         }
2616         
2617         /* end movie */
2618         if(BKE_imtype_is_movie(scene->r.imtype))
2619                 mh->end_movie();
2620
2621         scene->r.cfra= cfrao;
2622         
2623         /* UGLY WARNING */
2624         G.rendering= 0;
2625 }
2626
2627 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2628
2629 /* only the temp file! */
2630 void RE_ReadRenderResult(Scene *scene, Scene *scenode)
2631 {
2632         Render *re;
2633         int winx, winy;
2634         rcti disprect;
2635         
2636         /* calculate actual render result and display size */
2637         winx= (scene->r.size*scene->r.xsch)/100;
2638         winy= (scene->r.size*scene->r.ysch)/100;
2639         
2640         /* only in movie case we render smaller part */
2641         if(scene->r.mode & R_BORDER) {
2642                 disprect.xmin= scene->r.border.xmin*winx;
2643                 disprect.xmax= scene->r.border.xmax*winx;
2644                 
2645                 disprect.ymin= scene->r.border.ymin*winy;
2646                 disprect.ymax= scene->r.border.ymax*winy;
2647         }
2648         else {
2649                 disprect.xmin= disprect.ymin= 0;
2650                 disprect.xmax= winx;
2651                 disprect.ymax= winy;
2652         }
2653         
2654         if(scenode)
2655                 scene= scenode;
2656         
2657         /* get render: it can be called from UI with draw callbacks */
2658         re= RE_GetRender(scene->id.name);
2659         if(re==NULL)
2660                 re= RE_NewRender(scene->id.name);
2661         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2662         re->scene= scene;
2663         
2664         read_render_result(re, 0);
2665 }
2666
2667 void RE_set_max_threads(int threads)
2668 {
2669         if (threads==0) {
2670                 commandline_threads = BLI_system_thread_count();
2671         } else if(threads>=1 && threads<=BLENDER_MAX_THREADS) {
2672                 commandline_threads= threads;
2673         } else {
2674                 printf("Error, threads has to be in range 1-%d\n", BLENDER_MAX_THREADS);
2675         }
2676 }