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