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