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