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