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