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