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