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