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