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