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