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