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