Merged Soc 2009 - raytrace optimization [0]
[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_arithb.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) Composit 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 | 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                 for(;tot>0; tot--, cp+=4, fp+=4) {
1069                         cp[0] = FTOCHAR(fp[0]);
1070                         cp[1] = FTOCHAR(fp[1]);
1071                         cp[2] = FTOCHAR(fp[2]);
1072                         cp[3] = FTOCHAR(fp[3]);
1073                 }
1074         }
1075         else
1076                 /* else fill with black */
1077                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
1078
1079         RE_ReleaseResultImage(re);
1080 }
1081
1082
1083 RenderStats *RE_GetStats(Render *re)
1084 {
1085         return &re->i;
1086 }
1087
1088 Render *RE_NewRender(const char *name)
1089 {
1090         Render *re;
1091         
1092         /* only one render per name exists */
1093         re= RE_GetRender(name);
1094         if(re==NULL) {
1095                 
1096                 /* new render data struct */
1097                 re= MEM_callocN(sizeof(Render), "new render");
1098                 BLI_addtail(&RenderList, re);
1099                 strncpy(re->name, name, RE_MAXNAME);
1100                 BLI_rw_mutex_init(&re->resultmutex);
1101         }
1102         
1103         /* prevent UI to draw old results */
1104         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1105         RE_FreeRenderResult(re->result);
1106         re->result= NULL;
1107         re->result_ok= 0;
1108         BLI_rw_mutex_unlock(&re->resultmutex);
1109         
1110         /* set default empty callbacks */
1111         re->display_init= result_nothing;
1112         re->display_clear= result_nothing;
1113         re->display_draw= result_rcti_nothing;
1114         re->timecursor= int_nothing;
1115         re->test_break= void_nothing;
1116         re->error= print_error;
1117         if(G.background)
1118                 re->stats_draw= stats_background;
1119         else
1120                 re->stats_draw= stats_nothing;
1121         /* clear callback handles */
1122         re->dih= re->dch= re->ddh= re->sdh= re->tch= re->tbh= re->erh= NULL;
1123         
1124         /* init some variables */
1125         re->ycor= 1.0f;
1126         
1127         return re;
1128 }
1129
1130 /* only call this while you know it will remove the link too */
1131 void RE_FreeRender(Render *re)
1132 {
1133         BLI_rw_mutex_end(&re->resultmutex);
1134         
1135         free_renderdata_tables(re);
1136         free_sample_tables(re);
1137         
1138         RE_FreeRenderResult(re->result);
1139         RE_FreeRenderResult(re->pushedresult);
1140         
1141         BLI_remlink(&RenderList, re);
1142         MEM_freeN(re);
1143 }
1144
1145 /* exit blender */
1146 void RE_FreeAllRender(void)
1147 {
1148         while(RenderList.first) {
1149                 RE_FreeRender(RenderList.first);
1150         }
1151 }
1152
1153 /* ********* initialize state ******** */
1154
1155
1156 /* what doesn't change during entire render sequence */
1157 /* disprect is optional, if NULL it assumes full window render */
1158 void RE_InitState(Render *re, Render *source, RenderData *rd, int winx, int winy, rcti *disprect)
1159 {
1160         re->ok= TRUE;   /* maybe flag */
1161         
1162         re->i.starttime= PIL_check_seconds_timer();
1163         re->r= *rd;             /* hardcopy */
1164         
1165         re->winx= winx;
1166         re->winy= winy;
1167         if(disprect) {
1168                 re->disprect= *disprect;
1169                 re->rectx= disprect->xmax-disprect->xmin;
1170                 re->recty= disprect->ymax-disprect->ymin;
1171         }
1172         else {
1173                 re->disprect.xmin= re->disprect.ymin= 0;
1174                 re->disprect.xmax= winx;
1175                 re->disprect.ymax= winy;
1176                 re->rectx= winx;
1177                 re->recty= winy;
1178         }
1179         
1180         if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
1181                                                                                   (re->rectx < 16 || re->recty < 16) )) {
1182                 re->error(re->erh, "Image too small");
1183                 re->ok= 0;
1184         }
1185         else {
1186 #ifdef WITH_OPENEXR
1187                 if(re->r.scemode & R_FULL_SAMPLE)
1188                         re->r.scemode |= R_EXR_TILE_FILE;       /* enable automatic */
1189 #else
1190                 /* can't do this without openexr support */
1191                 re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1192 #endif
1193                 
1194                 /* fullsample wants uniform osa levels */
1195                 if(source && (re->r.scemode & R_FULL_SAMPLE)) {
1196                         /* but, if source has no full sample we disable it */
1197                         if((source->r.scemode & R_FULL_SAMPLE)==0)
1198                                 re->r.scemode &= ~R_FULL_SAMPLE;
1199                         else
1200                                 re->r.osa= re->osa= source->osa;
1201                 }
1202                 else {
1203                         /* check state variables, osa? */
1204                         if(re->r.mode & (R_OSA)) {
1205                                 re->osa= re->r.osa;
1206                                 if(re->osa>16) re->osa= 16;
1207                         }
1208                         else re->osa= 0;
1209                 }
1210
1211                 /* always call, checks for gamma, gamma tables and jitter too */
1212                 make_sample_tables(re); 
1213                 
1214                 /* if preview render, we try to keep old result */
1215                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1216
1217                 if(re->r.scemode & R_PREVIEWBUTS) {
1218                         if(re->result && re->result->rectx==re->rectx && re->result->recty==re->recty);
1219                         else {
1220                                 RE_FreeRenderResult(re->result);
1221                                 re->result= NULL;
1222                         }
1223                 }
1224                 else {
1225                         
1226                         /* make empty render result, so display callbacks can initialize */
1227                         RE_FreeRenderResult(re->result);
1228                         re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1229                         re->result->rectx= re->rectx;
1230                         re->result->recty= re->recty;
1231                 }
1232
1233                 BLI_rw_mutex_unlock(&re->resultmutex);
1234                 
1235                 /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1236                 re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1237                 
1238                 RE_init_threadcount(re);
1239         }
1240 }
1241
1242 /* part of external api, not called for regular render pipeline */
1243 void RE_SetDispRect (struct Render *re, rcti *disprect)
1244 {
1245         re->disprect= *disprect;
1246         re->rectx= disprect->xmax-disprect->xmin;
1247         re->recty= disprect->ymax-disprect->ymin;
1248         
1249         /* initialize render result */
1250         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1251
1252         RE_FreeRenderResult(re->result);
1253         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1254
1255         BLI_rw_mutex_unlock(&re->resultmutex);
1256 }
1257
1258 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1259 {
1260         /* re->ok flag? */
1261         
1262         re->viewplane= *viewplane;
1263         re->clipsta= clipsta;
1264         re->clipend= clipend;
1265         re->r.mode &= ~R_ORTHO;
1266
1267         i_window(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1268         
1269 }
1270
1271 void RE_SetOrtho(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         i_ortho(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1281 }
1282
1283 void RE_SetView(Render *re, float mat[][4])
1284 {
1285         /* re->ok flag? */
1286         Mat4CpyMat4(re->viewmat, mat);
1287         Mat4Invert(re->viewinv, re->viewmat);
1288 }
1289
1290 /* image and movie output has to move to either imbuf or kernel */
1291 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1292 {
1293         re->display_init= f;
1294         re->dih= handle;
1295 }
1296 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1297 {
1298         re->display_clear= f;
1299         re->dch= handle;
1300 }
1301 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
1302 {
1303         re->display_draw= f;
1304         re->ddh= handle;
1305 }
1306 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
1307 {
1308         re->stats_draw= f;
1309         re->sdh= handle;
1310 }
1311 void RE_timecursor_cb(Render *re, void *handle, void (*f)(void *handle, int))
1312 {
1313         re->timecursor= f;
1314         re->tch= handle;
1315 }
1316
1317 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
1318 {
1319         re->test_break= f;
1320         re->tbh= handle;
1321 }
1322 void RE_error_cb(Render *re, void *handle, void (*f)(void *handle, char *str))
1323 {
1324         re->error= f;
1325         re->erh= handle;
1326 }
1327
1328
1329 /* ********* add object data (later) ******** */
1330
1331 /* object is considered fully prepared on correct time etc */
1332 /* includes lights */
1333 void RE_AddObject(Render *re, Object *ob)
1334 {
1335         
1336 }
1337
1338 /* *************************************** */
1339
1340 static int render_display_draw_enabled(Render *re)
1341 {
1342         /* don't show preprocess for previewrender sss */
1343         if(re->sss_points)
1344                 return !(re->r.scemode & R_PREVIEWBUTS);
1345         else
1346                 return 1;
1347 }
1348
1349 /* allocate osa new results for samples */
1350 static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
1351 {
1352         int a;
1353         
1354         if(re->osa==0)
1355                 return new_render_result(re, partrct, crop, RR_USEMEM);
1356         
1357         for(a=0; a<re->osa; a++) {
1358                 RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
1359                 BLI_addtail(lb, rr);
1360                 rr->sample_nr= a;
1361         }
1362         
1363         return lb->first;
1364 }
1365
1366
1367 /* the main thread call, renders an entire part */
1368 static void *do_part_thread(void *pa_v)
1369 {
1370         RenderPart *pa= pa_v;
1371         
1372         /* need to return nicely all parts on esc */
1373         if(R.test_break(R.tbh)==0) {
1374                 
1375                 if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
1376                         pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
1377                 else
1378                         pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1379
1380                 if(R.sss_points)
1381                         zbufshade_sss_tile(pa);
1382                 else if(R.osa)
1383                         zbufshadeDA_tile(pa);
1384                 else
1385                         zbufshade_tile(pa);
1386                 
1387                 /* merge too on break! */
1388                 if(R.result->exrhandle) {
1389                         RenderResult *rr, *rrpart;
1390                         
1391                         for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
1392                                 save_render_result_tile(rr, rrpart);
1393                         
1394                 }
1395                 else if(render_display_draw_enabled(&R)) {
1396                         /* on break, don't merge in result for preview renders, looks nicer */
1397                         if(R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS));
1398                         else merge_render_result(R.result, pa->result);
1399                 }
1400         }
1401         
1402         pa->ready= 1;
1403         
1404         return NULL;
1405 }
1406
1407 /* returns with render result filled, not threaded, used for preview now only */
1408 static void render_tile_processor(Render *re, int firsttile)
1409 {
1410         RenderPart *pa;
1411         
1412         if(re->test_break(re->tbh))
1413                 return;
1414
1415         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1416
1417         /* hrmf... exception, this is used for preview render, re-entrant, so render result has to be re-used */
1418         if(re->result==NULL || re->result->layers.first==NULL) {
1419                 if(re->result) RE_FreeRenderResult(re->result);
1420                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1421         }
1422
1423         BLI_rw_mutex_unlock(&re->resultmutex);
1424         
1425         re->stats_draw(re->sdh, &re->i);
1426  
1427         if(re->result==NULL)
1428                 return;
1429         
1430         initparts(re);
1431
1432         /* assuming no new data gets added to dbase... */
1433         R= *re;
1434         
1435         for(pa= re->parts.first; pa; pa= pa->next) {
1436                 if(firsttile) {
1437                         re->i.partsdone++;      /* was reset in initparts */
1438                         firsttile--;
1439                 }
1440                 else {
1441                         do_part_thread(pa);
1442                         
1443                         if(pa->result) {
1444                                 if(!re->test_break(re->tbh)) {
1445                                         if(render_display_draw_enabled(re))
1446                                                 re->display_draw(re->ddh, pa->result, NULL);
1447                                         
1448                                         re->i.partsdone++;
1449                                         re->stats_draw(re->sdh, &re->i);
1450                                 }
1451                                 RE_FreeRenderResult(pa->result);
1452                                 pa->result= NULL;
1453                         }               
1454                         if(re->test_break(re->tbh))
1455                                 break;
1456                 }
1457         }
1458
1459         freeparts(re);
1460 }
1461
1462 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1463 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1464 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1465 float panorama_pixel_rot(Render *re)
1466 {
1467         float psize, phi, xfac;
1468         
1469         /* size of 1 pixel mapped to viewplane coords */
1470         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
1471         /* angle of a pixel */
1472         phi= atan(psize/re->clipsta);
1473         
1474         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1475         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1476         xfac= atan(0.5f*xfac/re->clipsta); 
1477         /* and how much the same viewplane angle is wrapped */
1478         psize= 0.5f*phi*((float)re->partx);
1479         
1480         /* the ratio applied to final per-pixel angle */
1481         phi*= xfac/psize;
1482         
1483         return phi;
1484 }
1485
1486 /* call when all parts stopped rendering, to find the next Y slice */
1487 /* if slice found, it rotates the dbase */
1488 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1489 {
1490         RenderPart *pa, *best= NULL;
1491         
1492         *minx= re->winx;
1493         
1494         /* most left part of the non-rendering parts */
1495         for(pa= re->parts.first; pa; pa= pa->next) {
1496                 if(pa->ready==0 && pa->nr==0) {
1497                         if(pa->disprect.xmin < *minx) {
1498                                 best= pa;
1499                                 *minx= pa->disprect.xmin;
1500                         }
1501                 }
1502         }
1503                         
1504         if(best) {
1505                 float phi= panorama_pixel_rot(re);
1506
1507                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1508                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
1509                 
1510                 /* shift viewplane */
1511                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1512                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1513                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1514                 Mat4CpyMat4(R.winmat, re->winmat);
1515                 
1516                 /* rotate database according to part coordinates */
1517                 project_renderdata(re, projectverto, 1, -R.panodxp*phi, 1);
1518                 R.panosi= sin(R.panodxp*phi);
1519                 R.panoco= cos(R.panodxp*phi);
1520         }
1521         return best;
1522 }
1523
1524 static RenderPart *find_next_part(Render *re, int minx)
1525 {
1526         RenderPart *pa, *best= NULL;
1527         int centx=re->winx/2, centy=re->winy/2, tot=1;
1528         int mindist, distx, disty;
1529         
1530         /* find center of rendered parts, image center counts for 1 too */
1531         for(pa= re->parts.first; pa; pa= pa->next) {
1532                 if(pa->ready) {
1533                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1534                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1535                         tot++;
1536                 }
1537         }
1538         centx/=tot;
1539         centy/=tot;
1540         
1541         /* closest of the non-rendering parts */
1542         mindist= re->winx*re->winy;
1543         for(pa= re->parts.first; pa; pa= pa->next) {
1544                 if(pa->ready==0 && pa->nr==0) {
1545                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1546                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1547                         distx= (int)sqrt(distx*distx + disty*disty);
1548                         if(distx<mindist) {
1549                                 if(re->r.mode & R_PANORAMA) {
1550                                         if(pa->disprect.xmin==minx) {
1551                                                 best= pa;
1552                                                 mindist= distx;
1553                                         }
1554                                 }
1555                                 else {
1556                                         best= pa;
1557                                         mindist= distx;
1558                                 }
1559                         }
1560                 }
1561         }
1562         return best;
1563 }
1564
1565 static void print_part_stats(Render *re, RenderPart *pa)
1566 {
1567         char str[64];
1568         
1569         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1570         re->i.infostr= str;
1571         re->stats_draw(re->sdh, &re->i);
1572         re->i.infostr= NULL;
1573 }
1574
1575 /* make osa new results for samples */
1576 static RenderResult *new_full_sample_buffers_exr(Render *re)
1577 {
1578         int a;
1579         
1580         for(a=0; a<re->osa; a++) {
1581                 RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
1582                 BLI_addtail(&re->fullresult, rr);
1583                 rr->sample_nr= a;
1584         }
1585         
1586         return re->fullresult.first;
1587 }
1588
1589 static void threaded_tile_processor(Render *re)
1590 {
1591         ListBase threads;
1592         RenderPart *pa, *nextpa;
1593         rctf viewplane= re->viewplane;
1594         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1595         
1596         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1597
1598         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
1599         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
1600                 RE_FreeRenderResult(re->result);
1601         
1602                 if(re->sss_points && render_display_draw_enabled(re))
1603                         re->result= new_render_result(re, &re->disprect, 0, 0);
1604                 else if(re->r.scemode & R_FULL_SAMPLE)
1605                         re->result= new_full_sample_buffers_exr(re);
1606                 else
1607                         re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
1608         }
1609
1610         BLI_rw_mutex_unlock(&re->resultmutex);
1611         
1612         if(re->result==NULL)
1613                 return;
1614         
1615         /* warning; no return here without closing exr file */
1616         
1617         initparts(re);
1618
1619         if(re->result->exrhandle) {
1620                 RenderResult *rr;
1621                 char str[FILE_MAX];
1622                 
1623                 for(rr= re->result; rr; rr= rr->next) {
1624                         render_unique_exr_name(re, str, rr->sample_nr);
1625                 
1626                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1627                         IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1628                 }
1629         }
1630         
1631         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1632         
1633         /* assuming no new data gets added to dbase... */
1634         R= *re;
1635         
1636         /* set threadsafe break */
1637         R.test_break= thread_break;
1638         
1639         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1640         if(re->r.mode & R_PANORAMA)
1641                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1642         else
1643                 nextpa= find_next_part(re, 0);
1644         
1645         while(rendering) {
1646                 
1647                 if(re->test_break(re->tbh))
1648                         PIL_sleep_ms(50);
1649                 else if(nextpa && BLI_available_threads(&threads)) {
1650                         drawtimer= 0;
1651                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1652                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1653                         BLI_insert_thread(&threads, nextpa);
1654
1655                         nextpa= find_next_part(re, minx);
1656                 }
1657                 else if(re->r.mode & R_PANORAMA) {
1658                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1659                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1660                         else {
1661                                 PIL_sleep_ms(50);
1662                                 drawtimer++;
1663                         }
1664                 }
1665                 else {
1666                         PIL_sleep_ms(50);
1667                         drawtimer++;
1668                 }
1669                 
1670                 /* check for ready ones to display, and if we need to continue */
1671                 rendering= 0;
1672                 hasdrawn= 0;
1673                 for(pa= re->parts.first; pa; pa= pa->next) {
1674                         if(pa->ready) {
1675                                 
1676                                 BLI_remove_thread(&threads, pa);
1677                                 
1678                                 if(pa->result) {
1679                                         if(render_display_draw_enabled(re))
1680                                                 re->display_draw(re->ddh, pa->result, NULL);
1681                                         print_part_stats(re, pa);
1682                                         
1683                                         free_render_result(&pa->fullresult, pa->result);
1684                                         pa->result= NULL;
1685                                         re->i.partsdone++;
1686                                         hasdrawn= 1;
1687                                 }
1688                         }
1689                         else {
1690                                 rendering= 1;
1691                                 if(pa->nr && pa->result && drawtimer>20) {
1692                                         if(render_display_draw_enabled(re))
1693                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
1694                                         hasdrawn= 1;
1695                                 }
1696                         }
1697                 }
1698                 if(hasdrawn)
1699                         drawtimer= 0;
1700
1701                 /* on break, wait for all slots to get freed */
1702                 if( (g_break=re->test_break(re->tbh)) && BLI_available_threads(&threads)==re->r.threads)
1703                         rendering= 0;
1704                 
1705         }
1706         
1707         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1708
1709         if(re->result->exrhandle) {
1710                 RenderResult *rr;
1711
1712                 save_empty_result_tiles(re);
1713                 
1714                 for(rr= re->result; rr; rr= rr->next) {
1715                         IMB_exr_close(rr->exrhandle);
1716                         rr->exrhandle= NULL;
1717                 }
1718                 
1719                 free_render_result(&re->fullresult, re->result);
1720                 re->result= NULL;
1721                 
1722                 read_render_result(re, 0);
1723         }
1724
1725         BLI_rw_mutex_unlock(&re->resultmutex);
1726         
1727         /* unset threadsafety */
1728         g_break= 0;
1729         
1730         BLI_end_threads(&threads);
1731         freeparts(re);
1732         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1733 }
1734
1735 /* currently only called by preview renders and envmap */
1736 void RE_TileProcessor(Render *re, int firsttile, int threaded)
1737 {
1738         /* the partsdone variable has to be reset to firsttile, to survive esc before it was set to zero */
1739         
1740         re->i.partsdone= firsttile;
1741
1742         if(!re->sss_points)
1743                 re->i.starttime= PIL_check_seconds_timer();
1744
1745         if(threaded)
1746                 threaded_tile_processor(re);
1747         else
1748                 render_tile_processor(re, firsttile);
1749                 
1750         if(!re->sss_points)
1751                 re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1752         re->stats_draw(re->sdh, &re->i);
1753 }
1754
1755
1756 /* ************  This part uses API, for rendering Blender scenes ********** */
1757
1758 static void external_render_3d(Render *re, RenderEngineType *type);
1759
1760 static void do_render_3d(Render *re)
1761 {
1762         RenderEngineType *type;
1763
1764         /* try external */
1765         for(type=R_engines.first; type; type=type->next)
1766                 if(strcmp(type->idname, re->r.engine) == 0)
1767                         break;
1768
1769         if(type && type->render) {
1770                 external_render_3d(re, type);
1771                 return;
1772         }
1773
1774         /* internal */
1775         
1776 //      re->cfra= cfra; /* <- unused! */
1777         
1778         /* make render verts/faces/halos/lamps */
1779         if(render_scene_needs_vector(re))
1780                 RE_Database_FromScene_Vectors(re, re->scene);
1781         else
1782            RE_Database_FromScene(re, re->scene, 1);
1783         
1784         threaded_tile_processor(re);
1785         
1786         /* do left-over 3d post effects (flares) */
1787         if(re->flag & R_HALO)
1788                 if(!re->test_break(re->tbh))
1789                         add_halo_flare(re);
1790         
1791         /* free all render verts etc */
1792         RE_Database_Free(re);
1793 }
1794
1795 /* called by blur loop, accumulate RGBA key alpha */
1796 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
1797 {
1798         float mfac= 1.0f - blurfac;
1799         int a, b, stride= 4*rr->rectx;
1800         int len= stride*sizeof(float);
1801         
1802         for(a=0; a<rr->recty; a++) {
1803                 if(blurfac==1.0f) {
1804                         memcpy(rectf, rectf1, len);
1805                 }
1806                 else {
1807                         float *rf= rectf, *rf1= rectf1;
1808                         
1809                         for( b= rr->rectx; b>0; b--, rf+=4, rf1+=4) {
1810                                 if(rf1[3]<0.01f)
1811                                         rf[3]= mfac*rf[3];
1812                                 else if(rf[3]<0.01f) {
1813                                         rf[0]= rf1[0];
1814                                         rf[1]= rf1[1];
1815                                         rf[2]= rf1[2];
1816                                         rf[3]= blurfac*rf1[3];
1817                                 }
1818                                 else {
1819                                         rf[0]= mfac*rf[0] + blurfac*rf1[0];
1820                                         rf[1]= mfac*rf[1] + blurfac*rf1[1];
1821                                         rf[2]= mfac*rf[2] + blurfac*rf1[2];
1822                                         rf[3]= mfac*rf[3] + blurfac*rf1[3];
1823                                 }                               
1824                         }
1825                 }
1826                 rectf+= stride;
1827                 rectf1+= stride;
1828         }
1829 }
1830
1831 /* called by blur loop, accumulate renderlayers */
1832 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1833 {
1834         float mfac= 1.0f - blurfac;
1835         int a, b, stride= channels*rr->rectx;
1836         int len= stride*sizeof(float);
1837         
1838         for(a=0; a<rr->recty; a++) {
1839                 if(blurfac==1.0f) {
1840                         memcpy(rectf, rectf1, len);
1841                 }
1842                 else {
1843                         float *rf= rectf, *rf1= rectf1;
1844                         
1845                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1846                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1847                         }
1848                 }
1849                 rectf+= stride;
1850                 rectf1+= stride;
1851         }
1852 }
1853
1854
1855 /* called by blur loop, accumulate renderlayers */
1856 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1857 {
1858         RenderLayer *rl, *rl1;
1859         RenderPass *rpass, *rpass1;
1860         
1861         rl1= brr->layers.first;
1862         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1863                 
1864                 /* combined */
1865                 if(rl->rectf && rl1->rectf) {
1866                         if(key_alpha)
1867                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1868                         else
1869                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1870                 }
1871                 
1872                 /* passes are allocated in sync */
1873                 rpass1= rl1->passes.first;
1874                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1875                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1876                 }
1877         }
1878 }
1879
1880 /* main blur loop, can be called by fields too */
1881 static void do_render_blur_3d(Render *re)
1882 {
1883         RenderResult *rres;
1884         float blurfac;
1885         int blur= re->r.osa;
1886         
1887         /* create accumulation render result */
1888         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1889         
1890         /* do the blur steps */
1891         while(blur--) {
1892                 set_mblur_offs( re->r.blurfac*((float)(re->r.osa-blur))/(float)re->r.osa );
1893                 
1894                 re->i.curblur= re->r.osa-blur;  /* stats */
1895                 
1896                 do_render_3d(re);
1897                 
1898                 blurfac= 1.0f/(float)(re->r.osa-blur);
1899                 
1900                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1901                 if(re->test_break(re->tbh)) break;
1902         }
1903         
1904         /* swap results */
1905         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1906         RE_FreeRenderResult(re->result);
1907         re->result= rres;
1908         BLI_rw_mutex_unlock(&re->resultmutex);
1909         
1910         set_mblur_offs(0.0f);
1911         re->i.curblur= 0;       /* stats */
1912         
1913         /* weak... the display callback wants an active renderlayer pointer... */
1914         re->result->renlay= render_get_active_layer(re, re->result);
1915         re->display_draw(re->ddh, re->result, NULL);    
1916 }
1917
1918
1919 /* function assumes rectf1 and rectf2 to be half size of rectf */
1920 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1921 {
1922         int a, stride= channels*rr->rectx;
1923         int len= stride*sizeof(float);
1924         
1925         for(a=0; a<rr->recty; a+=2) {
1926                 memcpy(rectf, rectf1, len);
1927                 rectf+= stride;
1928                 rectf1+= stride;
1929                 memcpy(rectf, rectf2, len);
1930                 rectf+= stride;
1931                 rectf2+= stride;
1932         }
1933 }
1934
1935 /* merge render results of 2 fields */
1936 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1937 {
1938         RenderLayer *rl, *rl1, *rl2;
1939         RenderPass *rpass, *rpass1, *rpass2;
1940         
1941         rl1= rr1->layers.first;
1942         rl2= rr2->layers.first;
1943         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1944                 
1945                 /* combined */
1946                 if(rl->rectf && rl1->rectf && rl2->rectf)
1947                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1948                 
1949                 /* passes are allocated in sync */
1950                 rpass1= rl1->passes.first;
1951                 rpass2= rl2->passes.first;
1952                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1953                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1954                 }
1955         }
1956 }
1957
1958
1959 /* interleaves 2 frames */
1960 static void do_render_fields_3d(Render *re)
1961 {
1962         RenderResult *rr1, *rr2= NULL;
1963         
1964         /* no render result was created, we can safely halve render y */
1965         re->winy /= 2;
1966         re->recty /= 2;
1967         re->disprect.ymin /= 2;
1968         re->disprect.ymax /= 2;
1969         
1970         re->i.curfield= 1;      /* stats */
1971         
1972         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1973         RE_SetCamera(re, re->scene->camera);
1974         if(re->r.mode & R_MBLUR)
1975                 do_render_blur_3d(re);
1976         else
1977                 do_render_3d(re);
1978
1979         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1980         rr1= re->result;
1981         re->result= NULL;
1982         BLI_rw_mutex_unlock(&re->resultmutex);
1983         
1984         /* second field */
1985         if(!re->test_break(re->tbh)) {
1986                 
1987                 re->i.curfield= 2;      /* stats */
1988                 
1989                 re->flag |= R_SEC_FIELD;
1990                 if((re->r.mode & R_FIELDSTILL)==0) 
1991                         set_field_offs(0.5f);
1992                 RE_SetCamera(re, re->scene->camera);
1993                 if(re->r.mode & R_MBLUR)
1994                         do_render_blur_3d(re);
1995                 else
1996                         do_render_3d(re);
1997                 re->flag &= ~R_SEC_FIELD;
1998                 set_field_offs(0.0f);
1999                 
2000                 rr2= re->result;
2001         }
2002         
2003         /* allocate original height new buffers */
2004         re->winy *= 2;
2005         re->recty *= 2;
2006         re->disprect.ymin *= 2;
2007         re->disprect.ymax *= 2;
2008
2009         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2010         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2011         RE_FreeRenderResult(rr1);
2012
2013         if(rr2) {
2014                 if(re->r.mode & R_ODDFIELD)
2015                         merge_renderresult_fields(re->result, rr2, rr1);
2016                 else
2017                         merge_renderresult_fields(re->result, rr1, rr2);
2018                 
2019                 RE_FreeRenderResult(rr2);
2020         }
2021         
2022         re->i.curfield= 0;      /* stats */
2023         
2024         /* weak... the display callback wants an active renderlayer pointer... */
2025         re->result->renlay= render_get_active_layer(re, re->result);
2026
2027         BLI_rw_mutex_unlock(&re->resultmutex);
2028
2029         re->display_draw(re->ddh, re->result, NULL);
2030 }
2031
2032 static void load_backbuffer(Render *re)
2033 {
2034         if(re->r.alphamode == R_ADDSKY) {
2035                 ImBuf *ibuf;
2036                 char name[256];
2037                 
2038                 strcpy(name, re->r.backbuf);
2039                 BLI_convertstringcode(name, G.sce);
2040                 BLI_convertstringframe(name, re->r.cfra);
2041                 
2042                 if(re->backbuf) {
2043                         re->backbuf->id.us--;
2044                         if(re->backbuf->id.us<1)
2045                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
2046                 }
2047                 
2048                 re->backbuf= BKE_add_image_file(name, re->r.cfra);
2049                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
2050                 if(ibuf==NULL) {
2051                         // error() doesnt work with render window open
2052                         //error("No backbuf there!");
2053                         printf("Error: No backbuf %s\n", name);
2054                 }
2055                 else {
2056                         if (re->r.mode & R_FIELDS)
2057                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
2058                 }
2059         }
2060 }
2061
2062 /* main render routine, no compositing */
2063 static void do_render_fields_blur_3d(Render *re)
2064 {
2065         /* also check for camera here */
2066         if(re->scene->camera==NULL) {
2067                 printf("ERROR: Cannot render, no camera\n");
2068                 G.afbreek= 1;
2069                 return;
2070         }
2071         
2072         /* backbuffer initialize */
2073         if(re->r.bufflag & 1)
2074                 load_backbuffer(re);
2075
2076         /* now use renderdata and camera to set viewplane */
2077         RE_SetCamera(re, re->scene->camera);
2078         
2079         if(re->r.mode & R_FIELDS)
2080                 do_render_fields_3d(re);
2081         else if(re->r.mode & R_MBLUR)
2082                 do_render_blur_3d(re);
2083         else
2084                 do_render_3d(re);
2085         
2086         /* when border render, check if we have to insert it in black */
2087         if(re->result) {
2088                 if(re->r.mode & R_BORDER) {
2089                         if((re->r.mode & R_CROP)==0) {
2090                                 RenderResult *rres;
2091                                 
2092                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2093
2094                                 /* sub-rect for merge call later on */
2095                                 re->result->tilerect= re->disprect;
2096                                 
2097                                 /* this copying sequence could become function? */
2098                                 /* weak is: it chances disprect from border */
2099                                 re->disprect.xmin= re->disprect.ymin= 0;
2100                                 re->disprect.xmax= re->winx;
2101                                 re->disprect.ymax= re->winy;
2102                                 re->rectx= re->winx;
2103                                 re->recty= re->winy;
2104                                 
2105                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2106                                 
2107                                 merge_render_result(rres, re->result);
2108                                 RE_FreeRenderResult(re->result);
2109                                 re->result= rres;
2110                                 
2111                                 /* weak... the display callback wants an active renderlayer pointer... */
2112                                 re->result->renlay= render_get_active_layer(re, re->result);
2113                                 
2114                                 BLI_rw_mutex_unlock(&re->resultmutex);
2115                 
2116                                 re->display_init(re->dih, re->result);
2117                                 re->display_draw(re->ddh, re->result, NULL);
2118                         }
2119                 }
2120         }
2121 }
2122
2123
2124 /* within context of current Render *re, render another scene.
2125    it uses current render image size and disprect, but doesn't execute composite
2126 */
2127 static void render_scene(Render *re, Scene *sce, int cfra)
2128 {
2129         Render *resc= RE_NewRender(sce->id.name);
2130         int winx= re->winx, winy= re->winy;
2131         
2132         sce->r.cfra= cfra;
2133                 
2134         /* exception: scene uses own size (unfinished code) */
2135         if(0) {
2136                 winx= (sce->r.size*sce->r.xsch)/100;
2137                 winy= (sce->r.size*sce->r.ysch)/100;
2138         }
2139         
2140         /* initial setup */
2141         RE_InitState(resc, re, &sce->r, winx, winy, &re->disprect);
2142         
2143         /* still unsure entity this... */
2144         resc->scene= sce;
2145         
2146         /* ensure scene has depsgraph, base flags etc OK */
2147         set_scene_bg(sce);
2148
2149         /* copy callbacks */
2150         resc->display_draw= re->display_draw;
2151         resc->ddh= re->ddh;
2152         resc->test_break= re->test_break;
2153         resc->tbh= re->tbh;
2154         resc->stats_draw= re->stats_draw;
2155         resc->sdh= re->sdh;
2156         
2157         do_render_fields_blur_3d(resc);
2158 }
2159
2160 static void tag_scenes_for_render(Render *re)
2161 {
2162         bNode *node;
2163         Scene *sce;
2164         
2165         for(sce= G.main->scene.first; sce; sce= sce->id.next)
2166                 sce->id.flag &= ~LIB_DOIT;
2167         
2168         re->scene->id.flag |= LIB_DOIT;
2169         
2170         if(re->scene->nodetree==NULL) return;
2171         
2172         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
2173         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2174                 if(node->type==CMP_NODE_R_LAYERS) {
2175                         if(node->id) {
2176                                 if(node->id != (ID *)re->scene)
2177                                         node->id->flag |= LIB_DOIT;
2178                         }
2179                 }
2180         }
2181         
2182 }
2183
2184 static void ntree_render_scenes(Render *re)
2185 {
2186         bNode *node;
2187         int cfra= re->scene->r.cfra;
2188         
2189         if(re->scene->nodetree==NULL) return;
2190         
2191         tag_scenes_for_render(re);
2192         
2193         /* now foreach render-result node tagged we do a full render */
2194         /* results are stored in a way compisitor will find it */
2195         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2196                 if(node->type==CMP_NODE_R_LAYERS) {
2197                         if(node->id && node->id != (ID *)re->scene) {
2198                                 if(node->id->flag & LIB_DOIT) {
2199                                         render_scene(re, (Scene *)node->id, cfra);
2200                                         node->id->flag &= ~LIB_DOIT;
2201                                 }
2202                         }
2203                 }
2204         }
2205 }
2206
2207 /* helper call to detect if theres a composite with render-result node */
2208 static int composite_needs_render(Scene *sce)
2209 {
2210         bNodeTree *ntree= sce->nodetree;
2211         bNode *node;
2212         
2213         if(ntree==NULL) return 1;
2214         if(sce->use_nodes==0) return 1;
2215         if((sce->r.scemode & R_DOCOMP)==0) return 1;
2216                 
2217         for(node= ntree->nodes.first; node; node= node->next) {
2218                 if(node->type==CMP_NODE_R_LAYERS)
2219                         if(node->id==NULL || node->id==&sce->id)
2220                                 return 1;
2221         }
2222         return 0;
2223 }
2224
2225 /* bad call... need to think over proper method still */
2226 static void render_composit_stats(void *unused, char *str)
2227 {
2228         R.i.infostr= str;
2229         R.stats_draw(R.sdh, &R.i);
2230         R.i.infostr= NULL;
2231 }
2232
2233
2234 /* reads all buffers, calls optional composite, merges in first result->rectf */
2235 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
2236 {
2237         float *rectf, filt[3][3];
2238         int sample;
2239         
2240         /* filtmask needs it */
2241         R= *re;
2242         
2243         /* we accumulate in here */
2244         rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
2245         
2246         for(sample=0; sample<re->r.osa; sample++) {
2247                 RenderResult rres;
2248                 int x, y, mask;
2249                 
2250                 /* set all involved renders on the samplebuffers (first was done by render itself) */
2251                 /* also function below assumes this */
2252                 if(sample) {
2253                         Render *re1;
2254                         
2255                         tag_scenes_for_render(re);
2256                         for(re1= RenderList.first; re1; re1= re1->next) {
2257                                 if(re1->scene->id.flag & LIB_DOIT)
2258                                         if(re1->r.scemode & R_FULL_SAMPLE)
2259                                                 read_render_result(re1, sample);
2260                         }
2261                 }
2262
2263                 /* composite */
2264                 if(ntree) {
2265                         ntreeCompositTagRender(re->scene);
2266                         ntreeCompositTagAnimated(ntree);
2267                         
2268                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2269                 }
2270                 
2271                 /* ensure we get either composited result or the active layer */
2272                 RE_AcquireResultImage(re, &rres);
2273                 
2274                 /* accumulate with filter, and clip */
2275                 mask= (1<<sample);
2276                 mask_array(mask, filt);
2277
2278                 for(y=0; y<re->recty; y++) {
2279                         float *rf= rectf + 4*y*re->rectx;
2280                         float *col= rres.rectf + 4*y*re->rectx;
2281                                 
2282                         for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
2283                                 if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
2284                                 if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
2285                                 if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
2286                                 
2287                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
2288                         }
2289                 }
2290                 
2291                 RE_ReleaseResultImage(re);
2292
2293                 /* show stuff */
2294                 if(sample!=re->osa-1) {
2295                         /* weak... the display callback wants an active renderlayer pointer... */
2296                         re->result->renlay= render_get_active_layer(re, re->result);
2297                         re->display_draw(re->ddh, re->result, NULL);
2298                 }
2299                 
2300                 if(re->test_break(re->tbh))
2301                         break;
2302         }
2303         
2304         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2305         if(re->result->rectf) 
2306                 MEM_freeN(re->result->rectf);
2307         re->result->rectf= rectf;
2308         BLI_rw_mutex_unlock(&re->resultmutex);
2309 }
2310
2311 void RE_MergeFullSample(Render *re, Scene *sce, bNodeTree *ntree)
2312 {
2313         Scene *scene;
2314         bNode *node;
2315         
2316         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
2317         
2318         /* tag scenes unread */
2319         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2320                 scene->id.flag |= LIB_DOIT;
2321         
2322         for(node= ntree->nodes.first; node; node= node->next) {
2323                 if(node->type==CMP_NODE_R_LAYERS) {
2324                         Scene *nodescene= (Scene *)node->id;
2325                         
2326                         if(nodescene==NULL) nodescene= sce;
2327                         if(nodescene->id.flag & LIB_DOIT) {
2328                                 nodescene->r.mode |= R_OSA;     /* render struct needs tables */
2329                                 RE_ReadRenderResult(sce, nodescene);
2330                                 nodescene->id.flag &= ~LIB_DOIT;
2331                         }
2332                 }
2333         }
2334         
2335         /* own render result should be read/allocated */
2336         if(re->scene->id.flag & LIB_DOIT)
2337                 RE_ReadRenderResult(re->scene, re->scene);
2338         
2339         /* and now we can draw (result is there) */
2340         re->display_init(re->dih, re->result);
2341         re->display_clear(re->dch, re->result);
2342         
2343         do_merge_fullsample(re, ntree);
2344 }
2345
2346 /* returns fully composited render-result on given time step (in RenderData) */
2347 static void do_render_composite_fields_blur_3d(Render *re)
2348 {
2349         bNodeTree *ntree= re->scene->nodetree;
2350         
2351         /* INIT seeding, compositor can use random texture */
2352         BLI_srandom(re->r.cfra);
2353         
2354         if(composite_needs_render(re->scene)) {
2355                 /* save memory... free all cached images */
2356                 ntreeFreeCache(ntree);
2357                 
2358                 do_render_fields_blur_3d(re);
2359         }
2360         
2361         /* swap render result */
2362         if(re->r.scemode & R_SINGLE_LAYER)
2363                 pop_render_result(re);
2364         
2365         if(!re->test_break(re->tbh)) {
2366                 
2367                 if(ntree) {
2368                         ntreeCompositTagRender(re->scene);
2369                         ntreeCompositTagAnimated(ntree);
2370                 }
2371                 
2372                 if(1 || !(re->r.scemode & R_COMP_RERENDER)) {
2373                         if(ntree && re->r.scemode & R_DOCOMP) {
2374                                 /* checks if there are render-result nodes that need scene */
2375                                 if((re->r.scemode & R_SINGLE_LAYER)==0)
2376                                         ntree_render_scenes(re);
2377                                 
2378                                 if(!re->test_break(re->tbh)) {
2379                                         ntree->stats_draw= render_composit_stats;
2380                                         ntree->test_break= re->test_break;
2381                                         ntree->sdh= re->sdh;
2382                                         ntree->tbh= re->tbh;
2383                                         /* in case it was never initialized */
2384                                         R.stats_draw= re->stats_draw;
2385                                         
2386                                         if(re->r.scemode & R_FULL_SAMPLE) 
2387                                                 do_merge_fullsample(re, ntree);
2388                                         else
2389                                                 ntreeCompositExecTree(ntree, &re->r, G.background==0);
2390                                         
2391                                         ntree->stats_draw= NULL;
2392                                         ntree->test_break= NULL;
2393                                         ntree->tbh= ntree->sdh= NULL;
2394                                 }
2395                         }
2396                         else if(re->r.scemode & R_FULL_SAMPLE)
2397                                 do_merge_fullsample(re, NULL);
2398                 }
2399         }
2400
2401         /* weak... the display callback wants an active renderlayer pointer... */
2402         re->result->renlay= render_get_active_layer(re, re->result);
2403         re->display_draw(re->ddh, re->result, NULL);
2404 }
2405
2406 static void renderresult_stampinfo(Scene *scene)
2407 {
2408         RenderResult rres;
2409         Render *re= RE_GetRender(scene->id.name);
2410
2411         /* this is the basic trick to get the displayed float or char rect from render result */
2412         RE_AcquireResultImage(re, &rres);
2413         BKE_stamp_buf(scene, (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
2414         RE_ReleaseResultImage(re);
2415 }
2416
2417 static void do_render_seq(Render * re)
2418 {
2419         static int recurs_depth = 0;
2420         struct ImBuf *ibuf;
2421         RenderResult *rr = re->result;
2422         int cfra = re->r.cfra;
2423
2424         recurs_depth++;
2425
2426         ibuf= give_ibuf_seq(re->scene, rr->rectx, rr->recty, cfra, 0, 100.0);
2427
2428         recurs_depth--;
2429         
2430         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2431
2432         if(ibuf) {
2433                 if(ibuf->rect_float) {
2434                         if (!rr->rectf)
2435                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
2436                         
2437                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2438                         
2439                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
2440                            can hang around when sequence render has rendered a 32 bits one before */
2441                         if(rr->rect32) {
2442                                 MEM_freeN(rr->rect32);
2443                                 rr->rect32= NULL;
2444                         }
2445                 }
2446                 else if(ibuf->rect) {
2447                         if (!rr->rect32)
2448                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2449
2450                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
2451
2452                         /* if (ibuf->zbuf) { */
2453                         /*      if (R.rectz) freeN(R.rectz); */
2454                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
2455                         /* } */
2456                 }
2457                 
2458                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
2459                         Editing * ed = re->scene->ed;
2460                         if (ed) {
2461                                 free_imbuf_seq(&ed->seqbase, TRUE);
2462                         }
2463                 }
2464         }
2465         else {
2466                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
2467                 if (rr->rectf)
2468                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
2469                 else if (rr->rect32)
2470                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
2471                 else
2472                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2473         }
2474
2475         BLI_rw_mutex_unlock(&re->resultmutex);
2476 }
2477
2478 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2479
2480 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2481 static void do_render_all_options(Render *re)
2482 {
2483         re->i.starttime= PIL_check_seconds_timer();
2484
2485         /* ensure no images are in memory from previous animated sequences */
2486         BKE_image_all_free_anim_ibufs(re->r.cfra);
2487         
2488         if((re->r.scemode & R_DOSEQ) && re->scene->ed && re->scene->ed->seqbase.first) {
2489                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2490                 if(!re->test_break(re->tbh)) 
2491                         do_render_seq(re);
2492                 
2493                 re->stats_draw(re->sdh, &re->i);
2494                 re->display_draw(re->ddh, re->result, NULL);
2495         }
2496         else {
2497                 do_render_composite_fields_blur_3d(re);
2498         }
2499         
2500         /* for UI only */
2501         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2502         renderresult_add_names(re->result);
2503         BLI_rw_mutex_unlock(&re->resultmutex);
2504         
2505         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2506         
2507         re->stats_draw(re->sdh, &re->i);
2508         
2509         /* stamp image info here */
2510         if((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
2511                 renderresult_stampinfo(re->scene);
2512                 re->display_draw(re->ddh, re->result, NULL);
2513         }
2514 }
2515
2516 static int is_rendering_allowed(Render *re)
2517 {
2518         SceneRenderLayer *srl;
2519         
2520         /* forbidden combinations */
2521         if(re->r.mode & R_PANORAMA) {
2522                 if(re->r.mode & R_BORDER) {
2523                         re->error(re->erh, "No border supported for Panorama");
2524                         return 0;
2525                 }
2526                 if(re->r.mode & R_ORTHO) {
2527                         re->error(re->erh, "No Ortho render possible for Panorama");
2528                         return 0;
2529                 }
2530         }
2531         
2532         if(re->r.mode & R_BORDER) {
2533                 if(re->r.border.xmax <= re->r.border.xmin || 
2534                    re->r.border.ymax <= re->r.border.ymin) {
2535                         re->error(re->erh, "No border area selected.");
2536                         return 0;
2537                 }
2538                 if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2539                         re->error(re->erh, "Border render and Buffer-save not supported yet");
2540                         return 0;
2541                 }
2542         }
2543         
2544         if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2545                 char str[FILE_MAX];
2546                 
2547                 render_unique_exr_name(re, str, 0);
2548                 
2549                 if (BLI_is_writable(str)==0) {
2550                         re->error(re->erh, "Can not save render buffers, check the temp default path");
2551                         return 0;
2552                 }
2553                 
2554                 /* no osa + fullsample won't work... */
2555                 if(re->osa==0)
2556                         re->r.scemode &= ~R_FULL_SAMPLE;
2557                 
2558                 /* no fullsample and edge */
2559                 if((re->r.scemode & R_FULL_SAMPLE) && (re->r.mode & R_EDGE)) {
2560                         re->error(re->erh, "Full Sample doesn't support Edge Enhance");
2561                         return 0;
2562                 }
2563                 
2564         }
2565         else
2566                 re->r.scemode &= ~R_FULL_SAMPLE;        /* clear to be sure */
2567         
2568         if(re->r.scemode & R_DOCOMP) {
2569                 if(re->scene->use_nodes) {
2570                         bNodeTree *ntree= re->scene->nodetree;
2571                         bNode *node;
2572                 
2573                         if(ntree==NULL) {
2574                                 re->error(re->erh, "No Nodetree in Scene");
2575                                 return 0;
2576                         }
2577                         
2578                         for(node= ntree->nodes.first; node; node= node->next)
2579                                 if(node->type==CMP_NODE_COMPOSITE)
2580                                         break;
2581                         
2582                         
2583                         if(node==NULL) {
2584                                 re->error(re->erh, "No Render Output Node in Scene");
2585                                 return 0;
2586                         }
2587                 }
2588         }
2589         
2590         /* check valid camera, without camera render is OK (compo, seq) */
2591         if(re->scene->camera==NULL)
2592                 re->scene->camera= scene_find_camera(re->scene);
2593         
2594         if(!(re->r.scemode & (R_DOSEQ|R_DOCOMP))) {
2595                 if(re->scene->camera==NULL) {
2596                         re->error(re->erh, "No camera");
2597                         return 0;
2598                 }
2599         }
2600         
2601         /* layer flag tests */
2602         if(re->r.scemode & R_SINGLE_LAYER) {
2603                 srl= BLI_findlink(&re->scene->r.layers, re->r.actlay);
2604                 /* force layer to be enabled */
2605                 srl->layflag &= ~SCE_LAY_DISABLE;
2606         }
2607         
2608         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
2609                 if(!(srl->layflag & SCE_LAY_DISABLE))
2610                         break;
2611         if(srl==NULL) {
2612                 re->error(re->erh, "All RenderLayers are disabled");
2613                 return 0;
2614         }
2615         
2616         /* renderer */
2617         if(!ELEM(re->r.renderer, R_INTERN, R_YAFRAY)) {
2618                 re->error(re->erh, "Unknown render engine set");
2619                 return 0;
2620         }
2621         return 1;
2622 }
2623
2624 static void update_physics_cache(Render *re, Scene *scene, int anim_init)
2625 {
2626         PTCacheBaker baker;
2627
2628         baker.scene = scene;
2629         baker.pid = NULL;
2630         baker.bake = 0;
2631         baker.render = 1;
2632         baker.anim_init = 1;
2633         baker.quick_step = 1;
2634         baker.break_test = re->test_break;
2635         baker.break_data = re->tbh;
2636         baker.progressbar = NULL;
2637
2638         BKE_ptcache_make_cache(&baker);
2639 }
2640 /* evaluating scene options for general Blender render */
2641 static int render_initialize_from_scene(Render *re, Scene *scene, int anim, int anim_init)
2642 {
2643         int winx, winy;
2644         rcti disprect;
2645         
2646         /* r.xsch and r.ysch has the actual view window size
2647                 r.border is the clipping rect */
2648         
2649         /* calculate actual render result and display size */
2650         winx= (scene->r.size*scene->r.xsch)/100;
2651         winy= (scene->r.size*scene->r.ysch)/100;
2652         
2653         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2654         if(scene->r.mode & R_BORDER) {
2655                 disprect.xmin= scene->r.border.xmin*winx;
2656                 disprect.xmax= scene->r.border.xmax*winx;
2657                 
2658                 disprect.ymin= scene->r.border.ymin*winy;
2659                 disprect.ymax= scene->r.border.ymax*winy;
2660         }
2661         else {
2662                 disprect.xmin= disprect.ymin= 0;
2663                 disprect.xmax= winx;
2664                 disprect.ymax= winy;
2665         }
2666         
2667         re->scene= scene;
2668         
2669         /* not too nice, but it survives anim-border render */
2670         if(anim) {
2671                 re->disprect= disprect;
2672                 return 1;
2673         }
2674         
2675         /* check all scenes involved */
2676         tag_scenes_for_render(re);
2677
2678         /*
2679          * Disabled completely for now,
2680          * can be later set as render profile option
2681          * and default for background render.
2682         */
2683         if(0) {
2684                 /* make sure dynamics are up to date */
2685                 update_physics_cache(re, scene, anim_init);
2686         }
2687         
2688         if(scene->r.scemode & R_SINGLE_LAYER)
2689                 push_render_result(re);
2690         
2691         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2692         if(!re->ok)  /* if an error was printed, abort */
2693                 return 0;
2694         
2695         /* initstate makes new result, have to send changed tags around */
2696         ntreeCompositTagRender(re->scene);
2697         
2698         if(!is_rendering_allowed(re))
2699                 return 0;
2700         
2701         re->display_init(re->dih, re->result);
2702         re->display_clear(re->dch, re->result);
2703         
2704         return 1;
2705 }
2706
2707 /* general Blender frame render call */
2708 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
2709 {
2710         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2711         G.rendering= 1;
2712         re->result_ok= 0;
2713         
2714         scene->r.cfra= frame;
2715         
2716         if(render_initialize_from_scene(re, scene, 0, 0)) {
2717                 do_render_all_options(re);
2718         }
2719         
2720         /* UGLY WARNING */
2721         G.rendering= 0;
2722         re->result_ok= 1;
2723 }
2724
2725 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
2726 {
2727         char name[FILE_MAX];
2728         RenderResult rres;
2729         
2730         RE_AcquireResultImage(re, &rres);
2731
2732         /* write movie or image */
2733         if(BKE_imtype_is_movie(scene->r.imtype)) {
2734                 int dofree = 0;
2735                 /* note; the way it gets 32 bits rects is weak... */
2736                 if(rres.rect32==NULL) {
2737                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2738                         dofree = 1;
2739                 }
2740                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
2741                 mh->append_movie(&re->r, scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
2742                 if(dofree) {
2743                         MEM_freeN(rres.rect32);
2744                 }
2745                 printf("Append frame %d", scene->r.cfra);
2746         } 
2747         else {
2748                 BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2749                 
2750                 if(re->r.imtype==R_MULTILAYER) {
2751                         if(re->result) {
2752                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2753                                 printf("Saved: %s", name);
2754                         }
2755                 }
2756                 else {
2757                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
2758                         int ok;
2759                         
2760                         /* if not exists, BKE_write_ibuf makes one */
2761                         ibuf->rect= (unsigned int *)rres.rect32;    
2762                         ibuf->rect_float= rres.rectf;
2763                         ibuf->zbuf_float= rres.rectz;
2764                         
2765                         /* float factor for random dither, imbuf takes care of it */
2766                         ibuf->dither= scene->r.dither_intensity;
2767                         /* gamma correct to sRGB color space */
2768                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2769                                 ibuf->profile = IB_PROFILE_SRGB;
2770
2771                         ok= BKE_write_ibuf(scene, ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2772                         
2773                         if(ok==0) {
2774                                 printf("Render error: cannot save %s\n", name);
2775                                 G.afbreek=1;
2776                         }
2777                         else printf("Saved: %s", name);
2778                         
2779                         /* optional preview images for exr */
2780                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
2781                                 if(BLI_testextensie(name, ".exr")) 
2782                                         name[strlen(name)-4]= 0;
2783                                 BKE_add_image_extension(scene, name, R_JPEG90);
2784                                 ibuf->depth= 24; 
2785                                 BKE_write_ibuf(scene, ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
2786                                 printf("\nSaved: %s", name);
2787                         }
2788                         
2789                                         /* imbuf knows which rects are not part of ibuf */
2790                         IMB_freeImBuf(ibuf);
2791                 }
2792         }
2793         
2794         RE_ReleaseResultImage(re);
2795
2796         BLI_timestr(re->i.lastframetime, name);
2797         printf(" Time: %s\n", name);
2798         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2799 }
2800
2801 /* saves images to disk */
2802 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra, int tfra)
2803 {
2804         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
2805         unsigned int lay;
2806         int cfrao= scene->r.cfra;
2807         int nfra;
2808         
2809         /* do not fully call for each frame, it initializes & pops output window */
2810         if(!render_initialize_from_scene(re, scene, 0, 1))
2811                 return;
2812         
2813         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2814         /* is also set by caller renderwin.c */
2815         G.rendering= 1;
2816         re->result_ok= 0;
2817         
2818         if(BKE_imtype_is_movie(scene->r.imtype))
2819                 mh->start_movie(scene, &re->r, re->rectx, re->recty);
2820         
2821         if (mh->get_next_frame) {
2822                 while (!(G.afbreek == 1)) {
2823                         int nf = mh->get_next_frame(&re->r);
2824                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2825                                 scene->r.cfra = re->r.cfra = nf;
2826                                 
2827                                 do_render_all_options(re);
2828
2829                                 if(re->test_break(re->tbh) == 0) {
2830                                         do_write_image_or_movie(re, scene, mh);
2831                                 }
2832                         } else {
2833                                 if(re->test_break(re->tbh))
2834                                         G.afbreek= 1;
2835                         }
2836                 }
2837         } else {
2838                 for(nfra= sfra, scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
2839                         char name[FILE_MAX];
2840                         
2841                         /* only border now, todo: camera lens. (ton) */
2842                         render_initialize_from_scene(re, scene, 1, 0);
2843
2844                         if(nfra!=scene->r.cfra) {
2845                                 /*
2846                                  * Skip this frame, but update for physics and particles system.
2847                                  * From convertblender.c:
2848                                  * in localview, lamps are using normal layers, objects only local bits.
2849                                  */
2850                                 if(scene->lay & 0xFF000000)
2851                                         lay= scene->lay & 0xFF000000;
2852                                 else
2853                                         lay= scene->lay;
2854
2855                                 scene_update_for_newframe(scene, lay);
2856                                 continue;
2857                         }
2858                         else
2859                                 nfra+= tfra;
2860
2861                         /* Touch/NoOverwrite options are only valid for image's */
2862                         if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2863                                 if(scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2864                                         BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2865
2866                                 if(scene->r.mode & R_NO_OVERWRITE && BLI_exist(name)) {
2867                                         printf("skipping existing frame \"%s\"\n", name);
2868                                         continue;
2869                                 }
2870                                 if(scene->r.mode & R_TOUCH && !BLI_exist(name)) {
2871                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2872                                         BLI_touch(name);
2873                                 }
2874                         }
2875
2876                         re->r.cfra= scene->r.cfra;         /* weak.... */
2877                         
2878                         do_render_all_options(re);
2879                         
2880                         if(re->test_break(re->tbh) == 0)
2881                                 do_write_image_or_movie(re, scene, mh);
2882                         else
2883                                 G.afbreek= 1;
2884                 
2885                         if(G.afbreek==1) {
2886                                 /* remove touched file */
2887                                 if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2888                                         if (scene->r.mode & R_TOUCH && BLI_exist(name) && BLI_filepathsize(name) == 0) {
2889                                                 BLI_delete(name, 0, 0);
2890                                         }
2891                                 }
2892                                 
2893                                 break;
2894                         }
2895                 }
2896         }
2897         
2898         /* end movie */
2899         if(BKE_imtype_is_movie(scene->r.imtype))
2900                 mh->end_movie();
2901
2902         scene->r.cfra= cfrao;
2903         
2904         /* UGLY WARNING */
2905         G.rendering= 0;
2906         re->result_ok= 1;
2907 }
2908
2909 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2910
2911 /* only the temp file! */
2912 void RE_ReadRenderResult(Scene *scene, Scene *scenode)
2913 {
2914         Render *re;
2915         int winx, winy;
2916         rcti disprect;
2917         
2918         /* calculate actual render result and display size */
2919         winx= (scene->r.size*scene->r.xsch)/100;
2920         winy= (scene->r.size*scene->r.ysch)/100;
2921         
2922         /* only in movie case we render smaller part */
2923         if(scene->r.mode & R_BORDER) {
2924                 disprect.xmin= scene->r.border.xmin*winx;
2925                 disprect.xmax= scene->r.border.xmax*winx;
2926                 
2927                 disprect.ymin= scene->r.border.ymin*winy;
2928                 disprect.ymax= scene->r.border.ymax*winy;
2929         }
2930         else {
2931                 disprect.xmin= disprect.ymin= 0;
2932                 disprect.xmax= winx;
2933                 disprect.ymax= winy;
2934         }
2935         
2936         if(scenode)
2937                 scene= scenode;
2938         
2939         /* get render: it can be called from UI with draw callbacks */
2940         re= RE_GetRender(scene->id.name);
2941         if(re==NULL)
2942                 re= RE_NewRender(scene->id.name);
2943         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2944         re->scene= scene;
2945         
2946         read_render_result(re, 0);
2947 }
2948
2949 void RE_set_max_threads(int threads)
2950 {
2951         if (threads==0) {
2952                 commandline_threads = BLI_system_thread_count();
2953         } else if(threads>=1 && threads<=BLENDER_MAX_THREADS) {
2954                 commandline_threads= threads;
2955         } else {
2956                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2957         }
2958 }
2959
2960 void RE_init_threadcount(Render *re) 
2961 {
2962         if(commandline_threads >= 1) { /* only set as an arg in background mode */
2963                 re->r.threads= MIN2(commandline_threads, BLENDER_MAX_THREADS);
2964         } else if ((re->r.mode & R_FIXED_THREADS)==0 || commandline_threads == 0) { /* Automatic threads */
2965                 re->r.threads = BLI_system_thread_count();
2966         }
2967 }
2968
2969 /************************** External Engines ***************************/
2970
2971 RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w, int h)
2972 {
2973         Render *re= engine->re;
2974         RenderResult *result;
2975         rcti disprect;
2976
2977         /* ensure the coordinates are within the right limits */
2978         CLAMP(x, 0, re->result->rectx);
2979         CLAMP(y, 0, re->result->recty);
2980         CLAMP(w, 0, re->result->rectx);
2981         CLAMP(h, 0, re->result->recty);
2982
2983         if(x + w > re->result->rectx)
2984                 w= re->result->rectx - x;
2985         if(y + h > re->result->recty)
2986                 h= re->result->recty - y;
2987
2988         /* allocate a render result */
2989         disprect.xmin= x;
2990         disprect.xmax= x+w;
2991         disprect.ymin= y;
2992         disprect.ymax= y+h;
2993
2994         if(0) { // XXX (re->r.scemode & R_FULL_SAMPLE)) {
2995                 result= new_full_sample_buffers(re, &engine->fullresult, &disprect, 0);
2996         }
2997         else {
2998                 result= new_render_result(re, &disprect, 0, RR_USEMEM);
2999                 BLI_addtail(&engine->fullresult, result);
3000         }
3001
3002         return result;
3003 }
3004
3005 void RE_engine_update_result(RenderEngine *engine, RenderResult *result)
3006 {
3007         Render *re= engine->re;
3008
3009         if(result && render_display_draw_enabled(re)) {
3010                 result->renlay= result->layers.first; // weak
3011                 re->display_draw(re->ddh, result, NULL);
3012         }
3013 }
3014
3015 void RE_engine_end_result(RenderEngine *engine, RenderResult *result)
3016 {
3017         Render *re= engine->re;
3018
3019         if(!result)
3020                 return;
3021
3022         /* merge */
3023         if(re->result->exrhandle) {
3024                 RenderResult *rr, *rrpart;
3025                 
3026                 // XXX crashes, exr expects very particular part sizes
3027                 for(rr= re->result, rrpart= result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
3028                         save_render_result_tile(rr, rrpart);
3029         }
3030         else if(render_display_draw_enabled(re)) {
3031                 /* on break, don't merge in result for preview renders, looks nicer */
3032                 if(re->test_break(re->tbh) && (re->r.scemode & R_PREVIEWBUTS));
3033                 else merge_render_result(re->result, result);
3034         }
3035
3036         /* draw */
3037         if(!re->test_break(re->tbh) && render_display_draw_enabled(re)) {
3038                 result->renlay= result->layers.first; // weak
3039                 re->display_draw(re->ddh, result, NULL);
3040         }
3041
3042         /* free */
3043         free_render_result(&engine->fullresult, result);
3044 }
3045
3046 int RE_engine_test_break(RenderEngine *engine)
3047 {
3048         Render *re= engine->re;
3049
3050         return re->test_break(re->tbh);
3051 }
3052
3053 void RE_engine_update_stats(RenderEngine *engine, char *stats, char *info)
3054 {
3055         Render *re= engine->re;
3056
3057         re->i.statstr= stats;
3058         re->i.infostr= info;
3059         re->stats_draw(re->sdh, &re->i);
3060         re->i.infostr= NULL;
3061         re->i.statstr= NULL;
3062 }
3063
3064 /* loads in image into a result, size must match
3065  * x/y offsets are only used on a partial copy when dimensions dont match */
3066 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, char *filename)
3067 {
3068         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect);
3069
3070         if(ibuf  && (ibuf->rect || ibuf->rect_float)) {
3071                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
3072                         if(ibuf->rect_float==NULL)
3073                                 IMB_float_from_rect(ibuf);
3074
3075                         memcpy(layer->rectf, ibuf->rect_float, sizeof(float)*4*layer->rectx*layer->recty);
3076                 } else {
3077                         if ((ibuf->x >= layer->rectx) && (ibuf->y >= layer->recty)) {
3078                                 ImBuf *ibuf_clip;
3079
3080                                 if(ibuf->rect_float==NULL)
3081                                         IMB_float_from_rect(ibuf);
3082
3083                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat, 0);
3084                                 if(ibuf_clip) {
3085                                         IMB_rectcpy(ibuf_clip, ibuf, 0,0, 0,0, layer->rectx, layer->recty);
3086
3087                                         memcpy(layer->rectf, ibuf_clip->rect_float, sizeof(float)*4*layer->rectx*layer->recty);
3088                                         IMB_freeImBuf(ibuf_clip);
3089                                 }