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