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