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