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