am learning bad spelling from blender. grr
[blender.git] / source / blender / render / intern / source / rendercore.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributors: Hos, Robert Wenzlaff.
24  * Contributors: 2004/2005/2006 Blender Foundation, full recode
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /* system includes */
30 #include <stdio.h>
31 #include <math.h>
32 #include <float.h>
33 #include <string.h>
34 #include <assert.h>
35
36 /* External modules: */
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_math.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_jitter.h"
42 #include "BLI_rand.h"
43 #include "BLI_threads.h"
44
45 #include "BKE_utildefines.h"
46
47 #include "DNA_image_types.h"
48 #include "DNA_lamp_types.h"
49 #include "DNA_material_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_group_types.h"
52
53 #include "BKE_global.h"
54 #include "BKE_image.h"
55 #include "BKE_main.h"
56 #include "BKE_node.h"
57 #include "BKE_texture.h"
58
59 #include "IMB_imbuf_types.h"
60 #include "IMB_imbuf.h"
61
62 /* local include */
63 #include "renderpipeline.h"
64 #include "render_types.h"
65 #include "renderdatabase.h"
66 #include "occlusion.h"
67 #include "pixelblending.h"
68 #include "pixelshading.h"
69 #include "shadbuf.h"
70 #include "shading.h"
71 #include "sss.h"
72 #include "zbuf.h"
73 #include "RE_raytrace.h"
74
75 #include "PIL_time.h"
76
77 /* own include */
78 #include "rendercore.h"
79
80
81 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
82 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
83 /* only to be used here in this file, it's for speed */
84 extern struct Render R;
85 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
86
87 /* x and y are current pixels in rect to be rendered */
88 /* do not normalize! */
89 void calc_view_vector(float *view, float x, float y)
90 {
91
92         view[2]= -ABS(R.clipsta);
93         
94         if(R.r.mode & R_ORTHO) {
95                 view[0]= view[1]= 0.0f;
96         }
97         else {
98                 
99                 if(R.r.mode & R_PANORAMA)
100                         x-= R.panodxp;
101                 
102                 /* move x and y to real viewplane coords */
103                 x= (x/(float)R.winx);
104                 view[0]= R.viewplane.xmin + x*(R.viewplane.xmax - R.viewplane.xmin);
105                 
106                 y= (y/(float)R.winy);
107                 view[1]= R.viewplane.ymin + y*(R.viewplane.ymax - R.viewplane.ymin);
108                 
109 //              if(R.flag & R_SEC_FIELD) {
110 //                      if(R.r.mode & R_ODDFIELD) view[1]= (y+R.ystart)*R.ycor;
111 //                      else view[1]= (y+R.ystart+1.0)*R.ycor;
112 //              }
113 //              else view[1]= (y+R.ystart+R.bluroffsy+0.5)*R.ycor;
114         
115                 if(R.r.mode & R_PANORAMA) {
116                         float u= view[0] + R.panodxv; float v= view[2];
117                         view[0]= R.panoco*u + R.panosi*v;
118                         view[2]= -R.panosi*u + R.panoco*v;
119                 }
120         }
121 }
122
123 void calc_renderco_ortho(float *co, float x, float y, int z)
124 {
125         /* x and y 3d coordinate can be derived from pixel coord and winmat */
126         float fx= 2.0f/(R.winx*R.winmat[0][0]);
127         float fy= 2.0f/(R.winy*R.winmat[1][1]);
128         float zco;
129         
130         co[0]= (x - 0.5f*R.winx)*fx - R.winmat[3][0]/R.winmat[0][0];
131         co[1]= (y - 0.5f*R.winy)*fy - R.winmat[3][1]/R.winmat[1][1];
132         
133         zco= ((float)z)/2147483647.0f;
134         co[2]= R.winmat[3][2]/( R.winmat[2][3]*zco - R.winmat[2][2] );
135 }
136
137 void calc_renderco_zbuf(float *co, float *view, int z)
138 {
139         float fac, zco;
140         
141         /* inverse of zbuf calc: zbuf = MAXZ*hoco_z/hoco_w */
142         zco= ((float)z)/2147483647.0f;
143         co[2]= R.winmat[3][2]/( R.winmat[2][3]*zco - R.winmat[2][2] );
144
145         fac= co[2]/view[2];
146         co[0]= fac*view[0];
147         co[1]= fac*view[1];
148 }
149
150 /* also used in zbuf.c and shadbuf.c */
151 int count_mask(unsigned short mask)
152 {
153         if(R.samples)
154                 return (R.samples->cmask[mask & 255]+R.samples->cmask[mask>>8]);
155         return 0;
156 }
157
158 static int calchalo_z(HaloRen *har, int zz)
159 {
160         
161         if(har->type & HA_ONLYSKY) {
162                 if(zz < 0x7FFFFFF0) zz= - 0x7FFFFF;     /* edge render messes zvalues */
163         }
164         else {
165                 zz= (zz>>8);
166         }
167         return zz;
168 }
169
170
171
172 static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, int od, float dist, float xn, float yn, PixStr *ps)
173 {
174         float col[4], accol[4], fac;
175         int amount, amountm, zz, flarec, sample, fullsample, mask=0;
176         
177         fullsample= (totsample > 1);
178         amount= 0;
179         accol[0]=accol[1]=accol[2]=accol[3]= 0.0f;
180         flarec= har->flarec;
181         
182         while(ps) {
183                 amountm= count_mask(ps->mask);
184                 amount+= amountm;
185                 
186                 zz= calchalo_z(har, ps->z);
187                 if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
188                         if(shadeHaloFloat(har, col, zz, dist, xn, yn, flarec)) {
189                                 flarec= 0;
190
191                                 if(fullsample) {
192                                         for(sample=0; sample<totsample; sample++)
193                                                 if(ps->mask & (1 << sample))
194                                                         addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
195                                 }
196                                 else {
197                                         fac= ((float)amountm)/(float)R.osa;
198                                         accol[0]+= fac*col[0];
199                                         accol[1]+= fac*col[1];
200                                         accol[2]+= fac*col[2];
201                                         accol[3]+= fac*col[3];
202                                 }
203                         }
204                 }
205                 
206                 mask |= ps->mask;
207                 ps= ps->next;
208         }
209
210         /* now do the sky sub-pixels */
211         amount= R.osa-amount;
212         if(amount) {
213                 if(shadeHaloFloat(har, col, 0x7FFFFF, dist, xn, yn, flarec)) {
214                         if(!fullsample) {
215                                 fac= ((float)amount)/(float)R.osa;
216                                 accol[0]+= fac*col[0];
217                                 accol[1]+= fac*col[1];
218                                 accol[2]+= fac*col[2];
219                                 accol[3]+= fac*col[3];
220                         }
221                 }
222         }
223
224         if(fullsample) {
225                 for(sample=0; sample<totsample; sample++)
226                         if(!(mask & (1 << sample)))
227                                 addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
228         }
229         else {
230                 col[0]= accol[0];
231                 col[1]= accol[1];
232                 col[2]= accol[2];
233                 col[3]= accol[3];
234                 
235                 for(sample=0; sample<totsample; sample++)
236                         addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
237         }
238 }
239
240 static void halo_tile(RenderPart *pa, RenderLayer *rl)
241 {
242         RenderLayer *rlpp[RE_MAX_OSA];
243         HaloRen *har;
244         rcti disprect= pa->disprect, testrect= pa->disprect;
245         float dist, xsq, ysq, xn, yn;
246         float col[4];
247         intptr_t *rd= NULL;
248         int a, *rz, zz, y, sample, totsample, od;
249         short minx, maxx, miny, maxy, x;
250         unsigned int lay= rl->lay;
251
252         /* we don't render halos in the cropped area, gives errors in flare counter */
253         if(pa->crop) {
254                 testrect.xmin+= pa->crop;
255                 testrect.xmax-= pa->crop;
256                 testrect.ymin+= pa->crop;
257                 testrect.ymax-= pa->crop;
258         }
259         
260         totsample= get_sample_layers(pa, rl, rlpp);
261
262         for(a=0; a<R.tothalo; a++) {
263                 har= R.sortedhalos[a];
264
265                 /* layer test, clip halo with y */
266                 if((har->lay & lay)==0);
267                 else if(testrect.ymin > har->maxy);
268                 else if(testrect.ymax < har->miny);
269                 else {
270                         
271                         minx= floor(har->xs-har->rad);
272                         maxx= ceil(har->xs+har->rad);
273                         
274                         if(testrect.xmin > maxx);
275                         else if(testrect.xmax < minx);
276                         else {
277                                 
278                                 minx= MAX2(minx, testrect.xmin);
279                                 maxx= MIN2(maxx, testrect.xmax);
280                         
281                                 miny= MAX2(har->miny, testrect.ymin);
282                                 maxy= MIN2(har->maxy, testrect.ymax);
283                         
284                                 for(y=miny; y<maxy; y++) {
285                                         int rectofs= (y-disprect.ymin)*pa->rectx + (minx - disprect.xmin);
286                                         rz= pa->rectz + rectofs;
287                                         od= rectofs;
288                                         
289                                         if(pa->rectdaps)
290                                                 rd= pa->rectdaps + rectofs;
291                                         
292                                         yn= (y-har->ys)*R.ycor;
293                                         ysq= yn*yn;
294                                         
295                                         for(x=minx; x<maxx; x++, rz++, od++) {
296                                                 xn= x- har->xs;
297                                                 xsq= xn*xn;
298                                                 dist= xsq+ysq;
299                                                 if(dist<har->radsq) {
300                                                         if(rd && *rd) {
301                                                                 halo_pixelstruct(har, rlpp, totsample, od, dist, xn, yn, (PixStr *)*rd);
302                                                         }
303                                                         else {
304                                                                 zz= calchalo_z(har, *rz);
305                                                                 if((zz> har->zs) || (har->mat && (har->mat->mode & MA_HALO_SOFT))) {
306                                                                         if(shadeHaloFloat(har, col, zz, dist, xn, yn, har->flarec)) {
307                                                                                 for(sample=0; sample<totsample; sample++)
308                                                                                         addalphaAddfacFloat(rlpp[sample]->rectf + od*4, col, har->add);
309                                                                         }
310                                                                 }
311                                                         }
312                                                 }
313                                                 if(rd) rd++;
314                                         }
315                                 }
316                         }
317                 }
318                 if(R.test_break(R.tbh) ) break; 
319         }
320 }
321
322 static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
323 {
324         RenderLayer *rlpp[RE_MAX_OSA];
325         ShadeInput shi;
326         float *pass;
327         float fac, col[4];
328         intptr_t *rd= pa->rectdaps;
329         int *rz= pa->rectz;
330         int x, y, sample, totsample, fullsample, od;
331         
332         totsample= get_sample_layers(pa, rl, rlpp);
333         fullsample= (totsample > 1);
334
335         shade_input_initialize(&shi, pa, rl, 0); /* this zero's ShadeInput for us */
336         
337         for(od=0, y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
338                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, rz++, od++) {
339                         
340                         calc_view_vector(shi.view, x, y);
341                         
342                         if(rd && *rd) {
343                                 PixStr *ps= (PixStr *)*rd;
344                                 int count, totsamp= 0, mask= 0;
345                                 
346                                 while(ps) {
347                                         if(R.r.mode & R_ORTHO)
348                                                 calc_renderco_ortho(shi.co, (float)x, (float)y, ps->z);
349                                         else
350                                                 calc_renderco_zbuf(shi.co, shi.view, ps->z);
351                                         
352                                         totsamp+= count= count_mask(ps->mask);
353                                         mask |= ps->mask;
354
355                                         col[0]= col[1]= col[2]= col[3]= 0.0f;
356                                         renderspothalo(&shi, col, 1.0f);
357
358                                         if(fullsample) {
359                                                 for(sample=0; sample<totsample; sample++) {
360                                                         if(ps->mask & (1 << sample)) {
361                                                                 pass= rlpp[sample]->rectf + od*4;
362                                                                 pass[0]+= col[0];
363                                                                 pass[1]+= col[1];
364                                                                 pass[2]+= col[2];
365                                                                 pass[3]+= col[3];
366                                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
367                                                         }
368                                                 }
369                                         }
370                                         else {
371                                                 fac= ((float)count)/(float)R.osa;
372                                                 pass= rl->rectf + od*4;
373                                                 pass[0]+= fac*col[0];
374                                                 pass[1]+= fac*col[1];
375                                                 pass[2]+= fac*col[2];
376                                                 pass[3]+= fac*col[3];
377                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
378                                         }
379
380                                         ps= ps->next;
381                                 }
382
383                                 if(totsamp<R.osa) {
384                                         shi.co[2]= 0.0f;
385
386                                         col[0]= col[1]= col[2]= col[3]= 0.0f;
387                                         renderspothalo(&shi, col, 1.0f);
388
389                                         if(fullsample) {
390                                                 for(sample=0; sample<totsample; sample++) {
391                                                         if(!(mask & (1 << sample))) {
392                                                                 pass= rlpp[sample]->rectf + od*4;
393                                                                 pass[0]+= col[0];
394                                                                 pass[1]+= col[1];
395                                                                 pass[2]+= col[2];
396                                                                 pass[3]+= col[3];
397                                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
398                                                         }
399                                                 }
400                                         }
401                                         else {
402                                                 fac= ((float)R.osa-totsamp)/(float)R.osa;
403                                                 pass= rl->rectf + od*4;
404                                                 pass[0]+= fac*col[0];
405                                                 pass[1]+= fac*col[1];
406                                                 pass[2]+= fac*col[2];
407                                                 pass[3]+= fac*col[3];
408                                                 if(pass[3]>1.0f) pass[3]= 1.0f;
409                                         }
410                                 }
411                         }
412                         else {
413                                 if(R.r.mode & R_ORTHO)
414                                         calc_renderco_ortho(shi.co, (float)x, (float)y, *rz);
415                                 else
416                                         calc_renderco_zbuf(shi.co, shi.view, *rz);
417                                 
418                                 col[0]= col[1]= col[2]= col[3]= 0.0f;
419                                 renderspothalo(&shi, col, 1.0f);
420
421                                 for(sample=0; sample<totsample; sample++) {
422                                         pass= rlpp[sample]->rectf + od*4;
423                                         pass[0]+= col[0];
424                                         pass[1]+= col[1];
425                                         pass[2]+= col[2];
426                                         pass[3]+= col[3];
427                                         if(pass[3]>1.0f) pass[3]= 1.0f;
428                                 }
429                         }
430                         
431                         if(rd) rd++;
432                 }
433                 if(y&1)
434                         if(R.test_break(R.tbh)) break; 
435         }
436 }                               
437
438
439 /* ********************* MAINLOOPS ******************** */
440
441 /* osa version */
442 static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset, ShadeInput *shi, ShadeResult *shr)
443 {
444         RenderPass *rpass;
445
446         /* combined rgb */
447         add_filt_fmask(curmask, shr->combined, rl->rectf + 4*offset, rectx);
448         
449         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
450                 float *fp, *col= NULL;
451                 int pixsize= 3;
452                 
453                 switch(rpass->passtype) {
454                         case SCE_PASS_Z:
455                                 fp= rpass->rect + offset;
456                                 *fp= shr->z;
457                                 break;
458                         case SCE_PASS_RGBA:
459                                 col= shr->col;
460                                 pixsize= 4;
461                                 break;
462                         case SCE_PASS_DIFFUSE:
463                                 col= shr->diff;
464                                 break;
465                         case SCE_PASS_SPEC:
466                                 col= shr->spec;
467                                 break;
468                         case SCE_PASS_SHADOW:
469                                 col= shr->shad;
470                                 break;
471                         case SCE_PASS_AO:
472                                 col= shr->ao;
473                                 break;
474                         case SCE_PASS_REFLECT:
475                                 col= shr->refl;
476                                 break;
477                         case SCE_PASS_REFRACT:
478                                 col= shr->refr;
479                                 break;
480                         case SCE_PASS_RADIO:
481                                 col= NULL; // removed shr->rad;
482                                 break;
483                         case SCE_PASS_NORMAL:
484                                 col= shr->nor;
485                                 break;
486                         case SCE_PASS_UV:
487                                 /* box filter only, gauss will screwup UV too much */
488                                 if(shi->totuv) {
489                                         float mult= (float)count_mask(curmask)/(float)R.osa;
490                                         fp= rpass->rect + 3*offset;
491                                         fp[0]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[0]);
492                                         fp[1]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[1]);
493                                         fp[2]+= mult;
494                                 }
495                                 break;
496                         case SCE_PASS_INDEXOB:
497                                 /* no filter */
498                                 if(shi->vlr) {
499                                         fp= rpass->rect + offset;
500                                         if(*fp==0.0f)
501                                                 *fp= (float)shi->obr->ob->index;
502                                 }
503                                 break;
504                         case SCE_PASS_MIST:
505                                 /*  */
506                                 col= &shr->mist;
507                                 pixsize= 1;
508                                 break;
509                         
510                         case SCE_PASS_VECTOR:
511                         {
512                                 /* add minimum speed in pixel, no filter */
513                                 fp= rpass->rect + 4*offset;
514                                 if( (ABS(shr->winspeed[0]) + ABS(shr->winspeed[1]))< (ABS(fp[0]) + ABS(fp[1])) ) {
515                                         fp[0]= shr->winspeed[0];
516                                         fp[1]= shr->winspeed[1];
517                                 }
518                                 if( (ABS(shr->winspeed[2]) + ABS(shr->winspeed[3]))< (ABS(fp[2]) + ABS(fp[3])) ) {
519                                         fp[2]= shr->winspeed[2];
520                                         fp[3]= shr->winspeed[3];
521                                 }
522                         }
523                                 break;
524
525                         case SCE_PASS_RAYHITS:
526                                 /*  */
527                                 col= shr->rayhits;
528                                 pixsize= 4;
529                                 break;
530                 }
531                 if(col) {
532                         fp= rpass->rect + pixsize*offset;
533                         add_filt_fmask_pixsize(curmask, col, fp, rectx, pixsize);
534                 }
535         }
536 }
537
538 /* non-osa version */
539 static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult *shr)
540 {
541         RenderPass *rpass;
542         float *fp;
543         
544         fp= rl->rectf + 4*offset;
545         QUATCOPY(fp, shr->combined);
546         
547         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
548                 float *col= NULL, uvcol[3];
549                 int a, pixsize= 3;
550                 
551                 switch(rpass->passtype) {
552                         case SCE_PASS_Z:
553                                 fp= rpass->rect + offset;
554                                 *fp= shr->z;
555                                 break;
556                         case SCE_PASS_RGBA:
557                                 col= shr->col;
558                                 pixsize= 4;
559                                 break;
560                         case SCE_PASS_DIFFUSE:
561                                 col= shr->diff;
562                                 break;
563                         case SCE_PASS_SPEC:
564                                 col= shr->spec;
565                                 break;
566                         case SCE_PASS_SHADOW:
567                                 col= shr->shad;
568                                 break;
569                         case SCE_PASS_AO:
570                                 col= shr->ao;
571                                 break;
572                         case SCE_PASS_REFLECT:
573                                 col= shr->refl;
574                                 break;
575                         case SCE_PASS_REFRACT:
576                                 col= shr->refr;
577                                 break;
578                         case SCE_PASS_RADIO:
579                                 col= NULL; // removed shr->rad;
580                                 break;
581                         case SCE_PASS_NORMAL:
582                                 col= shr->nor;
583                                 break;
584                         case SCE_PASS_UV:
585                                 if(shi->totuv) {
586                                         uvcol[0]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[0];
587                                         uvcol[1]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[1];
588                                         uvcol[2]= 1.0f;
589                                         col= uvcol;
590                                 }
591                                 break;
592                         case SCE_PASS_VECTOR:
593                                 col= shr->winspeed;
594                                 pixsize= 4;
595                                 break;
596                         case SCE_PASS_INDEXOB:
597                                 if(shi->vlr) {
598                                         fp= rpass->rect + offset;
599                                         *fp= (float)shi->obr->ob->index;
600                                 }
601                                 break;
602                         case SCE_PASS_MIST:
603                                 fp= rpass->rect + offset;
604                                 *fp= shr->mist;
605                                 break;
606                         case SCE_PASS_RAYHITS:
607                                 col= shr->rayhits;
608                                 pixsize= 4;
609                                 break;
610                 }
611                 if(col) {
612                         fp= rpass->rect + pixsize*offset;
613                         for(a=0; a<pixsize; a++)
614                                 fp[a]= col[a];
615                 }
616         }
617 }
618
619 int get_sample_layers(RenderPart *pa, RenderLayer *rl, RenderLayer **rlpp)
620 {
621         
622         if(pa->fullresult.first) {
623                 int sample, nr= BLI_findindex(&pa->result->layers, rl);
624                 
625                 for(sample=0; sample<R.osa; sample++) {
626                         RenderResult *rr= BLI_findlink(&pa->fullresult, sample);
627                 
628                         rlpp[sample]= BLI_findlink(&rr->layers, nr);
629                 }               
630                 return R.osa;
631         }
632         else {
633                 rlpp[0]= rl;
634                 return 1;
635         }
636 }
637
638
639 /* only do sky, is default in the solid layer (shade_tile) btw */
640 static void sky_tile(RenderPart *pa, RenderLayer *rl)
641 {
642         RenderLayer *rlpp[RE_MAX_OSA];
643         int x, y, od=0, totsample;
644         
645         if(R.r.alphamode!=R_ADDSKY)
646                 return;
647         
648         totsample= get_sample_layers(pa, rl, rlpp);
649         
650         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
651                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od+=4) {
652                         float col[4];
653                         int sample, done= 0;
654                         
655                         for(sample= 0; sample<totsample; sample++) {
656                                 float *pass= rlpp[sample]->rectf + od;
657                                 
658                                 if(pass[3]<1.0f) {
659                                         
660                                         if(done==0) {
661                                                 shadeSkyPixel(col, x, y, pa->thread);
662                                                 done= 1;
663                                         }
664                                         
665                                         if(pass[3]==0.0f) {
666                                                 QUATCOPY(pass, col);
667                                         }
668                                         else {
669                                                 addAlphaUnderFloat(pass, col);
670                                         }
671                                 }
672                         }                       
673                 }
674                 
675                 if(y&1)
676                         if(R.test_break(R.tbh)) break; 
677         }
678 }
679
680 static void atm_tile(RenderPart *pa, RenderLayer *rl)
681 {
682         RenderPass *zpass;
683         GroupObject *go;
684         LampRen *lar;
685         RenderLayer *rlpp[RE_MAX_OSA];
686         int totsample;
687         int x, y, od= 0;
688         
689         totsample= get_sample_layers(pa, rl, rlpp);
690
691         /* check that z pass is enabled */
692         if(pa->rectz==NULL) return;
693         for(zpass= rl->passes.first; zpass; zpass= zpass->next)
694                 if(zpass->passtype==SCE_PASS_Z)
695                         break;
696         
697         if(zpass==NULL) return;
698
699         /* check for at least one sun lamp that its atmosphere flag is is enabled */
700         for(go=R.lights.first; go; go= go->next) {
701                 lar= go->lampren;
702                 if(lar->type==LA_SUN && lar->sunsky && (lar->sunsky->effect_type & LA_SUN_EFFECT_AP))
703                         break;
704         }
705         /* do nothign and return if there is no sun lamp */
706         if(go==NULL)
707                 return;
708         
709         /* for each x,y and each sample, and each sun lamp*/
710         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++) {
711                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, od++) {
712                         int sample;
713                         
714                         for(sample=0; sample<totsample; sample++) {
715                                 float *zrect= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_Z) + od;
716                                 float *rgbrect = rlpp[sample]->rectf + 4*od;
717                                 float rgb[3] = {0};
718                                 int done= 0;
719                                 
720                                 for(go=R.lights.first; go; go= go->next) {
721                                 
722                                         
723                                         lar= go->lampren;
724                                         if(lar->type==LA_SUN && lar->sunsky) {
725                                                 
726                                                 /* if it's sky continue and don't apply atmosphere effect on it */
727                                                 if(*zrect >= 9.9e10 || rgbrect[3]==0.0f) {
728                                                         continue;
729                                                 }
730                                                 
731                                                 if((lar->sunsky->effect_type & LA_SUN_EFFECT_AP)) {     
732                                                         float tmp_rgb[3];
733                                                         
734                                                         VECCOPY(tmp_rgb, rgbrect);
735                                                         if(rgbrect[3]!=1.0f) {  /* de-premul */
736                                                                 float div= 1.0f/rgbrect[3];
737                                                                 VECMUL(tmp_rgb, div);
738                                                         }
739                                                         shadeAtmPixel(lar->sunsky, tmp_rgb, x, y, *zrect);
740                                                         if(rgbrect[3]!=1.0f) {  /* premul */
741                                                                 VECMUL(tmp_rgb, rgbrect[3]);
742                                                         }
743                                                         
744                                                         if(done==0) {
745                                                                 VECCOPY(rgb, tmp_rgb);
746                                                                 done = 1;                                               
747                                                         }
748                                                         else{
749                                                                 rgb[0] = 0.5f*rgb[0] + 0.5f*tmp_rgb[0];
750                                                                 rgb[1] = 0.5f*rgb[1] + 0.5f*tmp_rgb[1];
751                                                                 rgb[2] = 0.5f*rgb[2] + 0.5f*tmp_rgb[2];
752                                                         }
753                                                 }
754                                         }
755                                 }
756
757                                 /* if at least for one sun lamp aerial perspective was applied*/
758                                 if(done) {
759                                         VECCOPY(rgbrect, rgb);
760                                 }
761                         }
762                 }
763         }
764 }
765
766 static void shadeDA_tile(RenderPart *pa, RenderLayer *rl)
767 {
768         RenderResult *rr= pa->result;
769         ShadeSample ssamp;
770         intptr_t *rd, *rectdaps= pa->rectdaps;
771         int samp;
772         int x, y, seed, crop=0, offs=0, od;
773         
774         if(R.test_break(R.tbh)) return; 
775         
776         /* irregular shadowb buffer creation */
777         if(R.r.mode & R_SHADOW)
778                 ISB_create(pa, NULL);
779         
780         /* we set per pixel a fixed seed, for random AO and shadow samples */
781         seed= pa->rectx*pa->disprect.ymin;
782         
783         /* general shader info, passes */
784         shade_sample_initialize(&ssamp, pa, rl);
785
786         /* occlusion caching */
787         if(R.occlusiontree)
788                 cache_occ_samples(&R, pa, &ssamp);
789                 
790         /* filtered render, for now we assume only 1 filter size */
791         if(pa->crop) {
792                 crop= 1;
793                 rectdaps+= pa->rectx + 1;
794                 offs= pa->rectx + 1;
795         }
796         
797         /* scanline updates have to be 2 lines behind */
798         rr->renrect.ymin= 0;
799         rr->renrect.ymax= -2*crop;
800         rr->renlay= rl;
801                                 
802         for(y=pa->disprect.ymin+crop; y<pa->disprect.ymax-crop; y++, rr->renrect.ymax++) {
803                 rd= rectdaps;
804                 od= offs;
805                 
806                 for(x=pa->disprect.xmin+crop; x<pa->disprect.xmax-crop; x++, rd++, od++) {
807                         BLI_thread_srandom(pa->thread, seed++);
808                         
809                         if(*rd) {
810                                 if(shade_samples(&ssamp, (PixStr *)(*rd), x, y)) {
811                                         
812                                         /* multisample buffers or filtered mask filling? */
813                                         if(pa->fullresult.first) {
814                                                 int a;
815                                                 for(samp=0; samp<ssamp.tot; samp++) {
816                                                         int smask= ssamp.shi[samp].mask;
817                                                         for(a=0; a<R.osa; a++) {
818                                                                 int mask= 1<<a;
819                                                                 if(smask & mask)
820                                                                         add_passes(ssamp.rlpp[a], od, &ssamp.shi[samp], &ssamp.shr[samp]);
821                                                         }
822                                                 }
823                                         }
824                                         else {
825                                                 for(samp=0; samp<ssamp.tot; samp++)
826                                                         add_filt_passes(rl, ssamp.shi[samp].mask, pa->rectx, od, &ssamp.shi[samp], &ssamp.shr[samp]);
827                                         }
828                                 }
829                         }
830                 }
831                 
832                 rectdaps+= pa->rectx;
833                 offs+= pa->rectx;
834                 
835                 if(y&1) if(R.test_break(R.tbh)) break; 
836         }
837         
838         /* disable scanline updating */
839         rr->renlay= NULL;
840         
841         if(R.r.mode & R_SHADOW)
842                 ISB_free(pa);
843
844         if(R.occlusiontree)
845                 free_occ_samples(&R, pa);
846 }
847
848 /* ************* pixel struct ******** */
849
850
851 static PixStrMain *addpsmain(ListBase *lb)
852 {
853         PixStrMain *psm;
854         
855         psm= (PixStrMain *)MEM_mallocN(sizeof(PixStrMain),"pixstrMain");
856         BLI_addtail(lb, psm);
857         
858         psm->ps= (PixStr *)MEM_mallocN(4096*sizeof(PixStr),"pixstr");
859         psm->counter= 0;
860         
861         return psm;
862 }
863
864 static void freeps(ListBase *lb)
865 {
866         PixStrMain *psm, *psmnext;
867         
868         for(psm= lb->first; psm; psm= psmnext) {
869                 psmnext= psm->next;
870                 if(psm->ps)
871                         MEM_freeN(psm->ps);
872                 MEM_freeN(psm);
873         }
874         lb->first= lb->last= NULL;
875 }
876
877 static void addps(ListBase *lb, intptr_t *rd, int obi, int facenr, int z, int maskz, unsigned short mask)
878 {
879         PixStrMain *psm;
880         PixStr *ps, *last= NULL;
881         
882         if(*rd) {       
883                 ps= (PixStr *)(*rd);
884                 
885                 while(ps) {
886                         if( ps->obi == obi && ps->facenr == facenr ) {
887                                 ps->mask |= mask;
888                                 return;
889                         }
890                         last= ps;
891                         ps= ps->next;
892                 }
893         }
894         
895         /* make new PS (pixel struct) */
896         psm= lb->last;
897         
898         if(psm->counter==4095)
899                 psm= addpsmain(lb);
900         
901         ps= psm->ps + psm->counter++;
902         
903         if(last) last->next= ps;
904         else *rd= (intptr_t)ps;
905         
906         ps->next= NULL;
907         ps->obi= obi;
908         ps->facenr= facenr;
909         ps->z= z;
910         ps->maskz= maskz;
911         ps->mask = mask;
912         ps->shadfac= 0;
913 }
914
915 static void edge_enhance_add(RenderPart *pa, float *rectf, float *arect)
916 {
917         float addcol[4];
918         int pix;
919         
920         if(arect==NULL)
921                 return;
922         
923         for(pix= pa->rectx*pa->recty; pix>0; pix--, arect++, rectf+=4) {
924                 if(*arect != 0.0f) {
925                         addcol[0]= *arect * R.r.edgeR;
926                         addcol[1]= *arect * R.r.edgeG;
927                         addcol[2]= *arect * R.r.edgeB;
928                         addcol[3]= *arect;
929                         addAlphaOverFloat(rectf, addcol);
930                 }
931         }
932 }
933
934 static void convert_to_key_alpha(RenderPart *pa, RenderLayer *rl)
935 {
936         RenderLayer *rlpp[RE_MAX_OSA];
937         int y, sample, totsample;
938         
939         totsample= get_sample_layers(pa, rl, rlpp);
940         
941         for(sample= 0; sample<totsample; sample++) {
942                 float *rectf= rlpp[sample]->rectf;
943                 
944                 for(y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
945                         if(rectf[3] >= 1.0f);
946                         else if(rectf[3] > 0.0f) {
947                                 rectf[0] /= rectf[3];
948                                 rectf[1] /= rectf[3];
949                                 rectf[2] /= rectf[3];
950                         }
951                 }
952         }
953 }
954
955 /* adds only alpha values */
956 void edge_enhance_tile(RenderPart *pa, float *rectf, int *rectz)
957 {
958         /* use zbuffer to define edges, add it to the image */
959         int y, x, col, *rz, *rz1, *rz2, *rz3;
960         int zval1, zval2, zval3;
961         float *rf;
962         
963         /* shift values in zbuffer 4 to the right (anti overflows), for filter we need multiplying with 12 max */
964         rz= rectz;
965         if(rz==NULL) return;
966         
967         for(y=0; y<pa->recty; y++)
968                 for(x=0; x<pa->rectx; x++, rz++) (*rz)>>= 4;
969         
970         rz1= rectz;
971         rz2= rz1+pa->rectx;
972         rz3= rz2+pa->rectx;
973         
974         rf= rectf+pa->rectx+1;
975         
976         for(y=0; y<pa->recty-2; y++) {
977                 for(x=0; x<pa->rectx-2; x++, rz1++, rz2++, rz3++, rf++) {
978                         
979                         /* prevent overflow with sky z values */
980                         zval1=   rz1[0] + 2*rz1[1] +   rz1[2];
981                         zval2=  2*rz2[0]           + 2*rz2[2];
982                         zval3=   rz3[0] + 2*rz3[1] +   rz3[2];
983                         
984                         col= ( 4*rz2[1] - (zval1 + zval2 + zval3)/3 );
985                         if(col<0) col= -col;
986                         
987                         col >>= 5;
988                         if(col > (1<<16)) col= (1<<16);
989                         else col= (R.r.edgeint*col)>>8;
990                         
991                         if(col>0) {
992                                 float fcol;
993                                 
994                                 if(col>255) fcol= 1.0f;
995                                 else fcol= (float)col/255.0f;
996                                 
997                                 if(R.osa)
998                                         *rf+= fcol/(float)R.osa;
999                                 else
1000                                         *rf= fcol;
1001                         }
1002                 }
1003                 rz1+= 2;
1004                 rz2+= 2;
1005                 rz3+= 2;
1006                 rf+= 2;
1007         }
1008         
1009         /* shift back zbuf values, we might need it still */
1010         rz= rectz;
1011         for(y=0; y<pa->recty; y++)
1012                 for(x=0; x<pa->rectx; x++, rz++) (*rz)<<= 4;
1013         
1014 }
1015
1016 static void reset_sky_speed(RenderPart *pa, RenderLayer *rl)
1017 {
1018         /* for all pixels with max speed, set to zero */
1019     RenderLayer *rlpp[RE_MAX_OSA];
1020         float *fp;
1021         int a, sample, totsample;
1022         
1023         totsample= get_sample_layers(pa, rl, rlpp);
1024
1025         for(sample= 0; sample<totsample; sample++) {
1026                 fp= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_VECTOR);
1027                 if(fp==NULL) break;
1028
1029                 for(a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
1030                         if(fp[a] == PASS_VECTOR_MAX) fp[a]= 0.0f;
1031         }
1032 }
1033
1034 static unsigned short *make_solid_mask(RenderPart *pa)
1035
1036         intptr_t *rd= pa->rectdaps;
1037         unsigned short *solidmask, *sp;
1038         int x;
1039         
1040         if(rd==NULL) return NULL;
1041         
1042         sp=solidmask= MEM_mallocN(sizeof(short)*pa->rectx*pa->recty, "solidmask");
1043         
1044         for(x=pa->rectx*pa->recty; x>0; x--, rd++, sp++) {
1045                 if(*rd) {
1046                         PixStr *ps= (PixStr *)*rd;
1047                         
1048                         *sp= ps->mask;
1049                         for(ps= ps->next; ps; ps= ps->next)
1050                                 *sp |= ps->mask;
1051                 }
1052                 else
1053                         *sp= 0;
1054         }
1055                         
1056         return solidmask;
1057 }
1058
1059 static void addAlphaOverFloatMask(float *dest, float *source, unsigned short dmask, unsigned short smask)
1060 {
1061         unsigned short shared= dmask & smask;
1062         float mul= 1.0 - source[3];
1063         
1064         if(shared) {    /* overlapping masks */
1065                 
1066                 /* masks differ, we make a mixture of 'add' and 'over' */
1067                 if(shared!=dmask) {
1068                         float shared_bits= (float)count_mask(shared);           /* alpha over */
1069                         float tot_bits= (float)count_mask(smask|dmask);         /* alpha add */
1070                         
1071                         float add= (tot_bits - shared_bits)/tot_bits;           /* add level */
1072                         mul= add + (1.0f-add)*mul;
1073                 }
1074         }
1075         else if(dmask && smask) {
1076                 /* works for premul only, of course */
1077                 dest[0]+= source[0];
1078                 dest[1]+= source[1];
1079                 dest[2]+= source[2];
1080                 dest[3]+= source[3];
1081                 
1082                 return;
1083         }
1084
1085         dest[0]= (mul*dest[0]) + source[0];
1086         dest[1]= (mul*dest[1]) + source[1];
1087         dest[2]= (mul*dest[2]) + source[2];
1088         dest[3]= (mul*dest[3]) + source[3];
1089 }
1090
1091 typedef struct ZbufSolidData {
1092         RenderLayer *rl;
1093         ListBase *psmlist;
1094         float *edgerect;
1095 } ZbufSolidData;
1096
1097 void make_pixelstructs(RenderPart *pa, ZSpan *zspan, int sample, void *data)
1098 {
1099         ZbufSolidData *sdata= (ZbufSolidData*)data;
1100         ListBase *lb= sdata->psmlist;
1101         intptr_t *rd= pa->rectdaps;
1102         int *ro= zspan->recto;
1103         int *rp= zspan->rectp;
1104         int *rz= zspan->rectz;
1105         int *rm= zspan->rectmask;
1106         int x, y;
1107         int mask= 1<<sample;
1108
1109         for(y=0; y<pa->recty; y++) {
1110                 for(x=0; x<pa->rectx; x++, rd++, rp++, ro++, rz++, rm++) {
1111                         if(*rp) {
1112                                 addps(lb, rd, *ro, *rp, *rz, (zspan->rectmask)? *rm: 0, mask);
1113                         }
1114                 }
1115         }
1116
1117         if(sdata->rl->layflag & SCE_LAY_EDGE) 
1118                 if(R.r.mode & R_EDGE) 
1119                         edge_enhance_tile(pa, sdata->edgerect, zspan->rectz);
1120 }
1121
1122 /* main call for shading Delta Accum, for OSA */
1123 /* supposed to be fully threadable! */
1124 void zbufshadeDA_tile(RenderPart *pa)
1125 {
1126         RenderResult *rr= pa->result;
1127         RenderLayer *rl;
1128         ListBase psmlist= {NULL, NULL};
1129         float *edgerect= NULL;
1130         
1131         /* allocate the necessary buffers */
1132                                 /* zbuffer inits these rects */
1133         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1134         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1135         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1136         for(rl= rr->layers.first; rl; rl= rl->next) {
1137                 if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
1138                         pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
1139         
1140                 /* initialize pixelstructs and edge buffer */
1141                 addpsmain(&psmlist);
1142                 pa->rectdaps= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "zbufDArectd");
1143                 
1144                 if(rl->layflag & SCE_LAY_EDGE) 
1145                         if(R.r.mode & R_EDGE) 
1146                                 edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
1147                 
1148                 /* always fill visibility */
1149                 for(pa->sample=0; pa->sample<R.osa; pa->sample+=4) {
1150                         ZbufSolidData sdata;
1151
1152                         sdata.rl= rl;
1153                         sdata.psmlist= &psmlist;
1154                         sdata.edgerect= edgerect;
1155                         zbuffer_solid(pa, rl, make_pixelstructs, &sdata);
1156                         if(R.test_break(R.tbh)) break; 
1157                 }
1158                 
1159                 /* shades solid */
1160                 if(rl->layflag & SCE_LAY_SOLID) 
1161                         shadeDA_tile(pa, rl);
1162                 
1163                 /* lamphalo after solid, before ztra, looks nicest because ztra does own halo */
1164                 if(R.flag & R_LAMPHALO)
1165                         if(rl->layflag & SCE_LAY_HALO)
1166                                 lamphalo_tile(pa, rl);
1167                 
1168                 /* halo before ztra, because ztra fills in zbuffer now */
1169                 if(R.flag & R_HALO)
1170                         if(rl->layflag & SCE_LAY_HALO)
1171                                 halo_tile(pa, rl);
1172
1173                 /* transp layer */
1174                 if(R.flag & R_ZTRA || R.totstrand) {
1175                         if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
1176                                 if(pa->fullresult.first) {
1177                                         zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
1178                                 }
1179                                 else {
1180                                         unsigned short *ztramask, *solidmask= NULL; /* 16 bits, MAX_OSA */
1181                                         
1182                                         /* allocate, but not free here, for asynchronous display of this rect in main thread */
1183                                         rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
1184                                         
1185                                         /* swap for live updates, and it is used in zbuf.c!!! */
1186                                         SWAP(float *, rl->acolrect, rl->rectf);
1187                                         ztramask= zbuffer_transp_shade(pa, rl, rl->rectf, &psmlist);
1188                                         SWAP(float *, rl->acolrect, rl->rectf);
1189                                         
1190                                         /* zbuffer transp only returns ztramask if there's solid rendered */
1191                                         if(ztramask)
1192                                                 solidmask= make_solid_mask(pa);
1193
1194                                         if(ztramask && solidmask) {
1195                                                 unsigned short *sps= solidmask, *spz= ztramask;
1196                                                 unsigned short fullmask= (1<<R.osa)-1;
1197                                                 float *fcol= rl->rectf; float *acol= rl->acolrect;
1198                                                 int x;
1199                                                 
1200                                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4, sps++, spz++) {
1201                                                         if(*sps == fullmask)
1202                                                                 addAlphaOverFloat(fcol, acol);
1203                                                         else
1204                                                                 addAlphaOverFloatMask(fcol, acol, *sps, *spz);
1205                                                 }
1206                                         }
1207                                         else {
1208                                                 float *fcol= rl->rectf; float *acol= rl->acolrect;
1209                                                 int x;
1210                                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
1211                                                         addAlphaOverFloat(fcol, acol);
1212                                                 }
1213                                         }
1214                                         if(solidmask) MEM_freeN(solidmask);
1215                                         if(ztramask) MEM_freeN(ztramask);
1216                                 }
1217                         }
1218                 }
1219
1220                 /* sun/sky */
1221                 if(rl->layflag & SCE_LAY_SKY)
1222                         atm_tile(pa, rl);
1223                 
1224                 /* sky before edge */
1225                 if(rl->layflag & SCE_LAY_SKY)
1226                         sky_tile(pa, rl);
1227
1228                 /* extra layers */
1229                 if(rl->layflag & SCE_LAY_EDGE) 
1230                         if(R.r.mode & R_EDGE) 
1231                                 edge_enhance_add(pa, rl->rectf, edgerect);
1232                 
1233                 if(rl->passflag & SCE_PASS_VECTOR)
1234                         reset_sky_speed(pa, rl);
1235                 
1236                 /* de-premul alpha */
1237                 if(R.r.alphamode & R_ALPHAKEY)
1238                         convert_to_key_alpha(pa, rl);
1239                 
1240                 /* free stuff within loop! */
1241                 MEM_freeN(pa->rectdaps); pa->rectdaps= NULL;
1242                 freeps(&psmlist);
1243                 
1244                 if(edgerect) MEM_freeN(edgerect);
1245                 edgerect= NULL;
1246
1247                 if(pa->rectmask) {
1248                         MEM_freeN(pa->rectmask);
1249                         pa->rectmask= NULL;
1250                 }
1251         }
1252         
1253         /* free all */
1254         MEM_freeN(pa->recto); pa->recto= NULL;
1255         MEM_freeN(pa->rectp); pa->rectp= NULL;
1256         MEM_freeN(pa->rectz); pa->rectz= NULL;
1257         
1258         /* display active layer */
1259         rr->renrect.ymin=rr->renrect.ymax= 0;
1260         rr->renlay= render_get_active_layer(&R, rr);
1261 }
1262
1263
1264 /* ------------------------------------------------------------------------ */
1265
1266 /* non OSA case, full tile render */
1267 /* supposed to be fully threadable! */
1268 void zbufshade_tile(RenderPart *pa)
1269 {
1270         ShadeSample ssamp;
1271         RenderResult *rr= pa->result;
1272         RenderLayer *rl;
1273         PixStr ps;
1274         float *edgerect= NULL;
1275         
1276         /* fake pixel struct, to comply to osa render */
1277         ps.next= NULL;
1278         ps.mask= 0xFFFF;
1279         
1280         /* zbuffer code clears/inits rects */
1281         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1282         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1283         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1284
1285         for(rl= rr->layers.first; rl; rl= rl->next) {
1286                 if((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
1287                         pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
1288
1289                 /* general shader info, passes */
1290                 shade_sample_initialize(&ssamp, pa, rl);
1291                 
1292                 zbuffer_solid(pa, rl, NULL, NULL);
1293                 
1294                 if(!R.test_break(R.tbh)) {      /* NOTE: this if() is not consistent */
1295                         
1296                         /* edges only for solid part, ztransp doesn't support it yet anti-aliased */
1297                         if(rl->layflag & SCE_LAY_EDGE) {
1298                                 if(R.r.mode & R_EDGE) {
1299                                         edgerect= MEM_callocN(sizeof(float)*pa->rectx*pa->recty, "rectedge");
1300                                         edge_enhance_tile(pa, edgerect, pa->rectz);
1301                                 }
1302                         }
1303                         
1304                         /* initialize scanline updates for main thread */
1305                         rr->renrect.ymin= 0;
1306                         rr->renlay= rl;
1307                         
1308                         if(rl->layflag & SCE_LAY_SOLID) {
1309                                 float *fcol= rl->rectf;
1310                                 int *ro= pa->recto, *rp= pa->rectp, *rz= pa->rectz;
1311                                 int x, y, offs=0, seed;
1312                                 
1313                                 /* we set per pixel a fixed seed, for random AO and shadow samples */
1314                                 seed= pa->rectx*pa->disprect.ymin;
1315                                 
1316                                 /* irregular shadowb buffer creation */
1317                                 if(R.r.mode & R_SHADOW)
1318                                         ISB_create(pa, NULL);
1319
1320                                 if(R.occlusiontree)
1321                                         cache_occ_samples(&R, pa, &ssamp);
1322                                 
1323                                 for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
1324                                         for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, ro++, rz++, rp++, fcol+=4, offs++) {
1325                                                 /* per pixel fixed seed */
1326                                                 BLI_thread_srandom(pa->thread, seed++);
1327                                                 
1328                                                 if(*rp) {
1329                                                         ps.obi= *ro;
1330                                                         ps.facenr= *rp;
1331                                                         ps.z= *rz;
1332                                                         if(shade_samples(&ssamp, &ps, x, y)) {
1333                                                                 /* combined and passes */
1334                                                                 add_passes(rl, offs, ssamp.shi, ssamp.shr);
1335                                                         }
1336                                                 }
1337                                         }
1338                                         if(y&1)
1339                                                 if(R.test_break(R.tbh)) break; 
1340                                 }
1341                                 
1342                                 if(R.occlusiontree)
1343                                         free_occ_samples(&R, pa);
1344                                 
1345                                 if(R.r.mode & R_SHADOW)
1346                                         ISB_free(pa);
1347                         }
1348                         
1349                         /* disable scanline updating */
1350                         rr->renlay= NULL;
1351                 }
1352                 
1353                 /* lamphalo after solid, before ztra, looks nicest because ztra does own halo */
1354                 if(R.flag & R_LAMPHALO)
1355                         if(rl->layflag & SCE_LAY_HALO)
1356                                 lamphalo_tile(pa, rl);
1357                 
1358                 /* halo before ztra, because ztra fills in zbuffer now */
1359                 if(R.flag & R_HALO)
1360                         if(rl->layflag & SCE_LAY_HALO)
1361                                 halo_tile(pa, rl);
1362                 
1363                 if(R.flag & R_ZTRA || R.totstrand) {
1364                         if(rl->layflag & (SCE_LAY_ZTRA|SCE_LAY_STRAND)) {
1365                                 float *fcol, *acol;
1366                                 int x;
1367                                 
1368                                 /* allocate, but not free here, for asynchronous display of this rect in main thread */
1369                                 rl->acolrect= MEM_callocN(4*sizeof(float)*pa->rectx*pa->recty, "alpha layer");
1370                                 
1371                                 /* swap for live updates */
1372                                 SWAP(float *, rl->acolrect, rl->rectf);
1373                                 zbuffer_transp_shade(pa, rl, rl->rectf, NULL);
1374                                 SWAP(float *, rl->acolrect, rl->rectf);
1375                                 
1376                                 fcol= rl->rectf; acol= rl->acolrect;
1377                                 for(x=pa->rectx*pa->recty; x>0; x--, acol+=4, fcol+=4) {
1378                                         addAlphaOverFloat(fcol, acol);
1379                                 }
1380                         }
1381                 }
1382                 
1383                 /* sun/sky */
1384                 if(rl->layflag & SCE_LAY_SKY)
1385                         atm_tile(pa, rl);
1386                 
1387                 /* sky before edge */
1388                 if(rl->layflag & SCE_LAY_SKY)
1389                         sky_tile(pa, rl);
1390                 
1391                 if(!R.test_break(R.tbh)) {
1392                         if(rl->layflag & SCE_LAY_EDGE) 
1393                                 if(R.r.mode & R_EDGE)
1394                                         edge_enhance_add(pa, rl->rectf, edgerect);
1395                 }
1396                 
1397                 if(rl->passflag & SCE_PASS_VECTOR)
1398                         reset_sky_speed(pa, rl);
1399                 
1400                 /* de-premul alpha */
1401                 if(R.r.alphamode & R_ALPHAKEY)
1402                         convert_to_key_alpha(pa, rl);
1403                 
1404                 if(edgerect) MEM_freeN(edgerect);
1405                 edgerect= NULL;
1406
1407                 if(pa->rectmask) {
1408                         MEM_freeN(pa->rectmask);
1409                         pa->rectmask= NULL;
1410                 }
1411         }
1412
1413         /* display active layer */
1414         rr->renrect.ymin=rr->renrect.ymax= 0;
1415         rr->renlay= render_get_active_layer(&R, rr);
1416         
1417         MEM_freeN(pa->recto); pa->recto= NULL;
1418         MEM_freeN(pa->rectp); pa->rectp= NULL;
1419         MEM_freeN(pa->rectz); pa->rectz= NULL;
1420 }
1421
1422 /* SSS preprocess tile render, fully threadable */
1423 typedef struct ZBufSSSHandle {
1424         RenderPart *pa;
1425         ListBase psmlist;
1426         int totps;
1427 } ZBufSSSHandle;
1428
1429 static void addps_sss(void *cb_handle, int obi, int facenr, int x, int y, int z)
1430 {
1431         ZBufSSSHandle *handle = cb_handle;
1432         RenderPart *pa= handle->pa;
1433
1434         /* extra border for filter gives double samples on part edges,
1435            don't use those */
1436         if(x<pa->crop || x>=pa->rectx-pa->crop)
1437                 return;
1438         if(y<pa->crop || y>=pa->recty-pa->crop)
1439                 return;
1440         
1441         if(pa->rectall) {
1442                 intptr_t *rs= pa->rectall + pa->rectx*y + x;
1443
1444                 addps(&handle->psmlist, rs, obi, facenr, z, 0, 0);
1445                 handle->totps++;
1446         }
1447         if(pa->rectz) {
1448                 int *rz= pa->rectz + pa->rectx*y + x;
1449                 int *rp= pa->rectp + pa->rectx*y + x;
1450                 int *ro= pa->recto + pa->rectx*y + x;
1451
1452                 if(z < *rz) {
1453                         if(*rp == 0)
1454                                 handle->totps++;
1455                         *rz= z;
1456                         *rp= facenr;
1457                         *ro= obi;
1458                 }
1459         }
1460         if(pa->rectbackz) {
1461                 int *rz= pa->rectbackz + pa->rectx*y + x;
1462                 int *rp= pa->rectbackp + pa->rectx*y + x;
1463                 int *ro= pa->rectbacko + pa->rectx*y + x;
1464
1465                 if(z >= *rz) {
1466                         if(*rp == 0)
1467                                 handle->totps++;
1468                         *rz= z;
1469                         *rp= facenr;
1470                         *ro= obi;
1471                 }
1472         }
1473 }
1474
1475 static void shade_sample_sss(ShadeSample *ssamp, Material *mat, ObjectInstanceRen *obi, VlakRen *vlr, int quad, float x, float y, float z, float *co, float *color, float *area)
1476 {
1477         ShadeInput *shi= ssamp->shi;
1478         ShadeResult shr;
1479         float texfac, orthoarea, nor[3], alpha, sx, sy;
1480
1481         /* cache for shadow */
1482         shi->samplenr= R.shadowsamplenr[shi->thread]++;
1483         
1484         if(quad) 
1485                 shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
1486         else
1487                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
1488
1489         /* center pixel */
1490         sx = x + 0.5f;
1491         sy = y + 0.5f;
1492
1493         /* we estimate the area here using shi->dxco and shi->dyco. we need to
1494            enabled shi->osatex these are filled. we compute two areas, one with
1495            the normal pointed at the camera and one with the original normal, and
1496            then clamp to avoid a too large contribution from a single pixel */
1497         shi->osatex= 1;
1498
1499         VECCOPY(nor, shi->facenor);
1500         calc_view_vector(shi->facenor, sx, sy);
1501         normalize_v3(shi->facenor);
1502         shade_input_set_viewco(shi, x, y, sx, sy, z);
1503         orthoarea= len_v3(shi->dxco)*len_v3(shi->dyco);
1504
1505         VECCOPY(shi->facenor, nor);
1506         shade_input_set_viewco(shi, x, y, sx, sy, z);
1507         *area= len_v3(shi->dxco)*len_v3(shi->dyco);
1508         *area= MIN2(*area, 2.0f*orthoarea);
1509
1510         shade_input_set_uv(shi);
1511         shade_input_set_normals(shi);
1512
1513         /* we don't want flipped normals, they screw up back scattering */
1514         if(shi->flippednor)
1515                 shade_input_flip_normals(shi);
1516
1517         /* not a pretty solution, but fixes common cases */
1518         if(shi->obr->ob && shi->obr->ob->transflag & OB_NEG_SCALE) {
1519                 negate_v3(shi->vn);
1520                 negate_v3(shi->vno);
1521         }
1522
1523         /* if nodetree, use the material that we are currently preprocessing
1524            instead of the node material */
1525         if(shi->mat->nodetree && shi->mat->use_nodes)
1526                 shi->mat= mat;
1527
1528         /* init material vars */
1529         shade_input_init_material(shi);
1530         
1531         /* render */
1532         shade_input_set_shade_texco(shi);
1533         
1534         shade_samples_do_AO(ssamp);
1535         shade_material_loop(shi, &shr);
1536         
1537         VECCOPY(co, shi->co);
1538         VECCOPY(color, shr.combined);
1539
1540         /* texture blending */
1541         texfac= shi->mat->sss_texfac;
1542
1543         alpha= shr.combined[3];
1544         *area *= alpha;
1545 }
1546
1547 static void zbufshade_sss_free(RenderPart *pa)
1548 {
1549 #if 0
1550         MEM_freeN(pa->rectall); pa->rectall= NULL;
1551         freeps(&handle.psmlist);
1552 #else
1553         MEM_freeN(pa->rectz); pa->rectz= NULL;
1554         MEM_freeN(pa->rectp); pa->rectp= NULL;
1555         MEM_freeN(pa->recto); pa->recto= NULL;
1556         MEM_freeN(pa->rectbackz); pa->rectbackz= NULL;
1557         MEM_freeN(pa->rectbackp); pa->rectbackp= NULL;
1558         MEM_freeN(pa->rectbacko); pa->rectbacko= NULL;
1559 #endif
1560 }
1561
1562 void zbufshade_sss_tile(RenderPart *pa)
1563 {
1564         Render *re= &R;
1565         ShadeSample ssamp;
1566         ZBufSSSHandle handle;
1567         RenderResult *rr= pa->result;
1568         RenderLayer *rl;
1569         VlakRen *vlr;
1570         Material *mat= re->sss_mat;
1571         float (*co)[3], (*color)[3], *area, *fcol;
1572         int x, y, seed, quad, totpoint, display = !(re->r.scemode & R_PREVIEWBUTS);
1573         int *ro, *rz, *rp, *rbo, *rbz, *rbp, lay;
1574 #if 0
1575         PixStr *ps;
1576         intptr_t *rs;
1577         int z;
1578 #endif
1579
1580         /* setup pixelstr list and buffer for zbuffering */
1581         handle.pa= pa;
1582         handle.totps= 0;
1583
1584 #if 0
1585         handle.psmlist.first= handle.psmlist.last= NULL;
1586         addpsmain(&handle.psmlist);
1587
1588         pa->rectall= MEM_callocN(sizeof(intptr_t)*pa->rectx*pa->recty+4, "rectall");
1589 #else
1590         pa->recto= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "recto");
1591         pa->rectp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectp");
1592         pa->rectz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectz");
1593         pa->rectbacko= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbacko");
1594         pa->rectbackp= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackp");
1595         pa->rectbackz= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectbackz");
1596 #endif
1597
1598         /* setup shade sample with correct passes */
1599         memset(&ssamp, 0, sizeof(ssamp));
1600         shade_sample_initialize(&ssamp, pa, rr->layers.first);
1601         ssamp.tot= 1;
1602         
1603         for(rl=rr->layers.first; rl; rl=rl->next) {
1604                 ssamp.shi[0].lay |= rl->lay;
1605                 ssamp.shi[0].layflag |= rl->layflag;
1606                 ssamp.shi[0].passflag |= rl->passflag;
1607                 ssamp.shi[0].combinedflag |= ~rl->pass_xor;
1608         }
1609
1610         rl= rr->layers.first;
1611         ssamp.shi[0].passflag |= SCE_PASS_RGBA|SCE_PASS_COMBINED;
1612         ssamp.shi[0].combinedflag &= ~(SCE_PASS_SPEC);
1613         ssamp.shi[0].mat_override= NULL;
1614         ssamp.shi[0].light_override= NULL;
1615         lay= ssamp.shi[0].lay;
1616
1617         /* create the pixelstrs to be used later */
1618         zbuffer_sss(pa, lay, &handle, addps_sss);
1619
1620         if(handle.totps==0) {
1621                 zbufshade_sss_free(pa);
1622                 return;
1623         }
1624         
1625         fcol= rl->rectf;
1626
1627         co= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSCo");
1628         color= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSColor");
1629         area= MEM_mallocN(sizeof(float)*handle.totps, "SSSArea");
1630
1631 #if 0
1632         /* create ISB (does not work currently!) */
1633         if(re->r.mode & R_SHADOW)
1634                 ISB_create(pa, NULL);
1635 #endif
1636
1637         if(display) {
1638                 /* initialize scanline updates for main thread */
1639                 rr->renrect.ymin= 0;
1640                 rr->renlay= rl;
1641         }
1642         
1643         seed= pa->rectx*pa->disprect.ymin;
1644 #if 0
1645         rs= pa->rectall;
1646 #else
1647         rz= pa->rectz;
1648         rp= pa->rectp;
1649         ro= pa->recto;
1650         rbz= pa->rectbackz;
1651         rbp= pa->rectbackp;
1652         rbo= pa->rectbacko;
1653 #endif
1654         totpoint= 0;
1655
1656         for(y=pa->disprect.ymin; y<pa->disprect.ymax; y++, rr->renrect.ymax++) {
1657                 for(x=pa->disprect.xmin; x<pa->disprect.xmax; x++, fcol+=4) {
1658                         /* per pixel fixed seed */
1659                         BLI_thread_srandom(pa->thread, seed++);
1660                         
1661 #if 0
1662                         if(rs) {
1663                                 /* for each sample in this pixel, shade it */
1664                                 for(ps=(PixStr*)*rs; ps; ps=ps->next) {
1665                                         ObjectInstanceRen *obi= &re->objectinstance[ps->obi];
1666                                         ObjectRen *obr= obi->obr;
1667                                         vlr= RE_findOrAddVlak(obr, (ps->facenr-1) & RE_QUAD_MASK);
1668                                         quad= (ps->facenr & RE_QUAD_OFFS);
1669                                         z= ps->z;
1670
1671                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, z,
1672                                                 co[totpoint], color[totpoint], &area[totpoint]);
1673
1674                                         totpoint++;
1675
1676                                         VECADD(fcol, fcol, color);
1677                                         fcol[3]= 1.0f;
1678                                 }
1679
1680                                 rs++;
1681                         }
1682 #else
1683                         if(rp) {
1684                                 if(*rp != 0) {
1685                                         ObjectInstanceRen *obi= &re->objectinstance[*ro];
1686                                         ObjectRen *obr= obi->obr;
1687
1688                                         /* shade front */
1689                                         vlr= RE_findOrAddVlak(obr, (*rp-1) & RE_QUAD_MASK);
1690                                         quad= ((*rp) & RE_QUAD_OFFS);
1691
1692                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, *rz,
1693                                                 co[totpoint], color[totpoint], &area[totpoint]);
1694                                         
1695                                         VECADD(fcol, fcol, color[totpoint]);
1696                                         fcol[3]= 1.0f;
1697                                         totpoint++;
1698                                 }
1699
1700                                 rp++; rz++; ro++;
1701                         }
1702
1703                         if(rbp) {
1704                                 if(*rbp != 0 && !(*rbp == *(rp-1) && *rbo == *(ro-1))) {
1705                                         ObjectInstanceRen *obi= &re->objectinstance[*rbo];
1706                                         ObjectRen *obr= obi->obr;
1707
1708                                         /* shade back */
1709                                         vlr= RE_findOrAddVlak(obr, (*rbp-1) & RE_QUAD_MASK);
1710                                         quad= ((*rbp) & RE_QUAD_OFFS);
1711
1712                                         shade_sample_sss(&ssamp, mat, obi, vlr, quad, x, y, *rbz,
1713                                                 co[totpoint], color[totpoint], &area[totpoint]);
1714                                         
1715                                         /* to indicate this is a back sample */
1716                                         area[totpoint]= -area[totpoint];
1717
1718                                         VECADD(fcol, fcol, color[totpoint]);
1719                                         fcol[3]= 1.0f;
1720                                         totpoint++;
1721                                 }
1722
1723                                 rbz++; rbp++; rbo++;
1724                         }
1725 #endif
1726                 }
1727
1728                 if(y&1)
1729                         if(re->test_break(re->tbh)) break; 
1730         }
1731
1732         /* note: after adding we do not free these arrays, sss keeps them */
1733         if(totpoint > 0) {
1734                 sss_add_points(re, co, color, area, totpoint);
1735         }
1736         else {
1737                 MEM_freeN(co);
1738                 MEM_freeN(color);
1739                 MEM_freeN(area);
1740         }
1741         
1742 #if 0
1743         if(re->r.mode & R_SHADOW)
1744                 ISB_free(pa);
1745 #endif
1746                 
1747         if(display) {
1748                 /* display active layer */
1749                 rr->renrect.ymin=rr->renrect.ymax= 0;
1750                 rr->renlay= render_get_active_layer(&R, rr);
1751         }
1752         
1753         zbufshade_sss_free(pa);
1754 }
1755
1756 /* ------------------------------------------------------------------------ */
1757
1758 static void renderhalo_post(RenderResult *rr, float *rectf, HaloRen *har)       /* postprocess version */
1759 {
1760         float dist, xsq, ysq, xn, yn, colf[4], *rectft, *rtf;
1761         float haloxs, haloys;
1762         int minx, maxx, miny, maxy, x, y;
1763
1764         /* calculate the disprect mapped coordinate for halo. note: rectx is disprect corrected */
1765         haloxs= har->xs - R.disprect.xmin;
1766         haloys= har->ys - R.disprect.ymin;
1767         
1768         har->miny= miny= haloys - har->rad/R.ycor;
1769         har->maxy= maxy= haloys + har->rad/R.ycor;
1770         
1771         if(maxy<0);
1772         else if(rr->recty<miny);
1773         else {
1774                 minx= floor(haloxs-har->rad);
1775                 maxx= ceil(haloxs+har->rad);
1776                         
1777                 if(maxx<0);
1778                 else if(rr->rectx<minx);
1779                 else {
1780                 
1781                         if(minx<0) minx= 0;
1782                         if(maxx>=rr->rectx) maxx= rr->rectx-1;
1783                         if(miny<0) miny= 0;
1784                         if(maxy>rr->recty) maxy= rr->recty;
1785         
1786                         rectft= rectf+ 4*rr->rectx*miny;
1787
1788                         for(y=miny; y<maxy; y++) {
1789         
1790                                 rtf= rectft+4*minx;
1791                                 
1792                                 yn= (y - haloys)*R.ycor;
1793                                 ysq= yn*yn;
1794                                 
1795                                 for(x=minx; x<=maxx; x++) {
1796                                         xn= x - haloxs;
1797                                         xsq= xn*xn;
1798                                         dist= xsq+ysq;
1799                                         if(dist<har->radsq) {
1800                                                 
1801                                                 if(shadeHaloFloat(har, colf, 0x7FFFFF, dist, xn, yn, har->flarec))
1802                                                         addalphaAddfacFloat(rtf, colf, har->add);
1803                                         }
1804                                         rtf+=4;
1805                                 }
1806         
1807                                 rectft+= 4*rr->rectx;
1808                                 
1809                                 if(R.test_break(R.tbh)) break; 
1810                         }
1811                 }
1812         }
1813
1814 /* ------------------------------------------------------------------------ */
1815
1816 static void renderflare(RenderResult *rr, float *rectf, HaloRen *har)
1817 {
1818         extern float hashvectf[];
1819         HaloRen fla;
1820         Material *ma;
1821         float *rc, rad, alfa, visifac, vec[3];
1822         int b, type;
1823         
1824         fla= *har;
1825         fla.linec= fla.ringc= fla.flarec= 0;
1826         
1827         rad= har->rad;
1828         alfa= har->alfa;
1829         
1830         visifac= R.ycor*(har->pixels);
1831         /* all radials added / r^3  == 1.0f! */
1832         visifac /= (har->rad*har->rad*har->rad);
1833         visifac*= visifac;
1834
1835         ma= har->mat;
1836         
1837         /* first halo: just do */
1838         
1839         har->rad= rad*ma->flaresize*visifac;
1840         har->radsq= har->rad*har->rad;
1841         har->zs= fla.zs= 0;
1842         
1843         har->alfa= alfa*visifac;
1844
1845         renderhalo_post(rr, rectf, har);
1846         
1847         /* next halo's: the flares */
1848         rc= hashvectf + ma->seed2;
1849         
1850         for(b=1; b<har->flarec; b++) {
1851                 
1852                 fla.r= fabs(rc[0]);
1853                 fla.g= fabs(rc[1]);
1854                 fla.b= fabs(rc[2]);
1855                 fla.alfa= ma->flareboost*fabs(alfa*visifac*rc[3]);
1856                 fla.hard= 20.0f + fabs(70*rc[7]);
1857                 fla.tex= 0;
1858                 
1859                 type= (int)(fabs(3.9*rc[6]));
1860
1861                 fla.rad= ma->subsize*sqrt(fabs(2.0f*har->rad*rc[4]));
1862                 
1863                 if(type==3) {
1864                         fla.rad*= 3.0f;
1865                         fla.rad+= R.rectx/10;
1866                 }
1867                 
1868                 fla.radsq= fla.rad*fla.rad;
1869                 
1870                 vec[0]= 1.4*rc[5]*(har->xs-R.winx/2);
1871                 vec[1]= 1.4*rc[5]*(har->ys-R.winy/2);
1872                 vec[2]= 32.0f*sqrt(vec[0]*vec[0] + vec[1]*vec[1] + 1.0f);
1873                 
1874                 fla.xs= R.winx/2 + vec[0] + (1.2+rc[8])*R.rectx*vec[0]/vec[2];
1875                 fla.ys= R.winy/2 + vec[1] + (1.2+rc[8])*R.rectx*vec[1]/vec[2];
1876
1877                 if(R.flag & R_SEC_FIELD) {
1878                         if(R.r.mode & R_ODDFIELD) fla.ys += 0.5;
1879                         else fla.ys -= 0.5;
1880                 }
1881                 if(type & 1) fla.type= HA_FLARECIRC;
1882                 else fla.type= 0;
1883                 renderhalo_post(rr, rectf, &fla);
1884
1885                 fla.alfa*= 0.5;
1886                 if(type & 2) fla.type= HA_FLARECIRC;
1887                 else fla.type= 0;
1888                 renderhalo_post(rr, rectf, &fla);
1889                 
1890                 rc+= 7;
1891         }
1892 }
1893
1894 /* needs recode... integrate this better! */
1895 void add_halo_flare(Render *re)
1896 {
1897         RenderResult *rr= re->result;
1898         RenderLayer *rl;
1899         HaloRen *har;
1900         int a, mode, do_draw=0;
1901         
1902         /* for now, we get the first renderlayer in list with halos set */
1903         for(rl= rr->layers.first; rl; rl= rl->next)
1904                 if(rl->layflag & SCE_LAY_HALO)
1905                         break;
1906
1907         if(rl==NULL || rl->rectf==NULL)
1908                 return;
1909         
1910         mode= R.r.mode;
1911         R.r.mode &= ~R_PANORAMA;
1912         
1913         project_renderdata(&R, projectverto, 0, 0, 0);
1914         
1915         for(a=0; a<R.tothalo; a++) {
1916                 har= R.sortedhalos[a];
1917                 
1918                 if(har->flarec) {
1919                         do_draw= 1;
1920                         renderflare(rr, rl->rectf, har);
1921                 }
1922         }
1923
1924         if(do_draw) {
1925                 /* weak... the display callback wants an active renderlayer pointer... */
1926                 rr->renlay= rl;
1927                 re->display_draw(re->ddh, rr, NULL);
1928         }
1929         
1930         R.r.mode= mode; 
1931 }
1932
1933 /* ************************* used for shaded view ************************ */
1934
1935 /* if *re, then initialize, otherwise execute */
1936 void RE_shade_external(Render *re, ShadeInput *shi, ShadeResult *shr)
1937 {
1938         static VlakRen vlr;
1939         static ObjectRen obr;
1940         static ObjectInstanceRen obi;
1941         
1942         /* init */
1943         if(re) {
1944                 R= *re;
1945                 
1946                 /* fake render face */
1947                 memset(&vlr, 0, sizeof(VlakRen));
1948                 memset(&obr, 0, sizeof(ObjectRen));
1949                 memset(&obi, 0, sizeof(ObjectInstanceRen));
1950                 obr.lay= -1;
1951                 obi.obr= &obr;
1952                 
1953                 return;
1954         }
1955         shi->vlr= &vlr;
1956         shi->obr= &obr;
1957         shi->obi= &obi;
1958         
1959         if(shi->mat->nodetree && shi->mat->use_nodes)
1960                 ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
1961         else {
1962                 shade_input_init_material(shi);
1963                 shade_material_loop(shi, shr);
1964         }
1965 }
1966
1967 /* ************************* bake ************************ */
1968
1969
1970 typedef struct BakeShade {
1971         ShadeSample ssamp;
1972         ObjectInstanceRen *obi;
1973         VlakRen *vlr;
1974         
1975         ZSpan *zspan;
1976         Image *ima;
1977         ImBuf *ibuf;
1978         
1979         int rectx, recty, quad, type, vdone, ready;
1980
1981         float dir[3];
1982         Object *actob;
1983         
1984         unsigned int *rect;
1985         float *rect_float;
1986         
1987         int usemask;
1988         char *rect_mask; /* bake pixel mask */
1989
1990         float dxco[3], dyco[3];
1991
1992         short *do_update;
1993 } BakeShade;
1994
1995 /* bake uses a char mask to know what has been baked */
1996 #define BAKE_MASK_NULL          0
1997 #define BAKE_MASK_MARGIN        1
1998 #define BAKE_MASK_BAKED         2
1999 static void bake_mask_filter_extend( char *mask, int width, int height )
2000 {
2001         char *row1, *row2, *row3;
2002         int rowlen, x, y;
2003         char *temprect;
2004         
2005         rowlen= width;
2006         
2007         /* make a copy, to prevent flooding */
2008         temprect= MEM_dupallocN(mask);
2009         
2010         for(y=1; y<=height; y++) {
2011                 /* setup rows */
2012                 row1= (char *)(temprect + (y-2)*rowlen);
2013                 row2= row1 + rowlen;
2014                 row3= row2 + rowlen;
2015                 if(y==1)
2016                         row1= row2;
2017                 else if(y==height)
2018                         row3= row2;
2019                 
2020                 for(x=0; x<rowlen; x++) {
2021                         if (mask[((y-1)*rowlen)+x]==0) {
2022                                 if (*row1 || *row2 || *row3 || *(row1+1) || *(row3+1) ) {
2023                                         mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
2024                                 } else if((x!=rowlen-1) && (*(row1+2) || *(row2+2) || *(row3+2)) ) {
2025                                         mask[((y-1)*rowlen)+x] = BAKE_MASK_MARGIN;
2026                                 }
2027                         }
2028                         
2029                         if(x!=0) {
2030                                 row1++; row2++; row3++;
2031                         }
2032                 }
2033         }
2034         MEM_freeN(temprect);
2035 }
2036
2037 static void bake_mask_clear( ImBuf *ibuf, char *mask, char val )
2038 {
2039         int x,y;
2040         if (ibuf->rect_float) {
2041                 for(x=0; x<ibuf->x; x++) {
2042                         for(y=0; y<ibuf->y; y++) {
2043                                 if (mask[ibuf->x*y + x] == val) {
2044                                         float *col= ibuf->rect_float + 4*(ibuf->x*y + x);
2045                                         col[0] = col[1] = col[2] = col[3] = 0.0f;
2046                                 }
2047                         }
2048                 }
2049                 
2050         } else {
2051                 /* char buffer */
2052                 for(x=0; x<ibuf->x; x++) {
2053                         for(y=0; y<ibuf->y; y++) {
2054                                 if (mask[ibuf->x*y + x] == val) {
2055                                         char *col= (char *)(ibuf->rect + ibuf->x*y + x);
2056                                         col[0] = col[1] = col[2] = col[3] = 0;
2057                                 }
2058                         }
2059                 }
2060         }
2061 }
2062
2063 static void bake_set_shade_input(ObjectInstanceRen *obi, VlakRen *vlr, ShadeInput *shi, int quad, int isect, int x, int y, float u, float v)
2064 {
2065         if(isect) {
2066                 /* raytrace intersection with different u,v than scanconvert */
2067                 if(vlr->v4) {
2068                         if(quad)
2069                                 shade_input_set_triangle_i(shi, obi, vlr, 2, 1, 3);
2070                         else
2071                                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 3);
2072                 }
2073                 else
2074                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
2075         }
2076         else {
2077                 /* regular scanconvert */
2078                 if(quad) 
2079                         shade_input_set_triangle_i(shi, obi, vlr, 0, 2, 3);
2080                 else
2081                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
2082         }
2083                 
2084         /* cache for shadow */
2085         shi->samplenr= R.shadowsamplenr[shi->thread]++;
2086
2087         shi->mask= 0xFFFF; /* all samples */
2088         
2089         shi->u= -u;
2090         shi->v= -v;
2091         shi->xs= x;
2092         shi->ys= y;
2093         
2094         shade_input_set_uv(shi);
2095         shade_input_set_normals(shi);
2096
2097         /* no normal flip */
2098         if(shi->flippednor)
2099                 shade_input_flip_normals(shi);
2100
2101         /* set up view vector to look right at the surface (note that the normal
2102          * is negated in the renderer so it does not need to be done here) */
2103         shi->view[0]= shi->vn[0];
2104         shi->view[1]= shi->vn[1];
2105         shi->view[2]= shi->vn[2];
2106 }
2107
2108 static void bake_shade(void *handle, Object *ob, ShadeInput *shi, int quad, int x, int y, float u, float v, float *tvn, float *ttang)
2109 {
2110         BakeShade *bs= handle;
2111         ShadeSample *ssamp= &bs->ssamp;
2112         ShadeResult shr;
2113         VlakRen *vlr= shi->vlr;
2114         
2115         shade_input_init_material(shi);
2116         
2117         if(bs->type==RE_BAKE_AO) {
2118                 ambient_occlusion(shi);
2119
2120                 if(R.r.bake_flag & R_BAKE_NORMALIZE)
2121                         VECCOPY(shr.combined, shi->ao)
2122                 else
2123                         ambient_occlusion_to_diffuse(shi, shr.combined);
2124         }
2125         else {
2126                 if (bs->type==RE_BAKE_SHADOW) /* Why do shadows set the color anyhow?, ignore material color for baking */
2127                         shi->r = shi->g = shi->b = 1.0f;
2128         
2129                 shade_input_set_shade_texco(shi);
2130                 
2131                 if(!ELEM3(bs->type, RE_BAKE_NORMALS, RE_BAKE_TEXTURE, RE_BAKE_SHADOW))
2132                         shade_samples_do_AO(ssamp);
2133                 
2134                 if(shi->mat->nodetree && shi->mat->use_nodes) {
2135                         ntreeShaderExecTree(shi->mat->nodetree, shi, &shr);
2136                         shi->mat= vlr->mat;             /* shi->mat is being set in nodetree */
2137                 }
2138                 else
2139                         shade_material_loop(shi, &shr);
2140                 
2141                 if(bs->type==RE_BAKE_NORMALS) {
2142                         float nor[3];
2143
2144                         VECCOPY(nor, shi->vn);
2145
2146                         if(R.r.bake_normal_space == R_BAKE_SPACE_CAMERA);
2147                         else if(R.r.bake_normal_space == R_BAKE_SPACE_TANGENT) {
2148                                 float mat[3][3], imat[3][3];
2149
2150                                 /* bitangent */
2151                                 if(tvn && ttang) {
2152                                         VECCOPY(mat[0], ttang);
2153                                         cross_v3_v3v3(mat[1], tvn, ttang);
2154                                         VECCOPY(mat[2], tvn);
2155                                 }
2156                                 else {
2157                                         VECCOPY(mat[0], shi->nmaptang);
2158                                         cross_v3_v3v3(mat[1], shi->vn, shi->nmaptang);
2159                                         VECCOPY(mat[2], shi->vn);
2160                                 }
2161
2162                                 invert_m3_m3(imat, mat);
2163                                 mul_m3_v3(imat, nor);
2164                         }
2165                         else if(R.r.bake_normal_space == R_BAKE_SPACE_OBJECT)
2166                                 mul_mat3_m4_v3(ob->imat, nor); /* ob->imat includes viewinv! */
2167                         else if(R.r.bake_normal_space == R_BAKE_SPACE_WORLD)
2168                                 mul_mat3_m4_v3(R.viewinv, nor);
2169
2170                         normalize_v3(nor); /* in case object has scaling */
2171
2172                         shr.combined[0]= nor[0]/2.0f + 0.5f;
2173                         shr.combined[1]= 0.5f - nor[1]/2.0f;
2174                         shr.combined[2]= nor[2]/2.0f + 0.5f;
2175                 }
2176                 else if(bs->type==RE_BAKE_TEXTURE) {
2177                         shr.combined[0]= shi->r;
2178                         shr.combined[1]= shi->g;
2179                         shr.combined[2]= shi->b;
2180                         shr.alpha = shi->alpha;
2181                 }
2182                 else if(bs->type==RE_BAKE_SHADOW) {
2183                         VECCOPY(shr.combined, shr.shad);
2184                         shr.alpha = shi->alpha;
2185                 }
2186         }
2187         
2188         if(bs->rect_float) {
2189                 float *col= bs->rect_float + 4*(bs->rectx*y + x);
2190                 VECCOPY(col, shr.combined);
2191                 if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
2192                         col[3]= shr.alpha;
2193                 } else {
2194                         col[3]= 1.0;
2195                 }
2196         }
2197         else {
2198                 char *col= (char *)(bs->rect + bs->rectx*y + x);
2199                 col[0]= FTOCHAR(shr.combined[0]);
2200                 col[1]= FTOCHAR(shr.combined[1]);
2201                 col[2]= FTOCHAR(shr.combined[2]);
2202                 
2203                 
2204                 if (bs->type==RE_BAKE_ALL || bs->type==RE_BAKE_TEXTURE) {
2205                         col[3]= FTOCHAR(shr.alpha);
2206                 } else {
2207                         col[3]= 255;
2208                 }
2209         }
2210         
2211         if (bs->rect_mask) {
2212                 bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
2213         }
2214 }
2215
2216 static void bake_displacement(void *handle, ShadeInput *shi, float dist, int x, int y)
2217 {
2218         BakeShade *bs= handle;
2219         float disp;
2220         
2221         if(R.r.bake_flag & R_BAKE_NORMALIZE && R.r.bake_maxdist) {
2222                 disp = (dist+R.r.bake_maxdist) / (R.r.bake_maxdist*2); /* alter the range from [-bake_maxdist, bake_maxdist] to [0, 1]*/
2223         } else {
2224                 disp = 0.5 + dist; /* alter the range from [-0.5,0.5] to [0,1]*/
2225         }
2226         
2227         if(bs->rect_float) {
2228                 float *col= bs->rect_float + 4*(bs->rectx*y + x);
2229                 col[0] = col[1] = col[2] = disp;
2230                 col[3]= 1.0f;
2231         } else {        
2232                 char *col= (char *)(bs->rect + bs->rectx*y + x);
2233                 col[0]= FTOCHAR(disp);
2234                 col[1]= FTOCHAR(disp);
2235                 col[2]= FTOCHAR(disp);
2236                 col[3]= 255;
2237         }
2238         if (bs->rect_mask) {
2239                 bs->rect_mask[bs->rectx*y + x] = BAKE_MASK_BAKED;
2240         }
2241 }
2242
2243 #if 0
2244 static int bake_check_intersect(Isect *is, int ob, RayFace *face)
2245 {
2246         BakeShade *bs = (BakeShade*)is->userdata;
2247         
2248         /* no direction checking for now, doesn't always improve the result
2249          * (INPR(shi->facenor, bs->dir) > 0.0f); */
2250
2251         return (R.objectinstance[ob & ~RE_RAY_TRANSFORM_OFFS].obr->ob != bs->actob);
2252 }
2253 #endif
2254
2255 static int bake_intersect_tree(RayObject* raytree, Isect* isect, float *start, float *dir, float sign, float *hitco, float *dist)
2256 {
2257         //TODO, validate against blender 2.4x, results may have changed.
2258         float maxdist;
2259         int hit;
2260
2261         /* might be useful to make a user setting for maxsize*/
2262         if(R.r.bake_maxdist > 0.0f)
2263                 maxdist= R.r.bake_maxdist;
2264         else
2265                 maxdist= FLT_MAX + R.r.bake_biasdist;
2266         
2267         /* 'dir' is always normalized */
2268         VECADDFAC(isect->start, start, dir, -R.r.bake_biasdist);                                        
2269
2270         isect->vec[0] = dir[0]*maxdist*sign;
2271         isect->vec[1] = dir[1]*maxdist*sign;
2272         isect->vec[2] = dir[2]*maxdist*sign;
2273
2274         isect->labda = maxdist;
2275
2276         /* TODO, 2.4x had this...
2277         hit = RE_ray_tree_intersect_check(R.raytree, isect, bake_check_intersect);
2278         ...the active object may NOT be ignored in some cases.
2279         */
2280         hit = RE_rayobject_raycast(raytree, isect);
2281         if(hit) {
2282                 hitco[0] = isect->start[0] + isect->labda*isect->vec[0];
2283                 hitco[1] = isect->start[1] + isect->labda*isect->vec[1];
2284                 hitco[2] = isect->start[2] + isect->labda*isect->vec[2];
2285
2286                 *dist= len_v3v3(start, hitco);
2287         }
2288
2289         return hit;
2290 }
2291
2292 static void bake_set_vlr_dxyco(BakeShade *bs, float *uv1, float *uv2, float *uv3)
2293 {
2294         VlakRen *vlr= bs->vlr;
2295         float A, d1, d2, d3, *v1, *v2, *v3;
2296
2297         if(bs->quad) {
2298                 v1= vlr->v1->co;
2299                 v2= vlr->v3->co;
2300                 v3= vlr->v4->co;
2301         }
2302         else {
2303                 v1= vlr->v1->co;
2304                 v2= vlr->v2->co;
2305                 v3= vlr->v3->co;
2306         }
2307
2308         /* formula derived from barycentric coordinates:
2309          * (uvArea1*v1 + uvArea2*v2 + uvArea3*v3)/uvArea
2310          * then taking u and v partial derivatives to get dxco and dyco */
2311         A= (uv2[0] - uv1[0])*(uv3[1] - uv1[1]) - (uv3[0] - uv1[0])*(uv2[1] - uv1[1]);
2312
2313         if(fabs(A) > FLT_EPSILON) {
2314                 A= 0.5f/A;
2315
2316                 d1= uv2[1] - uv3[1];
2317                 d2= uv3[1] - uv1[1];
2318                 d3= uv1[1] - uv2[1];
2319                 bs->dxco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
2320                 bs->dxco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
2321                 bs->dxco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
2322
2323                 d1= uv3[0] - uv2[0];
2324                 d2= uv1[0] - uv3[0];
2325                 d3= uv2[0] - uv1[0];
2326                 bs->dyco[0]= (v1[0]*d1 + v2[0]*d2 + v3[0]*d3)*A;
2327                 bs->dyco[1]= (v1[1]*d1 + v2[1]*d2 + v3[1]*d3)*A;
2328                 bs->dyco[2]= (v1[2]*d1 + v2[2]*d2 + v3[2]*d3)*A;
2329         }
2330         else {
2331                 bs->dxco[0]= bs->dxco[1]= bs->dxco[2]= 0.0f;
2332                 bs->dyco[0]= bs->dyco[1]= bs->dyco[2]= 0.0f;
2333         }
2334
2335         if(bs->obi->flag & R_TRANSFORMED) {
2336                 mul_m3_v3(bs->obi->nmat, bs->dxco);
2337                 mul_m3_v3(bs->obi->nmat, bs->dyco);
2338         }
2339 }
2340
2341 static void do_bake_shade(void *handle, int x, int y, float u, float v)
2342 {
2343         BakeShade *bs= handle;
2344         VlakRen *vlr= bs->vlr;
2345         ObjectInstanceRen *obi= bs->obi;
2346         Object *ob= obi->obr->ob;
2347         float l, *v1, *v2, *v3, tvn[3], ttang[3];
2348         int quad;
2349         ShadeSample *ssamp= &bs->ssamp;
2350         ShadeInput *shi= ssamp->shi;
2351         
2352         /* fast threadsafe break test */
2353         if(R.test_break(R.tbh))
2354                 return;
2355         
2356         /* setup render coordinates */
2357         if(bs->quad) {
2358                 v1= vlr->v1->co;
2359                 v2= vlr->v3->co;
2360                 v3= vlr->v4->co;
2361         }
2362         else {
2363                 v1= vlr->v1->co;
2364                 v2= vlr->v2->co;
2365                 v3= vlr->v3->co;
2366         }
2367         
2368         /* renderco */
2369         l= 1.0f-u-v;
2370         
2371         shi->co[0]= l*v3[0]+u*v1[0]+v*v2[0];
2372         shi->co[1]= l*v3[1]+u*v1[1]+v*v2[1];
2373         shi->co[2]= l*v3[2]+u*v1[2]+v*v2[2];
2374         
2375         if(obi->flag & R_TRANSFORMED)
2376                 mul_m4_v3(obi->mat, shi->co);
2377         
2378         VECCOPY(shi->dxco, bs->dxco);
2379         VECCOPY(shi->dyco, bs->dyco);
2380
2381         quad= bs->quad;
2382         bake_set_shade_input(obi, vlr, shi, quad, 0, x, y, u, v);
2383
2384         if(bs->type==RE_BAKE_NORMALS && R.r.bake_normal_space==R_BAKE_SPACE_TANGENT) {
2385                 shade_input_set_shade_texco(shi);
2386                 VECCOPY(tvn, shi->vn);
2387                 VECCOPY(ttang, shi->nmaptang);
2388         }
2389
2390         /* if we are doing selected to active baking, find point on other face */
2391         if(bs->actob) {
2392                 Isect isec, minisec;
2393                 float co[3], minco[3], dist, mindist=0.0f;
2394                 int hit, sign, dir=1;
2395                 
2396                 /* intersect with ray going forward and backward*/
2397                 hit= 0;
2398                 memset(&minisec, 0, sizeof(minisec));
2399                 minco[0]= minco[1]= minco[2]= 0.0f;
2400                 
2401                 VECCOPY(bs->dir, shi->vn);
2402                 
2403                 for(sign=-1; sign<=1; sign+=2) {
2404                         memset(&isec, 0, sizeof(isec));
2405                         isec.mode= RE_RAY_MIRROR;
2406
2407                         isec.orig.ob   = obi;
2408                         isec.orig.face = vlr;
2409                         isec.userdata= bs;
2410                         
2411                         if(bake_intersect_tree(R.raytree, &isec, shi->co, shi->vn, sign, co, &dist)) {
2412                                 if(!hit || len_v3v3(shi->co, co) < len_v3v3(shi->co, minco)) {
2413                                         minisec= isec;
2414                                         mindist= dist;
2415                                         VECCOPY(minco, co);
2416                                         hit= 1;
2417                                         dir = sign;
2418                                 }
2419                         }
2420                 }
2421
2422                 if (bs->type==RE_BAKE_DISPLACEMENT) {
2423                         if(hit)
2424                                 bake_displacement(handle, shi, (dir==-1)? mindist:-mindist, x, y);
2425                         else
2426                                 bake_displacement(handle, shi, 0.0f, x, y);
2427                         return;
2428                 }
2429
2430                 /* if hit, we shade from the new point, otherwise from point one starting face */
2431                 if(hit) {
2432                         obi= (ObjectInstanceRen*)minisec.hit.ob;
2433                         vlr= (VlakRen*)minisec.hit.face;
2434                         quad= (minisec.isect == 2);
2435                         VECCOPY(shi->co, minco);
2436                         
2437                         u= -minisec.u;
2438                         v= -minisec.v;
2439                         bake_set_shade_input(obi, vlr, shi, quad, 1, x, y, u, v);
2440                 }
2441         }
2442
2443         if(bs->type==RE_BAKE_NORMALS && R.r.bake_normal_space==R_BAKE_SPACE_TANGENT)
2444                 bake_shade(handle, ob, shi, quad, x, y, u, v, tvn, ttang);
2445         else
2446                 bake_shade(handle, ob, shi, quad, x, y, u, v, 0, 0);
2447 }
2448
2449 static int get_next_bake_face(BakeShade *bs)
2450 {
2451         ObjectRen *obr;
2452         VlakRen *vlr;
2453         MTFace *tface;
2454         static int v= 0, vdone= 0;
2455         static ObjectInstanceRen *obi= NULL;
2456         
2457         if(bs==NULL) {
2458                 vlr= NULL;
2459                 v= vdone= 0;
2460                 obi= R.instancetable.first;
2461                 return 0;
2462         }
2463         
2464         BLI_lock_thread(LOCK_CUSTOM1);  
2465
2466         for(; obi; obi=obi->next, v=0) {
2467                 obr= obi->obr;
2468
2469                 for(; v<obr->totvlak; v++) {
2470                         vlr= RE_findOrAddVlak(obr, v);
2471
2472                         if((bs->actob && bs->actob == obr->ob) || (!bs->actob && (obr->ob->flag & SELECT))) {
2473                                 tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
2474
2475                                 if(tface && tface->tpage) {
2476                                         Image *ima= tface->tpage;
2477                                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
2478                                         float vec[4]= {0.0f, 0.0f, 0.0f, 0.0f};
2479                                         
2480                                         if(ibuf==NULL)
2481                                                 continue;
2482                                         
2483                                         if(ibuf->rect==NULL && ibuf->rect_float==NULL)
2484                                                 continue;
2485                                         
2486                                         if(ibuf->rect_float && !(ibuf->channels==0 || ibuf->channels==4))
2487                                                 continue;
2488                                         
2489                                         /* find the image for the first time? */
2490                                         if(ima->id.flag & LIB_DOIT) {
2491                                                 ima->id.flag &= ~LIB_DOIT;
2492                                                 
2493                                                 /* we either fill in float or char, this ensures things go fine */
2494                                                 if(ibuf->rect_float)
2495                                                         imb_freerectImBuf(ibuf);
2496                                                 /* clear image */
2497                                                 if(R.r.bake_flag & R_BAKE_CLEAR)
2498                                                         IMB_rectfill(ibuf, vec);
2499                                         
2500                                                 /* might be read by UI to set active image for display */
2501                                                 R.bakebuf= ima;
2502                                         }                               
2503                                         
2504                                         bs->obi= obi;
2505                                         bs->vlr= vlr;
2506                                         
2507                                         bs->vdone++;    /* only for error message if nothing was rendered */
2508                                         v++;
2509                                         
2510                                         BLI_unlock_thread(LOCK_CUSTOM1);
2511                                         return 1;
2512                                 }
2513                         }
2514                 }
2515         }
2516         
2517         BLI_unlock_thread(LOCK_CUSTOM1);
2518         return 0;
2519 }
2520
2521 /* already have tested for tface and ima and zspan */
2522 static void shade_tface(BakeShade *bs)
2523 {
2524         VlakRen *vlr= bs->vlr;
2525         ObjectInstanceRen *obi= bs->obi;
2526         ObjectRen *obr= obi->obr;
2527         MTFace *tface= RE_vlakren_get_tface(obr, vlr, obr->bakemtface, NULL, 0);
2528         Image *ima= tface->tpage;
2529         float vec[4][2];
2530         int a, i1, i2, i3;
2531         
2532         /* check valid zspan */
2533         if(ima!=bs->ima) {
2534                 bs->ima= ima;
2535                 bs->ibuf= BKE_image_get_ibuf(ima, NULL);
2536                 /* note, these calls only free/fill contents of zspan struct, not zspan itself */
2537                 zbuf_free_span(bs->zspan);
2538                 zbuf_alloc_span(bs->zspan, bs->ibuf->x, bs->ibuf->y, R.clipcrop);
2539         }                               
2540         
2541         bs->rectx= bs->ibuf->x;
2542         bs->recty= bs->ibuf->y;
2543         bs->rect= bs->ibuf->rect;
2544         bs->rect_float= bs->ibuf->rect_float;
2545         bs->quad= 0;
2546         
2547         if (bs->usemask) {
2548                 if (bs->ibuf->userdata==NULL) {
2549                         BLI_lock_thread(LOCK_CUSTOM1);
2550                         if (bs->ibuf->userdata==NULL) { /* since the thread was locked, its possible another thread alloced the value */
2551                                 bs->ibuf->userdata = (void *)MEM_callocN(sizeof(char)*bs->rectx*bs->recty, "BakeMask");
2552                                 bs->rect_mask= (char *)bs->ibuf->userdata;
2553                         }
2554                         BLI_unlock_thread(LOCK_CUSTOM1);
2555                 } else {
2556                         bs->rect_mask= (char *)bs->ibuf->userdata;
2557                 }
2558         }
2559         
2560         /* get pixel level vertex coordinates */
2561         for(a=0; a<4; a++) {
2562                 /* Note, workaround for pixel aligned UVs which are common and can screw up our intersection tests
2563                  * where a pixel gets inbetween 2 faces or the middle of a quad,
2564                  * camera aligned quads also have this problem but they are less common.
2565                  * Add a small offset to the UVs, fixes bug #18685 - Campbell */
2566                 vec[a][0]= tface->uv[a][0]*(float)bs->rectx - (0.5f + 0.001);
2567                 vec[a][1]= tface->uv[a][1]*(float)bs->recty - (0.5f + 0.002);
2568         }
2569         
2570         /* UV indices have to be corrected for possible quad->tria splits */
2571         i1= 0; i2= 1; i3= 2;
2572         vlr_set_uv_indices(vlr, &i1, &i2, &i3);
2573         bake_set_vlr_dxyco(bs, vec[i1], vec[i2], vec[i3]);
2574         zspan_scanconvert(bs->zspan, bs, vec[i1], vec[i2], vec[i3], do_bake_shade);
2575         
2576         if(vlr->v4) {
2577                 bs->quad= 1;
2578                 bake_set_vlr_dxyco(bs, vec[0], vec[2], vec[3]);
2579                 zspan_scanconvert(bs->zspan, bs, vec[0], vec[2], vec[3], do_bake_shade);
2580         }
2581 }
2582
2583 static void *do_bake_thread(void *bs_v)
2584 {
2585         BakeShade *bs= bs_v;
2586         
2587         while(get_next_bake_face(bs)) {
2588                 shade_tface(bs);
2589                 
2590                 /* fast threadsafe break test */
2591                 if(R.test_break(R.tbh))
2592                         break;
2593
2594                 /* access is not threadsafe but since its just true/false probably ok
2595                  * only used for interactive baking */
2596                 if(bs->do_update)
2597                         *bs->do_update= TRUE;
2598         }
2599         bs->ready= 1;
2600         
2601         return NULL;
2602 }
2603
2604 /* using object selection tags, the faces with UV maps get baked */
2605 /* render should have been setup */
2606 /* returns 0 if nothing was handled */
2607 int RE_bake_shade_all_selected(Render *re, int type, Object *actob, short *do_update)
2608 {
2609         BakeShade handles[BLENDER_MAX_THREADS];
2610         ListBase threads;
2611         Image *ima;
2612         int a, vdone=0, usemask=0;
2613         
2614         /* initialize render global */
2615         R= *re;
2616         R.bakebuf= NULL;
2617         
2618         /* initialize static vars */
2619         get_next_bake_face(NULL);
2620         
2621         /* do we need a mask? */
2622         if (re->r.bake_filter && (re->r.bake_flag & R_BAKE_CLEAR)==0)
2623                 usemask = 1;
2624         
2625         /* baker uses this flag to detect if image was initialized */
2626         for(ima= G.main->image.first; ima; ima= ima->id.next) {
2627                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
2628                 ima->id.flag |= LIB_DOIT;
2629                 if (ibuf)
2630                         ibuf->userdata = NULL; /* use for masking if needed */
2631         }
2632         
2633         BLI_init_threads(&threads, do_bake_thread, re->r.threads);
2634
2635         /* get the threads running */
2636         for(a=0; a<re->r.threads; a++) {
2637                 /* set defaults in handles */
2638                 memset(&handles[a], 0, sizeof(BakeShade));
2639                 
2640                 handles[a].ssamp.shi[0].lay= re->scene->lay;
2641                 
2642                 if (type==RE_BAKE_SHADOW) {
2643                         handles[a].ssamp.shi[0].passflag= SCE_PASS_SHADOW;
2644                 } else {
2645                         handles[a].ssamp.shi[0].passflag= SCE_PASS_COMBINED;
2646                 }
2647                 handles[a].ssamp.shi[0].combinedflag= ~(SCE_PASS_SPEC);
2648                 handles[a].ssamp.shi[0].thread= a;
2649                 handles[a].ssamp.tot= 1;
2650                 
2651                 handles[a].type= type;
2652                 handles[a].actob= actob;
2653                 handles[a].zspan= MEM_callocN(sizeof(ZSpan), "zspan for bake");
2654                 
2655                 handles[a].usemask = usemask;
2656
2657                 handles[a].do_update = do_update; /* use to tell the view to update */
2658                 
2659                 BLI_insert_thread(&threads, &handles[a]);
2660         }
2661         
2662         /* wait for everything to be done */
2663         a= 0;
2664         while(a!=re->r.threads) {
2665                 
2666                 PIL_sleep_ms(50);
2667
2668                 for(a=0; a<re->r.threads; a++)
2669                         if(handles[a].ready==0)
2670                                 break;
2671         }
2672         
2673         /* filter and refresh images */
2674         for(ima= G.main->image.first; ima; ima= ima->id.next) {
2675                 if((ima->id.flag & LIB_DOIT)==0) {
2676                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
2677                         if (re->r.bake_filter) {
2678                                 if (usemask) {
2679                                         /* extend the mask +2 pixels from the image,
2680                                          * this is so colors dont blend in from outside */
2681                                         char *temprect;
2682                                         
2683                                         for(a=0; a<re->r.bake_filter; a++)
2684                                                 bake_mask_filter_extend((char *)ibuf->userdata, ibuf->x, ibuf->y);
2685                                         
2686                                         temprect = MEM_dupallocN(ibuf->userdata);
2687                                         
2688                                         /* expand twice to clear this many pixels, so they blend back in */
2689                                         bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
2690                                         bake_mask_filter_extend(temprect, ibuf->x, ibuf->y);
2691                                         
2692                                         /* clear all pixels in the margin*/
2693                                         bake_mask_clear(ibuf, temprect, BAKE_MASK_MARGIN);
2694                                         MEM_freeN(temprect);
2695                                 }
2696                                 
2697                                 for(a=0; a<re->r.bake_filter; a++) {
2698                                         /*the mask, ibuf->userdata - can be null, in this case only zero alpha is used */
2699                                         IMB_filter_extend(ibuf, (char *)ibuf->userdata);
2700                                 }
2701                                 
2702                                 if (ibuf->userdata) {
2703                                         MEM_freeN(ibuf->userdata);
2704                                         ibuf->userdata= NULL;
2705                                 }
2706                         }
2707                         ibuf->userflags |= IB_BITMAPDIRTY;
2708                         if (ibuf->rect_float) IMB_rect_from_float(ibuf);
2709                 }
2710         }
2711         
2712         /* calculate return value */
2713         for(a=0; a<re->r.threads; a++) {
2714                 vdone+= handles[a].vdone;
2715                 
2716                 zbuf_free_span(handles[a].zspan);
2717                 MEM_freeN(handles[a].zspan);
2718         }
2719         
2720         BLI_end_threads(&threads);
2721         return vdone;
2722 }
2723
2724 struct Image *RE_bake_shade_get_image(void)
2725 {
2726         return R.bakebuf;
2727 }
2728