svn merge -r 23207:23528 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender-staging.git] / source / blender / render / intern / source / pipeline.c
1 /**  
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. 
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2006 Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <math.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "DNA_group_types.h"
35 #include "DNA_image_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_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+MAX_ID_NAME+100], 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 /* called for reading temp files, and for external engines */
883 static int read_render_result_from_file(char *filename, RenderResult *rr)
884 {
885         RenderLayer *rl;
886         RenderPass *rpass;
887         void *exrhandle= IMB_exr_get_handle();
888         int rectx, recty;
889
890         if(IMB_exr_begin_read(exrhandle, filename, &rectx, &recty)==0) {
891                 IMB_exr_close(exrhandle);
892                 return 0;
893         }
894         
895         if(rr == NULL || rectx!=rr->rectx || recty!=rr->recty) {
896                 printf("error in reading render result\n");
897                 IMB_exr_close(exrhandle);
898                 return 0;
899         }
900         else {
901                 for(rl= rr->layers.first; rl; rl= rl->next) {
902                         
903                         /* combined */
904                         if(rl->rectf) {
905                                 int a, xstride= 4;
906                                 for(a=0; a<xstride; a++)
907                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
908                                                                                 xstride, xstride*rectx, rl->rectf+a);
909                         }
910                         
911                         /* passes are allocated in sync */
912                         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
913                                 int a, xstride= rpass->channels;
914                                 for(a=0; a<xstride; a++)
915                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
916                                                                                 xstride, xstride*rectx, rpass->rect+a);
917                         }
918                         
919                 }
920                 IMB_exr_read_channels(exrhandle);
921                 renderresult_add_names(rr);
922         }
923         
924         IMB_exr_close(exrhandle);
925
926         return 1;
927 }
928
929 /* only for temp buffer files, makes exact copy of render result */
930 static void read_render_result(Render *re, int sample)
931 {
932         char str[FILE_MAX];
933
934         RE_FreeRenderResult(re->result);
935         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
936
937         render_unique_exr_name(re, str, sample);
938         printf("read exr tmp file: %s\n", str);
939
940         if(!read_render_result_from_file(str, re->result))
941                 printf("cannot read: %s\n", str);
942 }
943
944 /* *************************************************** */
945
946 Render *RE_GetRender(const char *name)
947 {
948         Render *re;
949         
950         /* search for existing renders */
951         for(re= RenderList.first; re; re= re->next) {
952                 if(strncmp(re->name, name, RE_MAXNAME)==0) {
953                         break;
954                 }
955         }
956         return re;
957 }
958
959 /* if you want to know exactly what has been done */
960 RenderResult *RE_GetResult(Render *re)
961 {
962         if(re)
963                 return re->result;
964         return NULL;
965 }
966
967 /* displist.c util.... */
968 Scene *RE_GetScene(Render *re)
969 {
970         if(re)
971                 return re->scene;
972         return NULL;
973 }
974
975 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
976 {
977         RenderLayer *rl= BLI_findlink(&rr->layers, re->r.actlay);
978         
979         if(rl) 
980                 return rl;
981         else 
982                 return rr->layers.first;
983 }
984
985
986 /* fill provided result struct with what's currently active or done */
987 void RE_GetResultImage(Render *re, RenderResult *rr)
988 {
989         memset(rr, 0, sizeof(RenderResult));
990
991         if(re && re->result) {
992                 RenderLayer *rl;
993                 
994                 rr->rectx= re->result->rectx;
995                 rr->recty= re->result->recty;
996                 
997                 rr->rectf= re->result->rectf;
998                 rr->rectz= re->result->rectz;
999                 rr->rect32= re->result->rect32;
1000                 
1001                 /* active layer */
1002                 rl= render_get_active_layer(re, re->result);
1003
1004                 if(rl) {
1005                         if(rr->rectf==NULL)
1006                                 rr->rectf= rl->rectf;
1007                         if(rr->rectz==NULL)
1008                                 rr->rectz= RE_RenderLayerGetPass(rl, SCE_PASS_Z);       
1009                 }
1010         }
1011 }
1012
1013 /* caller is responsible for allocating rect in correct size! */
1014 void RE_ResultGet32(Render *re, unsigned int *rect)
1015 {
1016         RenderResult rres;
1017         
1018         RE_GetResultImage(re, &rres);
1019         if(rres.rect32) 
1020                 memcpy(rect, rres.rect32, sizeof(int)*rres.rectx*rres.recty);
1021         else if(rres.rectf) {
1022                 float *fp= rres.rectf;
1023                 int tot= rres.rectx*rres.recty;
1024                 char *cp= (char *)rect;
1025                 
1026                 for(;tot>0; tot--, cp+=4, fp+=4) {
1027                         cp[0] = FTOCHAR(fp[0]);
1028                         cp[1] = FTOCHAR(fp[1]);
1029                         cp[2] = FTOCHAR(fp[2]);
1030                         cp[3] = FTOCHAR(fp[3]);
1031                 }
1032         }
1033         else
1034                 /* else fill with black */
1035                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
1036 }
1037
1038
1039 RenderStats *RE_GetStats(Render *re)
1040 {
1041         return &re->i;
1042 }
1043
1044 Render *RE_NewRender(const char *name)
1045 {
1046         Render *re;
1047         
1048         /* only one render per name exists */
1049         re= RE_GetRender(name);
1050         if(re==NULL) {
1051                 
1052                 /* new render data struct */
1053                 re= MEM_callocN(sizeof(Render), "new render");
1054                 BLI_addtail(&RenderList, re);
1055                 strncpy(re->name, name, RE_MAXNAME);
1056         }
1057         
1058         /* prevent UI to draw old results */
1059         RE_FreeRenderResult(re->result);
1060         re->result= NULL;
1061         re->result_ok= 0;
1062         
1063         /* set default empty callbacks */
1064         re->display_init= result_nothing;
1065         re->display_clear= result_nothing;
1066         re->display_draw= result_rcti_nothing;
1067         re->timecursor= int_nothing;
1068         re->test_break= void_nothing;
1069         re->error= print_error;
1070         if(G.background)
1071                 re->stats_draw= stats_background;
1072         else
1073                 re->stats_draw= stats_nothing;
1074         /* clear callback handles */
1075         re->dih= re->dch= re->ddh= re->sdh= re->tch= re->tbh= re->erh= NULL;
1076         
1077         /* init some variables */
1078         re->ycor= 1.0f;
1079         
1080         return re;
1081 }
1082
1083 /* only call this while you know it will remove the link too */
1084 void RE_FreeRender(Render *re)
1085 {
1086         
1087         free_renderdata_tables(re);
1088         free_sample_tables(re);
1089         
1090         RE_FreeRenderResult(re->result);
1091         RE_FreeRenderResult(re->pushedresult);
1092         
1093         BLI_remlink(&RenderList, re);
1094         MEM_freeN(re);
1095 }
1096
1097 /* exit blender */
1098 void RE_FreeAllRender(void)
1099 {
1100         while(RenderList.first) {
1101                 RE_FreeRender(RenderList.first);
1102         }
1103 }
1104
1105 /* ********* initialize state ******** */
1106
1107
1108 /* what doesn't change during entire render sequence */
1109 /* disprect is optional, if NULL it assumes full window render */
1110 void RE_InitState(Render *re, Render *source, RenderData *rd, int winx, int winy, rcti *disprect)
1111 {
1112         re->ok= TRUE;   /* maybe flag */
1113         
1114         re->i.starttime= PIL_check_seconds_timer();
1115         re->r= *rd;             /* hardcopy */
1116         
1117         re->winx= winx;
1118         re->winy= winy;
1119         if(disprect) {
1120                 re->disprect= *disprect;
1121                 re->rectx= disprect->xmax-disprect->xmin;
1122                 re->recty= disprect->ymax-disprect->ymin;
1123         }
1124         else {
1125                 re->disprect.xmin= re->disprect.ymin= 0;
1126                 re->disprect.xmax= winx;
1127                 re->disprect.ymax= winy;
1128                 re->rectx= winx;
1129                 re->recty= winy;
1130         }
1131         
1132         if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
1133                                                                                   (re->rectx < 16 || re->recty < 16) )) {
1134                 re->error(re->erh, "Image too small");
1135                 re->ok= 0;
1136         }
1137         else {
1138 #ifdef WITH_OPENEXR
1139                 if(re->r.scemode & R_FULL_SAMPLE)
1140                         re->r.scemode |= R_EXR_TILE_FILE;       /* enable automatic */
1141 #else
1142                 /* can't do this without openexr support */
1143                 re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1144 #endif
1145                 
1146                 /* fullsample wants uniform osa levels */
1147                 if(source && (re->r.scemode & R_FULL_SAMPLE)) {
1148                         /* but, if source has no full sample we disable it */
1149                         if((source->r.scemode & R_FULL_SAMPLE)==0)
1150                                 re->r.scemode &= ~R_FULL_SAMPLE;
1151                         else
1152                                 re->r.osa= re->osa= source->osa;
1153                 }
1154                 else {
1155                         /* check state variables, osa? */
1156                         if(re->r.mode & (R_OSA)) {
1157                                 re->osa= re->r.osa;
1158                                 if(re->osa>16) re->osa= 16;
1159                         }
1160                         else re->osa= 0;
1161                 }
1162
1163                 /* always call, checks for gamma, gamma tables and jitter too */
1164                 make_sample_tables(re); 
1165                 
1166                 /* if preview render, we try to keep old result */
1167                 if(re->r.scemode & R_PREVIEWBUTS) {
1168                         if(re->result && re->result->rectx==re->rectx && re->result->recty==re->recty);
1169                         else {
1170                                 RE_FreeRenderResult(re->result);
1171                                 re->result= NULL;
1172                         }
1173                 }
1174                 else {
1175                         
1176                         /* make empty render result, so display callbacks can initialize */
1177                         RE_FreeRenderResult(re->result);
1178                         re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1179                         re->result->rectx= re->rectx;
1180                         re->result->recty= re->recty;
1181                 }
1182                 
1183                 /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1184                 re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1185                 
1186                 RE_init_threadcount(re);
1187         }
1188 }
1189
1190 /* part of external api, not called for regular render pipeline */
1191 void RE_SetDispRect (struct Render *re, rcti *disprect)
1192 {
1193         re->disprect= *disprect;
1194         re->rectx= disprect->xmax-disprect->xmin;
1195         re->recty= disprect->ymax-disprect->ymin;
1196         
1197         /* initialize render result */
1198         RE_FreeRenderResult(re->result);
1199         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1200 }
1201
1202 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1203 {
1204         /* re->ok flag? */
1205         
1206         re->viewplane= *viewplane;
1207         re->clipsta= clipsta;
1208         re->clipend= clipend;
1209         re->r.mode &= ~R_ORTHO;
1210
1211         i_window(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1212         
1213 }
1214
1215 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1216 {
1217         /* re->ok flag? */
1218         
1219         re->viewplane= *viewplane;
1220         re->clipsta= clipsta;
1221         re->clipend= clipend;
1222         re->r.mode |= R_ORTHO;
1223
1224         i_ortho(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1225 }
1226
1227 void RE_SetView(Render *re, float mat[][4])
1228 {
1229         /* re->ok flag? */
1230         Mat4CpyMat4(re->viewmat, mat);
1231         Mat4Invert(re->viewinv, re->viewmat);
1232 }
1233
1234 /* image and movie output has to move to either imbuf or kernel */
1235 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1236 {
1237         re->display_init= f;
1238         re->dih= handle;
1239 }
1240 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1241 {
1242         re->display_clear= f;
1243         re->dch= handle;
1244 }
1245 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
1246 {
1247         re->display_draw= f;
1248         re->ddh= handle;
1249 }
1250 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
1251 {
1252         re->stats_draw= f;
1253         re->sdh= handle;
1254 }
1255 void RE_timecursor_cb(Render *re, void *handle, void (*f)(void *handle, int))
1256 {
1257         re->timecursor= f;
1258         re->tch= handle;
1259 }
1260
1261 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
1262 {
1263         re->test_break= f;
1264         re->tbh= handle;
1265 }
1266 void RE_error_cb(Render *re, void *handle, void (*f)(void *handle, char *str))
1267 {
1268         re->error= f;
1269         re->erh= handle;
1270 }
1271
1272
1273 /* ********* add object data (later) ******** */
1274
1275 /* object is considered fully prepared on correct time etc */
1276 /* includes lights */
1277 void RE_AddObject(Render *re, Object *ob)
1278 {
1279         
1280 }
1281
1282 /* *************************************** */
1283
1284 static int render_display_draw_enabled(Render *re)
1285 {
1286         /* don't show preprocess for previewrender sss */
1287         if(re->sss_points)
1288                 return !(re->r.scemode & R_PREVIEWBUTS);
1289         else
1290                 return 1;
1291 }
1292
1293 /* allocate osa new results for samples */
1294 static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
1295 {
1296         int a;
1297         
1298         if(re->osa==0)
1299                 return new_render_result(re, partrct, crop, RR_USEMEM);
1300         
1301         for(a=0; a<re->osa; a++) {
1302                 RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
1303                 BLI_addtail(lb, rr);
1304                 rr->sample_nr= a;
1305         }
1306         
1307         return lb->first;
1308 }
1309
1310
1311 /* the main thread call, renders an entire part */
1312 static void *do_part_thread(void *pa_v)
1313 {
1314         RenderPart *pa= pa_v;
1315         
1316         /* need to return nicely all parts on esc */
1317         if(R.test_break(R.tbh)==0) {
1318                 
1319                 if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
1320                         pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
1321                 else
1322                         pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1323
1324                 if(R.sss_points)
1325                         zbufshade_sss_tile(pa);
1326                 else if(R.osa)
1327                         zbufshadeDA_tile(pa);
1328                 else
1329                         zbufshade_tile(pa);
1330                 
1331                 /* merge too on break! */
1332                 if(R.result->exrhandle) {
1333                         RenderResult *rr, *rrpart;
1334                         
1335                         for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
1336                                 save_render_result_tile(rr, rrpart);
1337                         
1338                 }
1339                 else if(render_display_draw_enabled(&R)) {
1340                         /* on break, don't merge in result for preview renders, looks nicer */
1341                         if(R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS));
1342                         else merge_render_result(R.result, pa->result);
1343                 }
1344         }
1345         
1346         pa->ready= 1;
1347         
1348         return NULL;
1349 }
1350
1351 /* returns with render result filled, not threaded, used for preview now only */
1352 static void render_tile_processor(Render *re, int firsttile)
1353 {
1354         RenderPart *pa;
1355         
1356         if(re->test_break(re->tbh))
1357                 return;
1358
1359         /* hrmf... exception, this is used for preview render, re-entrant, so render result has to be re-used */
1360         if(re->result==NULL || re->result->layers.first==NULL) {
1361                 if(re->result) RE_FreeRenderResult(re->result);
1362                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1363         }
1364         
1365         re->stats_draw(re->sdh, &re->i);
1366  
1367         if(re->result==NULL)
1368                 return;
1369         
1370         initparts(re);
1371         
1372         /* assuming no new data gets added to dbase... */
1373         R= *re;
1374         
1375         for(pa= re->parts.first; pa; pa= pa->next) {
1376                 if(firsttile) {
1377                         re->i.partsdone++;      /* was reset in initparts */
1378                         firsttile--;
1379                 }
1380                 else {
1381                         do_part_thread(pa);
1382                         
1383                         if(pa->result) {
1384                                 if(!re->test_break(re->tbh)) {
1385                                         if(render_display_draw_enabled(re))
1386                                                 re->display_draw(re->ddh, pa->result, NULL);
1387                                         
1388                                         re->i.partsdone++;
1389                                         re->stats_draw(re->sdh, &re->i);
1390                                 }
1391                                 RE_FreeRenderResult(pa->result);
1392                                 pa->result= NULL;
1393                         }               
1394                         if(re->test_break(re->tbh))
1395                                 break;
1396                 }
1397         }
1398         
1399         freeparts(re);
1400 }
1401
1402 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1403 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1404 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1405 float panorama_pixel_rot(Render *re)
1406 {
1407         float psize, phi, xfac;
1408         
1409         /* size of 1 pixel mapped to viewplane coords */
1410         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
1411         /* angle of a pixel */
1412         phi= atan(psize/re->clipsta);
1413         
1414         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1415         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1416         xfac= atan(0.5f*xfac/re->clipsta); 
1417         /* and how much the same viewplane angle is wrapped */
1418         psize= 0.5f*phi*((float)re->partx);
1419         
1420         /* the ratio applied to final per-pixel angle */
1421         phi*= xfac/psize;
1422         
1423         return phi;
1424 }
1425
1426 /* call when all parts stopped rendering, to find the next Y slice */
1427 /* if slice found, it rotates the dbase */
1428 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1429 {
1430         RenderPart *pa, *best= NULL;
1431         
1432         *minx= re->winx;
1433         
1434         /* most left part of the non-rendering parts */
1435         for(pa= re->parts.first; pa; pa= pa->next) {
1436                 if(pa->ready==0 && pa->nr==0) {
1437                         if(pa->disprect.xmin < *minx) {
1438                                 best= pa;
1439                                 *minx= pa->disprect.xmin;
1440                         }
1441                 }
1442         }
1443                         
1444         if(best) {
1445                 float phi= panorama_pixel_rot(re);
1446
1447                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1448                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
1449                 
1450                 /* shift viewplane */
1451                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1452                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1453                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1454                 Mat4CpyMat4(R.winmat, re->winmat);
1455                 
1456                 /* rotate database according to part coordinates */
1457                 project_renderdata(re, projectverto, 1, -R.panodxp*phi, 1);
1458                 R.panosi= sin(R.panodxp*phi);
1459                 R.panoco= cos(R.panodxp*phi);
1460         }
1461         return best;
1462 }
1463
1464 static RenderPart *find_next_part(Render *re, int minx)
1465 {
1466         RenderPart *pa, *best= NULL;
1467         int centx=re->winx/2, centy=re->winy/2, tot=1;
1468         int mindist, distx, disty;
1469         
1470         /* find center of rendered parts, image center counts for 1 too */
1471         for(pa= re->parts.first; pa; pa= pa->next) {
1472                 if(pa->ready) {
1473                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1474                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1475                         tot++;
1476                 }
1477         }
1478         centx/=tot;
1479         centy/=tot;
1480         
1481         /* closest of the non-rendering parts */
1482         mindist= re->winx*re->winy;
1483         for(pa= re->parts.first; pa; pa= pa->next) {
1484                 if(pa->ready==0 && pa->nr==0) {
1485                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1486                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1487                         distx= (int)sqrt(distx*distx + disty*disty);
1488                         if(distx<mindist) {
1489                                 if(re->r.mode & R_PANORAMA) {
1490                                         if(pa->disprect.xmin==minx) {
1491                                                 best= pa;
1492                                                 mindist= distx;
1493                                         }
1494                                 }
1495                                 else {
1496                                         best= pa;
1497                                         mindist= distx;
1498                                 }
1499                         }
1500                 }
1501         }
1502         return best;
1503 }
1504
1505 static void print_part_stats(Render *re, RenderPart *pa)
1506 {
1507         char str[64];
1508         
1509         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1510         re->i.infostr= str;
1511         re->stats_draw(re->sdh, &re->i);
1512         re->i.infostr= NULL;
1513 }
1514
1515 /* make osa new results for samples */
1516 static RenderResult *new_full_sample_buffers_exr(Render *re)
1517 {
1518         int a;
1519         
1520         for(a=0; a<re->osa; a++) {
1521                 RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
1522                 BLI_addtail(&re->fullresult, rr);
1523                 rr->sample_nr= a;
1524         }
1525         
1526         return re->fullresult.first;
1527 }
1528
1529 static void threaded_tile_processor(Render *re)
1530 {
1531         ListBase threads;
1532         RenderPart *pa, *nextpa;
1533         rctf viewplane= re->viewplane;
1534         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1535         
1536         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
1537         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
1538                 RE_FreeRenderResult(re->result);
1539         
1540                 if(re->sss_points && render_display_draw_enabled(re))
1541                         re->result= new_render_result(re, &re->disprect, 0, 0);
1542                 else if(re->r.scemode & R_FULL_SAMPLE)
1543                         re->result= new_full_sample_buffers_exr(re);
1544                 else
1545                         re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
1546         }
1547         
1548         if(re->result==NULL)
1549                 return;
1550         
1551         /* warning; no return here without closing exr file */
1552         
1553         initparts(re);
1554         
1555         if(re->result->exrhandle) {
1556                 RenderResult *rr;
1557                 char str[FILE_MAX];
1558                 
1559                 for(rr= re->result; rr; rr= rr->next) {
1560                         render_unique_exr_name(re, str, rr->sample_nr);
1561                 
1562                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1563                         IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1564                 }
1565         }
1566         
1567         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1568         
1569         /* assuming no new data gets added to dbase... */
1570         R= *re;
1571         
1572         /* set threadsafe break */
1573         R.test_break= thread_break;
1574         
1575         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1576         if(re->r.mode & R_PANORAMA)
1577                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1578         else
1579                 nextpa= find_next_part(re, 0);
1580         
1581         while(rendering) {
1582                 
1583                 if(re->test_break(re->tbh))
1584                         PIL_sleep_ms(50);
1585                 else if(nextpa && BLI_available_threads(&threads)) {
1586                         drawtimer= 0;
1587                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1588                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1589                         BLI_insert_thread(&threads, nextpa);
1590
1591                         nextpa= find_next_part(re, minx);
1592                 }
1593                 else if(re->r.mode & R_PANORAMA) {
1594                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1595                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1596                         else {
1597                                 PIL_sleep_ms(50);
1598                                 drawtimer++;
1599                         }
1600                 }
1601                 else {
1602                         PIL_sleep_ms(50);
1603                         drawtimer++;
1604                 }
1605                 
1606                 /* check for ready ones to display, and if we need to continue */
1607                 rendering= 0;
1608                 hasdrawn= 0;
1609                 for(pa= re->parts.first; pa; pa= pa->next) {
1610                         if(pa->ready) {
1611                                 
1612                                 BLI_remove_thread(&threads, pa);
1613                                 
1614                                 if(pa->result) {
1615                                         if(render_display_draw_enabled(re))
1616                                                 re->display_draw(re->ddh, pa->result, NULL);
1617                                         print_part_stats(re, pa);
1618                                         
1619                                         free_render_result(&pa->fullresult, pa->result);
1620                                         pa->result= NULL;
1621                                         re->i.partsdone++;
1622                                         hasdrawn= 1;
1623                                 }
1624                         }
1625                         else {
1626                                 rendering= 1;
1627                                 if(pa->nr && pa->result && drawtimer>20) {
1628                                         if(render_display_draw_enabled(re))
1629                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
1630                                         hasdrawn= 1;
1631                                 }
1632                         }
1633                 }
1634                 if(hasdrawn)
1635                         drawtimer= 0;
1636
1637                 /* on break, wait for all slots to get freed */
1638                 if( (g_break=re->test_break(re->tbh)) && BLI_available_threads(&threads)==re->r.threads)
1639                         rendering= 0;
1640                 
1641         }
1642         
1643         if(re->result->exrhandle) {
1644                 RenderResult *rr;
1645
1646                 save_empty_result_tiles(re);
1647                 
1648                 for(rr= re->result; rr; rr= rr->next) {
1649                         IMB_exr_close(rr->exrhandle);
1650                         rr->exrhandle= NULL;
1651                 }
1652                 
1653                 free_render_result(&re->fullresult, re->result);
1654                 re->result= NULL;
1655                 
1656                 read_render_result(re, 0);
1657         }
1658         
1659         /* unset threadsafety */
1660         g_break= 0;
1661         
1662         BLI_end_threads(&threads);
1663         freeparts(re);
1664         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1665 }
1666
1667 /* currently only called by preview renders and envmap */
1668 void RE_TileProcessor(Render *re, int firsttile, int threaded)
1669 {
1670         /* the partsdone variable has to be reset to firsttile, to survive esc before it was set to zero */
1671         
1672         re->i.partsdone= firsttile;
1673
1674         if(!re->sss_points)
1675                 re->i.starttime= PIL_check_seconds_timer();
1676
1677         if(threaded)
1678                 threaded_tile_processor(re);
1679         else
1680                 render_tile_processor(re, firsttile);
1681                 
1682         if(!re->sss_points)
1683                 re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1684         re->stats_draw(re->sdh, &re->i);
1685 }
1686
1687
1688 /* ************  This part uses API, for rendering Blender scenes ********** */
1689
1690 static void external_render_3d(Render *re, RenderEngineType *type);
1691
1692 static void do_render_3d(Render *re)
1693 {
1694         RenderEngineType *type;
1695
1696         /* try external */
1697         for(type=R_engines.first; type; type=type->next)
1698                 if(strcmp(type->idname, re->r.engine) == 0)
1699                         break;
1700
1701         if(type && type->render) {
1702                 external_render_3d(re, type);
1703                 return;
1704         }
1705
1706         /* internal */
1707         
1708 //      re->cfra= cfra; /* <- unused! */
1709         
1710         /* make render verts/faces/halos/lamps */
1711         if(render_scene_needs_vector(re))
1712                 RE_Database_FromScene_Vectors(re, re->scene);
1713         else
1714            RE_Database_FromScene(re, re->scene, 1);
1715         
1716         threaded_tile_processor(re);
1717         
1718         /* do left-over 3d post effects (flares) */
1719         if(re->flag & R_HALO)
1720                 if(!re->test_break(re->tbh))
1721                         add_halo_flare(re);
1722         
1723         /* free all render verts etc */
1724         RE_Database_Free(re);
1725 }
1726
1727 /* called by blur loop, accumulate RGBA key alpha */
1728 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
1729 {
1730         float mfac= 1.0f - blurfac;
1731         int a, b, stride= 4*rr->rectx;
1732         int len= stride*sizeof(float);
1733         
1734         for(a=0; a<rr->recty; a++) {
1735                 if(blurfac==1.0f) {
1736                         memcpy(rectf, rectf1, len);
1737                 }
1738                 else {
1739                         float *rf= rectf, *rf1= rectf1;
1740                         
1741                         for( b= rr->rectx; b>0; b--, rf+=4, rf1+=4) {
1742                                 if(rf1[3]<0.01f)
1743                                         rf[3]= mfac*rf[3];
1744                                 else if(rf[3]<0.01f) {
1745                                         rf[0]= rf1[0];
1746                                         rf[1]= rf1[1];
1747                                         rf[2]= rf1[2];
1748                                         rf[3]= blurfac*rf1[3];
1749                                 }
1750                                 else {
1751                                         rf[0]= mfac*rf[0] + blurfac*rf1[0];
1752                                         rf[1]= mfac*rf[1] + blurfac*rf1[1];
1753                                         rf[2]= mfac*rf[2] + blurfac*rf1[2];
1754                                         rf[3]= mfac*rf[3] + blurfac*rf1[3];
1755                                 }                               
1756                         }
1757                 }
1758                 rectf+= stride;
1759                 rectf1+= stride;
1760         }
1761 }
1762
1763 /* called by blur loop, accumulate renderlayers */
1764 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1765 {
1766         float mfac= 1.0f - blurfac;
1767         int a, b, stride= channels*rr->rectx;
1768         int len= stride*sizeof(float);
1769         
1770         for(a=0; a<rr->recty; a++) {
1771                 if(blurfac==1.0f) {
1772                         memcpy(rectf, rectf1, len);
1773                 }
1774                 else {
1775                         float *rf= rectf, *rf1= rectf1;
1776                         
1777                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1778                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1779                         }
1780                 }
1781                 rectf+= stride;
1782                 rectf1+= stride;
1783         }
1784 }
1785
1786
1787 /* called by blur loop, accumulate renderlayers */
1788 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1789 {
1790         RenderLayer *rl, *rl1;
1791         RenderPass *rpass, *rpass1;
1792         
1793         rl1= brr->layers.first;
1794         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1795                 
1796                 /* combined */
1797                 if(rl->rectf && rl1->rectf) {
1798                         if(key_alpha)
1799                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1800                         else
1801                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1802                 }
1803                 
1804                 /* passes are allocated in sync */
1805                 rpass1= rl1->passes.first;
1806                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1807                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1808                 }
1809         }
1810 }
1811
1812 /* main blur loop, can be called by fields too */
1813 static void do_render_blur_3d(Render *re)
1814 {
1815         RenderResult *rres;
1816         float blurfac;
1817         int blur= re->r.osa;
1818         
1819         /* create accumulation render result */
1820         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1821         
1822         /* do the blur steps */
1823         while(blur--) {
1824                 set_mblur_offs( re->r.blurfac*((float)(re->r.osa-blur))/(float)re->r.osa );
1825                 
1826                 re->i.curblur= re->r.osa-blur;  /* stats */
1827                 
1828                 do_render_3d(re);
1829                 
1830                 blurfac= 1.0f/(float)(re->r.osa-blur);
1831                 
1832                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1833                 if(re->test_break(re->tbh)) break;
1834         }
1835         
1836         /* swap results */
1837         RE_FreeRenderResult(re->result);
1838         re->result= rres;
1839         
1840         set_mblur_offs(0.0f);
1841         re->i.curblur= 0;       /* stats */
1842         
1843         /* weak... the display callback wants an active renderlayer pointer... */
1844         re->result->renlay= render_get_active_layer(re, re->result);
1845         re->display_draw(re->ddh, re->result, NULL);    
1846 }
1847
1848
1849 /* function assumes rectf1 and rectf2 to be half size of rectf */
1850 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1851 {
1852         int a, stride= channels*rr->rectx;
1853         int len= stride*sizeof(float);
1854         
1855         for(a=0; a<rr->recty; a+=2) {
1856                 memcpy(rectf, rectf1, len);
1857                 rectf+= stride;
1858                 rectf1+= stride;
1859                 memcpy(rectf, rectf2, len);
1860                 rectf+= stride;
1861                 rectf2+= stride;
1862         }
1863 }
1864
1865 /* merge render results of 2 fields */
1866 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1867 {
1868         RenderLayer *rl, *rl1, *rl2;
1869         RenderPass *rpass, *rpass1, *rpass2;
1870         
1871         rl1= rr1->layers.first;
1872         rl2= rr2->layers.first;
1873         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1874                 
1875                 /* combined */
1876                 if(rl->rectf && rl1->rectf && rl2->rectf)
1877                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1878                 
1879                 /* passes are allocated in sync */
1880                 rpass1= rl1->passes.first;
1881                 rpass2= rl2->passes.first;
1882                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1883                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1884                 }
1885         }
1886 }
1887
1888
1889 /* interleaves 2 frames */
1890 static void do_render_fields_3d(Render *re)
1891 {
1892         RenderResult *rr1, *rr2= NULL;
1893         
1894         /* no render result was created, we can safely halve render y */
1895         re->winy /= 2;
1896         re->recty /= 2;
1897         re->disprect.ymin /= 2;
1898         re->disprect.ymax /= 2;
1899         
1900         re->i.curfield= 1;      /* stats */
1901         
1902         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1903         RE_SetCamera(re, re->scene->camera);
1904         if(re->r.mode & R_MBLUR)
1905                 do_render_blur_3d(re);
1906         else
1907                 do_render_3d(re);
1908         rr1= re->result;
1909         re->result= NULL;
1910         
1911         /* second field */
1912         if(!re->test_break(re->tbh)) {
1913                 
1914                 re->i.curfield= 2;      /* stats */
1915                 
1916                 re->flag |= R_SEC_FIELD;
1917                 if((re->r.mode & R_FIELDSTILL)==0) 
1918                         set_field_offs(0.5f);
1919                 RE_SetCamera(re, re->scene->camera);
1920                 if(re->r.mode & R_MBLUR)
1921                         do_render_blur_3d(re);
1922                 else
1923                         do_render_3d(re);
1924                 re->flag &= ~R_SEC_FIELD;
1925                 set_field_offs(0.0f);
1926                 
1927                 rr2= re->result;
1928         }
1929         
1930         /* allocate original height new buffers */
1931         re->winy *= 2;
1932         re->recty *= 2;
1933         re->disprect.ymin *= 2;
1934         re->disprect.ymax *= 2;
1935         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1936         
1937         if(rr2) {
1938                 if(re->r.mode & R_ODDFIELD)
1939                         merge_renderresult_fields(re->result, rr2, rr1);
1940                 else
1941                         merge_renderresult_fields(re->result, rr1, rr2);
1942                 
1943                 RE_FreeRenderResult(rr2);
1944         }
1945         RE_FreeRenderResult(rr1);
1946         
1947         re->i.curfield= 0;      /* stats */
1948         
1949         /* weak... the display callback wants an active renderlayer pointer... */
1950         re->result->renlay= render_get_active_layer(re, re->result);
1951         re->display_draw(re->ddh, re->result, NULL);
1952 }
1953
1954 static void load_backbuffer(Render *re)
1955 {
1956         if(re->r.alphamode == R_ADDSKY) {
1957                 ImBuf *ibuf;
1958                 char name[256];
1959                 
1960                 strcpy(name, re->r.backbuf);
1961                 BLI_convertstringcode(name, G.sce);
1962                 BLI_convertstringframe(name, re->r.cfra);
1963                 
1964                 if(re->backbuf) {
1965                         re->backbuf->id.us--;
1966                         if(re->backbuf->id.us<1)
1967                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
1968                 }
1969                 
1970                 re->backbuf= BKE_add_image_file(name, re->r.cfra);
1971                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
1972                 if(ibuf==NULL) {
1973                         // error() doesnt work with render window open
1974                         //error("No backbuf there!");
1975                         printf("Error: No backbuf %s\n", name);
1976                 }
1977                 else {
1978                         if (re->r.mode & R_FIELDS)
1979                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
1980                 }
1981         }
1982 }
1983
1984 /* main render routine, no compositing */
1985 static void do_render_fields_blur_3d(Render *re)
1986 {
1987         /* also check for camera here */
1988         if(re->scene->camera==NULL) {
1989                 printf("ERROR: Cannot render, no camera\n");
1990                 G.afbreek= 1;
1991                 return;
1992         }
1993         
1994         /* backbuffer initialize */
1995         if(re->r.bufflag & 1)
1996                 load_backbuffer(re);
1997
1998         /* now use renderdata and camera to set viewplane */
1999         RE_SetCamera(re, re->scene->camera);
2000         
2001         if(re->r.mode & R_FIELDS)
2002                 do_render_fields_3d(re);
2003         else if(re->r.mode & R_MBLUR)
2004                 do_render_blur_3d(re);
2005         else
2006                 do_render_3d(re);
2007         
2008         /* when border render, check if we have to insert it in black */
2009         if(re->result) {
2010                 if(re->r.mode & R_BORDER) {
2011                         if((re->r.mode & R_CROP)==0) {
2012                                 RenderResult *rres;
2013                                 
2014                                 /* sub-rect for merge call later on */
2015                                 re->result->tilerect= re->disprect;
2016                                 
2017                                 /* this copying sequence could become function? */
2018                                 /* weak is: it chances disprect from border */
2019                                 re->disprect.xmin= re->disprect.ymin= 0;
2020                                 re->disprect.xmax= re->winx;
2021                                 re->disprect.ymax= re->winy;
2022                                 re->rectx= re->winx;
2023                                 re->recty= re->winy;
2024                                 
2025                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2026                                 
2027                                 merge_render_result(rres, re->result);
2028                                 RE_FreeRenderResult(re->result);
2029                                 re->result= rres;
2030                                 
2031                                 /* weak... the display callback wants an active renderlayer pointer... */
2032                                 re->result->renlay= render_get_active_layer(re, re->result);
2033                                 
2034                                 re->display_init(re->dih, re->result);
2035                                 re->display_draw(re->ddh, re->result, NULL);
2036                         }
2037                 }
2038         }
2039 }
2040
2041
2042 /* within context of current Render *re, render another scene.
2043    it uses current render image size and disprect, but doesn't execute composite
2044 */
2045 static void render_scene(Render *re, Scene *sce, int cfra)
2046 {
2047         Render *resc= RE_NewRender(sce->id.name);
2048         int winx= re->winx, winy= re->winy;
2049         
2050         sce->r.cfra= cfra;
2051                 
2052         /* exception: scene uses own size (unfinished code) */
2053         if(0) {
2054                 winx= (sce->r.size*sce->r.xsch)/100;
2055                 winy= (sce->r.size*sce->r.ysch)/100;
2056         }
2057         
2058         /* initial setup */
2059         RE_InitState(resc, re, &sce->r, winx, winy, &re->disprect);
2060         
2061         /* still unsure entity this... */
2062         resc->scene= sce;
2063         
2064         /* ensure scene has depsgraph, base flags etc OK */
2065         set_scene_bg(sce);
2066
2067         /* copy callbacks */
2068         resc->display_draw= re->display_draw;
2069         resc->ddh= re->ddh;
2070         resc->test_break= re->test_break;
2071         resc->tbh= re->tbh;
2072         resc->stats_draw= re->stats_draw;
2073         resc->sdh= re->sdh;
2074         
2075         do_render_fields_blur_3d(resc);
2076 }
2077
2078 static void tag_scenes_for_render(Render *re)
2079 {
2080         bNode *node;
2081         Scene *sce;
2082         
2083         for(sce= G.main->scene.first; sce; sce= sce->id.next)
2084                 sce->id.flag &= ~LIB_DOIT;
2085         
2086         re->scene->id.flag |= LIB_DOIT;
2087         
2088         if(re->scene->nodetree==NULL) return;
2089         
2090         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
2091         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2092                 if(node->type==CMP_NODE_R_LAYERS) {
2093                         if(node->id) {
2094                                 if(node->id != (ID *)re->scene)
2095                                         node->id->flag |= LIB_DOIT;
2096                         }
2097                 }
2098         }
2099         
2100 }
2101
2102 static void ntree_render_scenes(Render *re)
2103 {
2104         bNode *node;
2105         int cfra= re->scene->r.cfra;
2106         
2107         if(re->scene->nodetree==NULL) return;
2108         
2109         tag_scenes_for_render(re);
2110         
2111         /* now foreach render-result node tagged we do a full render */
2112         /* results are stored in a way compisitor will find it */
2113         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2114                 if(node->type==CMP_NODE_R_LAYERS) {
2115                         if(node->id && node->id != (ID *)re->scene) {
2116                                 if(node->id->flag & LIB_DOIT) {
2117                                         render_scene(re, (Scene *)node->id, cfra);
2118                                         node->id->flag &= ~LIB_DOIT;
2119                                 }
2120                         }
2121                 }
2122         }
2123 }
2124
2125 /* helper call to detect if theres a composite with render-result node */
2126 static int composite_needs_render(Scene *sce)
2127 {
2128         bNodeTree *ntree= sce->nodetree;
2129         bNode *node;
2130         
2131         if(ntree==NULL) return 1;
2132         if(sce->use_nodes==0) return 1;
2133         if((sce->r.scemode & R_DOCOMP)==0) return 1;
2134                 
2135         for(node= ntree->nodes.first; node; node= node->next) {
2136                 if(node->type==CMP_NODE_R_LAYERS)
2137                         if(node->id==NULL || node->id==&sce->id)
2138                                 return 1;
2139         }
2140         return 0;
2141 }
2142
2143 /* bad call... need to think over proper method still */
2144 static void render_composit_stats(void *unused, char *str)
2145 {
2146         R.i.infostr= str;
2147         R.stats_draw(R.sdh, &R.i);
2148         R.i.infostr= NULL;
2149 }
2150
2151
2152 /* reads all buffers, calls optional composite, merges in first result->rectf */
2153 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
2154 {
2155         float *rectf, filt[3][3];
2156         int sample;
2157         
2158         /* filtmask needs it */
2159         R= *re;
2160         
2161         /* we accumulate in here */
2162         rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
2163         
2164         for(sample=0; sample<re->r.osa; sample++) {
2165                 RenderResult rres;
2166                 int x, y, mask;
2167                 
2168                 /* set all involved renders on the samplebuffers (first was done by render itself) */
2169                 /* also function below assumes this */
2170                 if(sample) {
2171                         Render *re1;
2172                         
2173                         tag_scenes_for_render(re);
2174                         for(re1= RenderList.first; re1; re1= re1->next) {
2175                                 if(re1->scene->id.flag & LIB_DOIT)
2176                                         if(re1->r.scemode & R_FULL_SAMPLE)
2177                                                 read_render_result(re1, sample);
2178                         }
2179                 }
2180
2181                 /* composite */
2182                 if(ntree) {
2183                         ntreeCompositTagRender(re->scene);
2184                         ntreeCompositTagAnimated(ntree);
2185                         
2186                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2187                 }
2188                 
2189                 /* ensure we get either composited result or the active layer */
2190                 RE_GetResultImage(re, &rres);
2191                 
2192                 /* accumulate with filter, and clip */
2193                 mask= (1<<sample);
2194                 mask_array(mask, filt);
2195
2196                 for(y=0; y<re->recty; y++) {
2197                         float *rf= rectf + 4*y*re->rectx;
2198                         float *col= rres.rectf + 4*y*re->rectx;
2199                                 
2200                         for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
2201                                 if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
2202                                 if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
2203                                 if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
2204                                 
2205                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
2206                         }
2207                 }
2208                 
2209                 /* show stuff */
2210                 if(sample!=re->osa-1) {
2211                         /* weak... the display callback wants an active renderlayer pointer... */
2212                         re->result->renlay= render_get_active_layer(re, re->result);
2213                         re->display_draw(re->ddh, re->result, NULL);
2214                 }
2215                 
2216                 if(re->test_break(re->tbh))
2217                         break;
2218         }
2219         
2220         if(re->result->rectf) 
2221                 MEM_freeN(re->result->rectf);
2222         re->result->rectf= rectf;
2223 }
2224
2225 void RE_MergeFullSample(Render *re, Scene *sce, bNodeTree *ntree)
2226 {
2227         Scene *scene;
2228         bNode *node;
2229         
2230         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
2231         
2232         /* tag scenes unread */
2233         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2234                 scene->id.flag |= LIB_DOIT;
2235         
2236         for(node= ntree->nodes.first; node; node= node->next) {
2237                 if(node->type==CMP_NODE_R_LAYERS) {
2238                         Scene *nodescene= (Scene *)node->id;
2239                         
2240                         if(nodescene==NULL) nodescene= sce;
2241                         if(nodescene->id.flag & LIB_DOIT) {
2242                                 nodescene->r.mode |= R_OSA;     /* render struct needs tables */
2243                                 RE_ReadRenderResult(sce, nodescene);
2244                                 nodescene->id.flag &= ~LIB_DOIT;
2245                         }
2246                 }
2247         }
2248         
2249         /* own render result should be read/allocated */
2250         if(re->scene->id.flag & LIB_DOIT)
2251                 RE_ReadRenderResult(re->scene, re->scene);
2252         
2253         /* and now we can draw (result is there) */
2254         re->display_init(re->dih, re->result);
2255         re->display_clear(re->dch, re->result);
2256         
2257         do_merge_fullsample(re, ntree);
2258 }
2259
2260 /* returns fully composited render-result on given time step (in RenderData) */
2261 static void do_render_composite_fields_blur_3d(Render *re)
2262 {
2263         bNodeTree *ntree= re->scene->nodetree;
2264         
2265         /* INIT seeding, compositor can use random texture */
2266         BLI_srandom(re->r.cfra);
2267         
2268         if(composite_needs_render(re->scene)) {
2269                 /* save memory... free all cached images */
2270                 ntreeFreeCache(ntree);
2271                 
2272                 do_render_fields_blur_3d(re);
2273         }
2274         
2275         /* swap render result */
2276         if(re->r.scemode & R_SINGLE_LAYER)
2277                 pop_render_result(re);
2278         
2279         if(!re->test_break(re->tbh)) {
2280                 
2281                 if(ntree) {
2282                         ntreeCompositTagRender(re->scene);
2283                         ntreeCompositTagAnimated(ntree);
2284                 }
2285                 
2286                 if(1 || !(re->r.scemode & R_COMP_RERENDER)) {
2287                         if(ntree && re->r.scemode & R_DOCOMP) {
2288                                 /* checks if there are render-result nodes that need scene */
2289                                 if((re->r.scemode & R_SINGLE_LAYER)==0)
2290                                         ntree_render_scenes(re);
2291                                 
2292                                 if(!re->test_break(re->tbh)) {
2293                                         ntree->stats_draw= render_composit_stats;
2294                                         ntree->test_break= re->test_break;
2295                                         ntree->sdh= re->sdh;
2296                                         ntree->tbh= re->tbh;
2297                                         /* in case it was never initialized */
2298                                         R.stats_draw= re->stats_draw;
2299                                         
2300                                         if(re->r.scemode & R_FULL_SAMPLE) 
2301                                                 do_merge_fullsample(re, ntree);
2302                                         else
2303                                                 ntreeCompositExecTree(ntree, &re->r, G.background==0);
2304                                         
2305                                         ntree->stats_draw= NULL;
2306                                         ntree->test_break= NULL;
2307                                         ntree->tbh= ntree->sdh= NULL;
2308                                 }
2309                         }
2310                         else if(re->r.scemode & R_FULL_SAMPLE)
2311                                 do_merge_fullsample(re, NULL);
2312                 }
2313         }
2314
2315         /* weak... the display callback wants an active renderlayer pointer... */
2316         re->result->renlay= render_get_active_layer(re, re->result);
2317         re->display_draw(re->ddh, re->result, NULL);
2318 }
2319
2320 static void renderresult_stampinfo(Scene *scene)
2321 {
2322         RenderResult rres;
2323         /* this is the basic trick to get the displayed float or char rect from render result */
2324         RE_GetResultImage(RE_GetRender(scene->id.name), &rres);
2325         BKE_stamp_buf(scene, (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
2326 }
2327
2328 static void do_render_seq(Render * re)
2329 {
2330         static int recurs_depth = 0;
2331         struct ImBuf *ibuf;
2332         RenderResult *rr = re->result;
2333         int cfra = re->r.cfra;
2334
2335         recurs_depth++;
2336
2337         ibuf= give_ibuf_seq(re->scene, rr->rectx, rr->recty, cfra, 0, 100.0);
2338
2339         recurs_depth--;
2340         
2341         if(ibuf) {
2342                 if(ibuf->rect_float) {
2343                         if (!rr->rectf)
2344                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
2345                         
2346                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2347                         
2348                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
2349                            can hang around when sequence render has rendered a 32 bits one before */
2350                         if(rr->rect32) {
2351                                 MEM_freeN(rr->rect32);
2352                                 rr->rect32= NULL;
2353                         }
2354                 }
2355                 else if(ibuf->rect) {
2356                         if (!rr->rect32)
2357                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2358
2359                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
2360
2361                         /* if (ibuf->zbuf) { */
2362                         /*      if (R.rectz) freeN(R.rectz); */
2363                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
2364                         /* } */
2365                 }
2366                 
2367                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
2368                         Editing * ed = re->scene->ed;
2369                         if (ed) {
2370                                 free_imbuf_seq(&ed->seqbase, TRUE);
2371                         }
2372                 }
2373         }
2374         else {
2375                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
2376                 if (rr->rectf)
2377                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
2378                 else if (rr->rect32)
2379                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
2380                 else
2381                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2382         }
2383 }
2384
2385 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2386
2387 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2388 static void do_render_all_options(Render *re)
2389 {
2390         re->i.starttime= PIL_check_seconds_timer();
2391
2392         /* ensure no images are in memory from previous animated sequences */
2393         BKE_image_all_free_anim_ibufs(re->r.cfra);
2394         
2395         if((re->r.scemode & R_DOSEQ) && re->scene->ed && re->scene->ed->seqbase.first) {
2396                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2397                 if(!re->test_break(re->tbh)) 
2398                         do_render_seq(re);
2399                 
2400                 re->stats_draw(re->sdh, &re->i);
2401                 re->display_draw(re->ddh, re->result, NULL);
2402                 
2403         }
2404         else {
2405                 do_render_composite_fields_blur_3d(re);
2406         }
2407         
2408         /* for UI only */
2409         renderresult_add_names(re->result);
2410         
2411         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2412         
2413         re->stats_draw(re->sdh, &re->i);
2414         
2415         /* stamp image info here */
2416         if((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
2417                 renderresult_stampinfo(re->scene);
2418                 re->display_draw(re->ddh, re->result, NULL);
2419         }
2420 }
2421
2422 static int is_rendering_allowed(Render *re)
2423 {
2424         SceneRenderLayer *srl;
2425         
2426         /* forbidden combinations */
2427         if(re->r.mode & R_PANORAMA) {
2428                 if(re->r.mode & R_BORDER) {
2429                         re->error(re->erh, "No border supported for Panorama");
2430                         return 0;
2431                 }
2432                 if(re->r.mode & R_ORTHO) {
2433                         re->error(re->erh, "No Ortho render possible for Panorama");
2434                         return 0;
2435                 }
2436         }
2437         
2438         if(re->r.mode & R_BORDER) {
2439                 if(re->r.border.xmax <= re->r.border.xmin || 
2440                    re->r.border.ymax <= re->r.border.ymin) {
2441                         re->error(re->erh, "No border area selected.");
2442                         return 0;
2443                 }
2444                 if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2445                         re->error(re->erh, "Border render and Buffer-save not supported yet");
2446                         return 0;
2447                 }
2448         }
2449         
2450         if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2451                 char str[FILE_MAX];
2452                 
2453                 render_unique_exr_name(re, str, 0);
2454                 
2455                 if (BLI_is_writable(str)==0) {
2456                         re->error(re->erh, "Can not save render buffers, check the temp default path");
2457                         return 0;
2458                 }
2459                 
2460                 /* no osa + fullsample won't work... */
2461                 if(re->osa==0)
2462                         re->r.scemode &= ~R_FULL_SAMPLE;
2463                 
2464                 /* no fullsample and edge */
2465                 if((re->r.scemode & R_FULL_SAMPLE) && (re->r.mode & R_EDGE)) {
2466                         re->error(re->erh, "Full Sample doesn't support Edge Enhance");
2467                         return 0;
2468                 }
2469                 
2470         }
2471         else
2472                 re->r.scemode &= ~R_FULL_SAMPLE;        /* clear to be sure */
2473         
2474         if(re->r.scemode & R_DOCOMP) {
2475                 if(re->scene->use_nodes) {
2476                         bNodeTree *ntree= re->scene->nodetree;
2477                         bNode *node;
2478                 
2479                         if(ntree==NULL) {
2480                                 re->error(re->erh, "No Nodetree in Scene");
2481                                 return 0;
2482                         }
2483                         
2484                         for(node= ntree->nodes.first; node; node= node->next)
2485                                 if(node->type==CMP_NODE_COMPOSITE)
2486                                         break;
2487                         
2488                         
2489                         if(node==NULL) {
2490                                 re->error(re->erh, "No Render Output Node in Scene");
2491                                 return 0;
2492                         }
2493                 }
2494         }
2495         
2496         /* check valid camera, without camera render is OK (compo, seq) */
2497         if(re->scene->camera==NULL)
2498                 re->scene->camera= scene_find_camera(re->scene);
2499         
2500         if(!(re->r.scemode & (R_DOSEQ|R_DOCOMP))) {
2501                 if(re->scene->camera==NULL) {
2502                         re->error(re->erh, "No camera");
2503                         return 0;
2504                 }
2505         }
2506         
2507         /* layer flag tests */
2508         if(re->r.scemode & R_SINGLE_LAYER) {
2509                 srl= BLI_findlink(&re->scene->r.layers, re->r.actlay);
2510                 /* force layer to be enabled */
2511                 srl->layflag &= ~SCE_LAY_DISABLE;
2512         }
2513         
2514         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
2515                 if(!(srl->layflag & SCE_LAY_DISABLE))
2516                         break;
2517         if(srl==NULL) {
2518                 re->error(re->erh, "All RenderLayers are disabled");
2519                 return 0;
2520         }
2521         
2522         /* renderer */
2523         if(!ELEM(re->r.renderer, R_INTERN, R_YAFRAY)) {
2524                 re->error(re->erh, "Unknown render engine set");
2525                 return 0;
2526         }
2527         return 1;
2528 }
2529
2530 static void update_physics_cache(Render *re, Scene *scene, int anim_init)
2531 {
2532         PTCacheBaker baker;
2533
2534         baker.scene = scene;
2535         baker.pid = NULL;
2536         baker.bake = 0;
2537         baker.render = 1;
2538         baker.anim_init = 1;
2539         baker.quick_step = 1;
2540         baker.break_test = re->test_break;
2541         baker.break_data = re->tbh;
2542         baker.progressbar = NULL;
2543
2544         BKE_ptcache_make_cache(&baker);
2545 }
2546 /* evaluating scene options for general Blender render */
2547 static int render_initialize_from_scene(Render *re, Scene *scene, int anim, int anim_init)
2548 {
2549         int winx, winy;
2550         rcti disprect;
2551         
2552         /* r.xsch and r.ysch has the actual view window size
2553                 r.border is the clipping rect */
2554         
2555         /* calculate actual render result and display size */
2556         winx= (scene->r.size*scene->r.xsch)/100;
2557         winy= (scene->r.size*scene->r.ysch)/100;
2558         
2559         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2560         if(scene->r.mode & R_BORDER) {
2561                 disprect.xmin= scene->r.border.xmin*winx;
2562                 disprect.xmax= scene->r.border.xmax*winx;
2563                 
2564                 disprect.ymin= scene->r.border.ymin*winy;
2565                 disprect.ymax= scene->r.border.ymax*winy;
2566         }
2567         else {
2568                 disprect.xmin= disprect.ymin= 0;
2569                 disprect.xmax= winx;
2570                 disprect.ymax= winy;
2571         }
2572         
2573         re->scene= scene;
2574         
2575         /* not too nice, but it survives anim-border render */
2576         if(anim) {
2577                 re->disprect= disprect;
2578                 return 1;
2579         }
2580         
2581         /* check all scenes involved */
2582         tag_scenes_for_render(re);
2583
2584         /*
2585          * Disabled completely for now,
2586          * can be later set as render profile option
2587          * and default for background render.
2588         */
2589         if(0) {
2590                 /* make sure dynamics are up to date */
2591                 update_physics_cache(re, scene, anim_init);
2592         }
2593         
2594         if(scene->r.scemode & R_SINGLE_LAYER)
2595                 push_render_result(re);
2596         
2597         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2598         if(!re->ok)  /* if an error was printed, abort */
2599                 return 0;
2600         
2601         /* initstate makes new result, have to send changed tags around */
2602         ntreeCompositTagRender(re->scene);
2603         
2604         if(!is_rendering_allowed(re))
2605                 return 0;
2606         
2607         re->display_init(re->dih, re->result);
2608         re->display_clear(re->dch, re->result);
2609         
2610         return 1;
2611 }
2612
2613 /* general Blender frame render call */
2614 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
2615 {
2616         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2617         G.rendering= 1;
2618         re->result_ok= 0;
2619         
2620         scene->r.cfra= frame;
2621         
2622         if(render_initialize_from_scene(re, scene, 0, 0)) {
2623                 do_render_all_options(re);
2624         }
2625         
2626         /* UGLY WARNING */
2627         G.rendering= 0;
2628         re->result_ok= 1;
2629 }
2630
2631 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
2632 {
2633         char name[FILE_MAX];
2634         RenderResult rres;
2635         
2636         RE_GetResultImage(re, &rres);
2637
2638         /* write movie or image */
2639         if(BKE_imtype_is_movie(scene->r.imtype)) {
2640                 int dofree = 0;
2641                 /* note; the way it gets 32 bits rects is weak... */
2642                 if(rres.rect32==NULL) {
2643                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2644                         dofree = 1;
2645                 }
2646                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
2647                 mh->append_movie(&re->r, scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
2648                 if(dofree) {
2649                         MEM_freeN(rres.rect32);
2650                 }
2651                 printf("Append frame %d", scene->r.cfra);
2652         } 
2653         else {
2654                 BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2655                 
2656                 if(re->r.imtype==R_MULTILAYER) {
2657                         if(re->result) {
2658                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2659                                 printf("Saved: %s", name);
2660                         }
2661                 }
2662                 else {
2663                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
2664                         int ok;
2665                         
2666                         /* if not exists, BKE_write_ibuf makes one */
2667                         ibuf->rect= (unsigned int *)rres.rect32;    
2668                         ibuf->rect_float= rres.rectf;
2669                         ibuf->zbuf_float= rres.rectz;
2670                         
2671                         /* float factor for random dither, imbuf takes care of it */
2672                         ibuf->dither= scene->r.dither_intensity;
2673                         /* gamma correct to sRGB color space */
2674                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2675                                 ibuf->profile = IB_PROFILE_SRGB;
2676
2677                         ok= BKE_write_ibuf(scene, ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2678                         
2679                         if(ok==0) {
2680                                 printf("Render error: cannot save %s\n", name);
2681                                 G.afbreek=1;
2682                         }
2683                         else printf("Saved: %s", name);
2684                         
2685                         /* optional preview images for exr */
2686                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
2687                                 if(BLI_testextensie(name, ".exr")) 
2688                                         name[strlen(name)-4]= 0;
2689                                 BKE_add_image_extension(scene, name, R_JPEG90);
2690                                 ibuf->depth= 24; 
2691                                 BKE_write_ibuf(scene, ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
2692                                 printf("\nSaved: %s", name);
2693                         }
2694                         
2695                                         /* imbuf knows which rects are not part of ibuf */
2696                         IMB_freeImBuf(ibuf);
2697                 }
2698         }
2699         
2700         BLI_timestr(re->i.lastframetime, name);
2701         printf(" Time: %s\n", name);
2702         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2703 }
2704
2705 /* saves images to disk */
2706 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra, int tfra)
2707 {
2708         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
2709         unsigned int lay;
2710         int cfrao= scene->r.cfra;
2711         int nfra;
2712         
2713         /* do not fully call for each frame, it initializes & pops output window */
2714         if(!render_initialize_from_scene(re, scene, 0, 1))
2715                 return;
2716         
2717         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2718         /* is also set by caller renderwin.c */
2719         G.rendering= 1;
2720         re->result_ok= 0;
2721         
2722         if(BKE_imtype_is_movie(scene->r.imtype))
2723                 mh->start_movie(scene, &re->r, re->rectx, re->recty);
2724         
2725         if (mh->get_next_frame) {
2726                 while (!(G.afbreek == 1)) {
2727                         int nf = mh->get_next_frame(&re->r);
2728                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2729                                 scene->r.cfra = re->r.cfra = nf;
2730                                 
2731                                 do_render_all_options(re);
2732
2733                                 if(re->test_break(re->tbh) == 0) {
2734                                         do_write_image_or_movie(re, scene, mh);
2735                                 }
2736                         } else {
2737                                 re->test_break(re->tbh);
2738                         }
2739                 }
2740         } else {
2741                 for(nfra= sfra, scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
2742                         char name[FILE_MAX];
2743                         
2744                         /* only border now, todo: camera lens. (ton) */
2745                         render_initialize_from_scene(re, scene, 1, 0);
2746
2747                         if(nfra!=scene->r.cfra) {
2748                                 /*
2749                                  * Skip this frame, but update for physics and particles system.
2750                                  * From convertblender.c:
2751                                  * in localview, lamps are using normal layers, objects only local bits.
2752                                  */
2753                                 if(scene->lay & 0xFF000000)
2754                                         lay= scene->lay & 0xFF000000;
2755                                 else
2756                                         lay= scene->lay;
2757
2758                                 scene_update_for_newframe(scene, lay);
2759                                 continue;
2760                         }
2761                         else
2762                                 nfra+= tfra;
2763
2764                         /* Touch/NoOverwrite options are only valid for image's */
2765                         if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2766                                 if(scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2767                                         BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2768
2769                                 if(scene->r.mode & R_NO_OVERWRITE && BLI_exist(name)) {
2770                                         printf("skipping existing frame \"%s\"\n", name);
2771                                         continue;
2772                                 }
2773                                 if(scene->r.mode & R_TOUCH && !BLI_exist(name)) {
2774                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2775                                         BLI_touch(name);
2776                                 }
2777                         }
2778
2779                         re->r.cfra= scene->r.cfra;         /* weak.... */
2780                         
2781                         do_render_all_options(re);
2782                         
2783                         if(re->test_break(re->tbh) == 0) {
2784                                 do_write_image_or_movie(re, scene, mh);
2785                         }
2786                 
2787                         if(G.afbreek==1) {
2788                                 /* remove touched file */
2789                                 if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2790                                         if (scene->r.mode & R_TOUCH && BLI_exist(name) && BLI_filepathsize(name) == 0) {
2791                                                 BLI_delete(name, 0, 0);
2792                                         }
2793                                 }
2794                                 
2795                                 break;
2796                         }
2797                 }
2798         }
2799         
2800         /* end movie */
2801         if(BKE_imtype_is_movie(scene->r.imtype))
2802                 mh->end_movie();
2803
2804         scene->r.cfra= cfrao;
2805         
2806         /* UGLY WARNING */
2807         G.rendering= 0;
2808         re->result_ok= 1;
2809 }
2810
2811 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2812
2813 /* only the temp file! */
2814 void RE_ReadRenderResult(Scene *scene, Scene *scenode)
2815 {
2816         Render *re;
2817         int winx, winy;
2818         rcti disprect;
2819         
2820         /* calculate actual render result and display size */
2821         winx= (scene->r.size*scene->r.xsch)/100;
2822         winy= (scene->r.size*scene->r.ysch)/100;
2823         
2824         /* only in movie case we render smaller part */
2825         if(scene->r.mode & R_BORDER) {
2826                 disprect.xmin= scene->r.border.xmin*winx;
2827                 disprect.xmax= scene->r.border.xmax*winx;
2828                 
2829                 disprect.ymin= scene->r.border.ymin*winy;
2830                 disprect.ymax= scene->r.border.ymax*winy;
2831         }
2832         else {
2833                 disprect.xmin= disprect.ymin= 0;
2834                 disprect.xmax= winx;
2835                 disprect.ymax= winy;
2836         }
2837         
2838         if(scenode)
2839                 scene= scenode;
2840         
2841         /* get render: it can be called from UI with draw callbacks */
2842         re= RE_GetRender(scene->id.name);
2843         if(re==NULL)
2844                 re= RE_NewRender(scene->id.name);
2845         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2846         re->scene= scene;
2847         
2848         read_render_result(re, 0);
2849 }
2850
2851 void RE_set_max_threads(int threads)
2852 {
2853         if (threads==0) {
2854                 commandline_threads = BLI_system_thread_count();
2855         } else if(threads>=1 && threads<=BLENDER_MAX_THREADS) {
2856                 commandline_threads= threads;
2857         } else {
2858                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2859         }
2860 }
2861
2862 void RE_init_threadcount(Render *re) 
2863 {
2864         if(commandline_threads >= 1) { /* only set as an arg in background mode */
2865                 re->r.threads= MIN2(commandline_threads, BLENDER_MAX_THREADS);
2866         } else if ((re->r.mode & R_FIXED_THREADS)==0 || commandline_threads == 0) { /* Automatic threads */
2867                 re->r.threads = BLI_system_thread_count();
2868         }
2869 }
2870
2871 /************************** External Engines ***************************/
2872
2873 RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w, int h)
2874 {
2875         Render *re= engine->re;
2876         RenderResult *result;
2877         rcti disprect;
2878
2879         /* ensure the coordinates are within the right limits */
2880         CLAMP(x, 0, re->result->rectx);
2881         CLAMP(y, 0, re->result->recty);
2882         CLAMP(w, 0, re->result->rectx);
2883         CLAMP(h, 0, re->result->recty);
2884
2885         if(x + w > re->result->rectx)
2886                 w= re->result->rectx - x;
2887         if(y + h > re->result->recty)
2888                 h= re->result->recty - y;
2889
2890         /* allocate a render result */
2891         disprect.xmin= x;
2892         disprect.xmax= x+w;
2893         disprect.ymin= y;
2894         disprect.ymax= y+h;
2895
2896         if(0) { // XXX (re->r.scemode & R_FULL_SAMPLE)) {
2897                 result= new_full_sample_buffers(re, &engine->fullresult, &disprect, 0);
2898         }
2899         else {
2900                 result= new_render_result(re, &disprect, 0, RR_USEMEM);
2901                 BLI_addtail(&engine->fullresult, result);
2902         }
2903
2904         return result;
2905 }
2906
2907 void RE_engine_update_result(RenderEngine *engine, RenderResult *result)
2908 {
2909         Render *re= engine->re;
2910
2911         if(result && render_display_draw_enabled(re)) {
2912                 result->renlay= result->layers.first; // weak
2913                 re->display_draw(re->ddh, result, NULL);
2914         }
2915 }
2916
2917 void RE_engine_end_result(RenderEngine *engine, RenderResult *result)
2918 {
2919         Render *re= engine->re;
2920
2921         if(!result)
2922                 return;
2923
2924         /* merge */
2925         if(re->result->exrhandle) {
2926                 RenderResult *rr, *rrpart;
2927                 
2928                 // XXX crashes, exr expects very particular part sizes
2929                 for(rr= re->result, rrpart= result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
2930                         save_render_result_tile(rr, rrpart);
2931         }
2932         else if(render_display_draw_enabled(re)) {
2933                 /* on break, don't merge in result for preview renders, looks nicer */
2934                 if(re->test_break(re->tbh) && (re->r.scemode & R_PREVIEWBUTS));
2935                 else merge_render_result(re->result, result);
2936         }
2937
2938         /* draw */
2939         if(!re->test_break(re->tbh) && render_display_draw_enabled(re)) {
2940                 result->renlay= result->layers.first; // weak
2941                 re->display_draw(re->ddh, result, NULL);
2942         }
2943
2944         /* free */
2945         free_render_result(&engine->fullresult, result);
2946 }
2947
2948 int RE_engine_test_break(RenderEngine *engine)
2949 {
2950         Render *re= engine->re;
2951
2952         return re->test_break(re->tbh);
2953 }
2954
2955 void RE_engine_update_stats(RenderEngine *engine, char *stats, char *info)
2956 {
2957         Render *re= engine->re;
2958
2959         re->i.statstr= stats;
2960         re->i.infostr= info;
2961         re->stats_draw(re->sdh, &re->i);
2962         re->i.infostr= NULL;
2963         re->i.statstr= NULL;
2964 }
2965
2966 /* loads in image into a result, size must match
2967  * x/y offsets are only used on a partial copy when dimensions dont match */
2968 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, char *filename)
2969 {
2970         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect);
2971
2972         if(ibuf  && (ibuf->rect || ibuf->rect_float)) {
2973                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
2974                         if(ibuf->rect_float==NULL)
2975                                 IMB_float_from_rect(ibuf);
2976
2977                         memcpy(layer->rectf, ibuf->rect_float, sizeof(float)*4*layer->rectx*layer->recty);
2978                 } else {
2979                         if ((ibuf->x >= layer->rectx) && (ibuf->y >= layer->recty)) {
2980                                 ImBuf *ibuf_clip;
2981
2982                                 if(ibuf->rect_float==NULL)
2983                                         IMB_float_from_rect(ibuf);
2984
2985                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat, 0);
2986                                 if(ibuf_clip) {
2987                                         IMB_rectcpy(ibuf_clip, ibuf, 0,0, 0,0, layer->rectx, layer->recty);
2988
2989                                         memcpy(layer->rectf, ibuf_clip->rect_float, sizeof(float)*4*layer->rectx*layer->recty);
2990                                         IMB_freeImBuf(ibuf_clip);
2991                                 }
2992                                 else {
2993                                         BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'\n", filename);
2994                                 }
2995                         }
2996                         else {
2997                                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'\n", filename);
2998                         }
2999                 }
3000
3001                 IMB_freeImBuf(ibuf);
3002         }
3003         else {
3004                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
3005         }
3006 }
3007
3008 void RE_result_load_from_file(RenderResult *result, ReportList *reports, char *filename)
3009 {
3010         if(!read_render_result_from_file(filename, result)) {
3011                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
3012                 return;
3013         }
3014 }
3015
3016 static void external_render_3d(Render *re, RenderEngineType *type)
3017 {
3018         RenderEngine engine;
3019
3020         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
3021                 RE_FreeRenderResult(re->result);
3022         
3023                 if(0) // XXX re->r.scemode & R_FULL_SAMPLE)
3024                         re->result= new_full_sample_buffers_exr(re);
3025                 else
3026                         re->result= new_render_result(re, &re->disprect, 0, 0); // XXX re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
3027         }
3028         
3029         if(re->result==NULL)
3030                 return;
3031
3032         /* external */
3033         memset(&engine, 0, sizeof(engine));
3034         engine.type= type;
3035         engine.re= re;
3036
3037         type->render(&engine, re->scene);
3038
3039         free_render_result(&engine.fullresult, engine.fullresult.first);
3040
3041         if(re->result->exrhandle) {
3042                 RenderResult *rr;
3043
3044                 save_empty_result_tiles(re);
3045                 
3046                 for(rr= re->result; rr; rr= rr->next) {
3047                         IMB_exr_close(rr->exrhandle);
3048                         rr->exrhandle= NULL;
3049                 }
3050                 
3051                 free_render_result(&re->fullresult, re->result);
3052                 re->result= NULL;
3053                 
3054                 read_render_result(re, 0);
3055         }
3056 }
3057