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