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