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