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