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