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