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