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