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