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