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