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