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