Orange branch: Revived hidden treasure, the Groups!
[blender.git] / source / blender / render / intern / source / rendercore.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): Hos, Robert Wenzlaff.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 /* system includes */
34 #include <math.h>
35 #include <string.h>
36 #include <stdlib.h>
37
38 /* External modules: */
39 #include "MEM_guardedalloc.h"
40 #include "BLI_arithb.h"
41 #include "MTC_matrixops.h"
42
43 #include "BKE_utildefines.h"
44
45 #include "DNA_camera_types.h"
46 #include "DNA_group_types.h"
47 #include "DNA_image_types.h"
48 #include "DNA_lamp_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_object_types.h"
52 #include "DNA_texture_types.h"
53
54 #include "BKE_global.h"
55 #include "BKE_texture.h"
56
57 #include "BLI_rand.h"
58
59 /* local include */
60 #include "RE_callbacks.h"
61 #include "render.h"
62 #include "zbuf.h"               /* stuff like bgnaccumbuf, fillrect, ...*/
63 #include "pixelblending.h"
64 #include "pixelshading.h"
65 #include "vanillaRenderPipe.h"  /* transfercolour... */
66 #include "gammaCorrectionTables.h"
67 #include "shadbuf.h"
68 #include "renderHelp.h"
69
70 #include "jitter.h"
71 #include "texture.h"
72
73 /* own include */
74 #include "rendercore.h"
75
76 #ifdef HAVE_CONFIG_H
77 #include <config.h>
78 #endif
79
80 #include "SDL_thread.h"
81
82
83 /* global for this file. struct render will be more dynamic later, to allow multiple renderers */
84 RE_Render R;
85
86 float bluroffsx=0.0, bluroffsy=0.0;     // set in initrender.c (bad, ton)
87
88 /* x and y are current pixels to be rendered */
89 void calc_view_vector(float *view, float x, float y)
90 {
91         
92         if(R.r.mode & R_ORTHO) {
93                 view[0]= view[1]= 0.0;
94         }
95         else {
96                 view[0]= (x+(R.xstart)+bluroffsx +0.5);
97                 
98                 if(R.flag & R_SEC_FIELD) {
99                         if(R.r.mode & R_ODDFIELD) view[1]= (y+R.ystart)*R.ycor;
100                         else view[1]= (y+R.ystart+1.0)*R.ycor;
101                 }
102                 else view[1]= (y+R.ystart+bluroffsy+0.5)*R.ycor;
103         }       
104         view[2]= -R.viewfac;
105         
106         if(R.r.mode & R_PANORAMA) {
107                 float panoco, panosi, u, v;
108                 panoco = getPanovCo();
109                 panosi = getPanovSi();
110                 
111                 u= view[0]; v= view[2];
112                 view[0]= panoco*u + panosi*v;
113                 view[2]= -panosi*u + panoco*v;
114         }
115 }
116
117 #if 0
118 static void fogcolor(float *colf, float *rco, float *view)
119 {
120         float alpha, stepsize, startdist, dist, hor[4], zen[3], vec[3], dview[3];
121         float div=0.0f, distfac;
122         
123         hor[0]= R.wrld.horr; hor[1]= R.wrld.horg; hor[2]= R.wrld.horb;
124         zen[0]= R.wrld.zenr; zen[1]= R.wrld.zeng; zen[2]= R.wrld.zenb;
125         
126         VECCOPY(vec, rco);
127         
128         /* we loop from cur coord to mist start in steps */
129         stepsize= 1.0f;
130         
131         div= ABS(view[2]);
132         dview[0]= view[0]/(stepsize*div);
133         dview[1]= view[1]/(stepsize*div);
134         dview[2]= -stepsize;
135
136         startdist= -rco[2] + BLI_frand();
137         for(dist= startdist; dist>R.wrld.miststa; dist-= stepsize) {
138                 
139                 hor[0]= R.wrld.horr; hor[1]= R.wrld.horg; hor[2]= R.wrld.horb;
140                 alpha= 1.0f;
141                 do_sky_tex(vec, vec, NULL, hor, zen, &alpha);
142                 
143                 distfac= (dist-R.wrld.miststa)/R.wrld.mistdist;
144                 
145                 hor[3]= hor[0]*distfac*distfac;
146                 
147                 /* premul! */
148                 alpha= hor[3];
149                 hor[0]= hor[0]*alpha;
150                 hor[1]= hor[1]*alpha;
151                 hor[2]= hor[2]*alpha;
152                 addAlphaOverFloat(colf, hor);
153                 
154                 VECSUB(vec, vec, dview);
155         }       
156 }
157 #endif
158
159 float mistfactor(float zcor, float *co) /* dist en height, return alpha */
160 {
161         float fac, hi;
162         
163         fac= zcor - R.wrld.miststa;     /* zcor is calculated per pixel */
164
165         /* fac= -co[2]-R.wrld.miststa; */
166
167         if(fac>0.0) {
168                 if(fac< R.wrld.mistdist) {
169                         
170                         fac= (fac/(R.wrld.mistdist));
171                         
172                         if(R.wrld.mistype==0) fac*= fac;
173                         else if(R.wrld.mistype==1);
174                         else fac= sqrt(fac);
175                 }
176                 else fac= 1.0;
177         }
178         else fac= 0.0;
179         
180         /* height switched off mist */
181         if(R.wrld.misthi!=0.0 && fac!=0.0) {
182                 /* at height misthi the mist is completely gone */
183
184                 hi= R.viewinv[0][2]*co[0]+R.viewinv[1][2]*co[1]+R.viewinv[2][2]*co[2]+R.viewinv[3][2];
185                 
186                 if(hi>R.wrld.misthi) fac= 0.0;
187                 else if(hi>0.0) {
188                         hi= (R.wrld.misthi-hi)/R.wrld.misthi;
189                         fac*= hi*hi;
190                 }
191         }
192
193         return (1.0-fac)* (1.0-R.wrld.misi);    
194 }
195
196 /* external for preview only */
197 void RE_sky_char(float *view, char *col)
198 {
199         float f, colf[3];
200         float dither_value;
201
202         dither_value = ( (BLI_frand()-0.5)*R.r.dither_intensity)/256.0; 
203         
204         shadeSkyPixelFloat(colf, view, view, NULL);
205         
206         f= 255.0*(colf[0]+dither_value);
207         if(f<=0.0) col[0]= 0; else if(f>255.0) col[0]= 255;
208         else col[0]= (char)f;
209         f= 255.0*(colf[1]+dither_value);
210         if(f<=0.0) col[1]= 0; else if(f>255.0) col[1]= 255;
211         else col[1]= (char)f;
212         f= 255.0*(colf[2]+dither_value);
213         if(f<=0.0) col[2]= 0; else if(f>255.0) col[2]= 255;
214         else col[2]= (char)f;
215         col[3]= 1;      /* to prevent wrong optimalisation alphaover of flares */
216 }
217
218
219 /* ************************************** */
220
221
222 static void spothalo(struct LampRen *lar, ShadeInput *shi, float *intens)
223 {
224         double a, b, c, disc, nray[3], npos[3];
225         float t0, t1 = 0.0, t2= 0.0, t3, haint;
226         float p1[3], p2[3], ladist, maxz = 0.0, maxy = 0.0;
227         int snijp, doclip=1, use_yco=0;
228         int ok1=0, ok2=0;
229         
230         *intens= 0.0;
231         haint= lar->haint;
232         
233         if(R.r.mode & R_ORTHO) {
234                 /* camera pos (view vector) cannot be used... */
235                 /* camera position (cox,coy,0) rotate around lamp */
236                 p1[0]= shi->co[0]-lar->co[0];
237                 p1[1]= shi->co[1]-lar->co[1];
238                 p1[2]= -lar->co[2];
239                 MTC_Mat3MulVecfl(lar->imat, p1);
240                 VECCOPY(npos, p1);      // npos is double!
241         }
242         else {
243                 VECCOPY(npos, lar->sh_invcampos);       /* in initlamp calculated */
244         }
245         
246         /* rotate view */
247         VECCOPY(nray, shi->view);
248         MTC_Mat3MulVecd(lar->imat, nray);
249         
250         if(R.wrld.mode & WO_MIST) {
251                 /* patchy... */
252                 haint *= mistfactor(-lar->co[2], lar->co);
253                 if(haint==0.0) {
254                         return;
255                 }
256         }
257
258
259         /* rotate maxz */
260         if(shi->co[2]==0.0) doclip= 0;  /* for when halo at sky */
261         else {
262                 p1[0]= shi->co[0]-lar->co[0];
263                 p1[1]= shi->co[1]-lar->co[1];
264                 p1[2]= shi->co[2]-lar->co[2];
265         
266                 maxz= lar->imat[0][2]*p1[0]+lar->imat[1][2]*p1[1]+lar->imat[2][2]*p1[2];
267                 maxz*= lar->sh_zfac;
268                 maxy= lar->imat[0][1]*p1[0]+lar->imat[1][1]*p1[1]+lar->imat[2][1]*p1[2];
269
270                 if( fabs(nray[2]) <0.000001 ) use_yco= 1;
271         }
272         
273         /* scale z to make sure volume is normalized */ 
274         nray[2]*= lar->sh_zfac;
275         /* nray does not need normalization */
276         
277         ladist= lar->sh_zfac*lar->dist;
278         
279         /* solve */
280         a = nray[0] * nray[0] + nray[1] * nray[1] - nray[2]*nray[2];
281         b = nray[0] * npos[0] + nray[1] * npos[1] - nray[2]*npos[2];
282         c = npos[0] * npos[0] + npos[1] * npos[1] - npos[2]*npos[2];
283
284         snijp= 0;
285         if (fabs(a) < 0.00000001) {
286                 /*
287                  * Only one intersection point...
288                  */
289                 return;
290         }
291         else {
292                 disc = b*b - a*c;
293                 
294                 if(disc==0.0) {
295                         t1=t2= (-b)/ a;
296                         snijp= 2;
297                 }
298                 else if (disc > 0.0) {
299                         disc = sqrt(disc);
300                         t1 = (-b + disc) / a;
301                         t2 = (-b - disc) / a;
302                         snijp= 2;
303                 }
304         }
305         if(snijp==2) {
306                 /* sort */
307                 if(t1>t2) {
308                         a= t1; t1= t2; t2= a;
309                 }
310
311                 /* z of intersection points with diabolo */
312                 p1[2]= npos[2] + t1*nray[2];
313                 p2[2]= npos[2] + t2*nray[2];
314
315                 /* evaluate both points */
316                 if(p1[2]<=0.0) ok1= 1;
317                 if(p2[2]<=0.0 && t1!=t2) ok2= 1;
318                 
319                 /* at least 1 point with negative z */
320                 if(ok1==0 && ok2==0) return;
321                 
322                 /* intersction point with -ladist, the bottom of the cone */
323                 if(use_yco==0) {
324                         t3= (-ladist-npos[2])/nray[2];
325                                 
326                         /* de we have to replace one of the intersection points? */
327                         if(ok1) {
328                                 if(p1[2]<-ladist) t1= t3;
329                         }
330                         else {
331                                 ok1= 1;
332                                 t1= t3;
333                         }
334                         if(ok2) {
335                                 if(p2[2]<-ladist) t2= t3;
336                         }
337                         else {
338                                 ok2= 1;
339                                 t2= t3;
340                         }
341                 }
342                 else if(ok1==0 || ok2==0) return;
343                 
344                 /* at least 1 visible interesction point */
345                 if(t1<0.0 && t2<0.0) return;
346                 
347                 if(t1<0.0) t1= 0.0;
348                 if(t2<0.0) t2= 0.0;
349                 
350                 if(t1==t2) return;
351                 
352                 /* sort again to be sure */
353                 if(t1>t2) {
354                         a= t1; t1= t2; t2= a;
355                 }
356                 
357                 /* calculate t0: is the maximum visible z (when halo is intersected by face) */ 
358                 if(doclip) {
359                         if(use_yco==0) t0= (maxz-npos[2])/nray[2];
360                         else t0= (maxy-npos[1])/nray[1];
361
362                         if(t0<t1) return;
363                         if(t0<t2) t2= t0;
364                 }
365
366                 /* calc points */
367                 p1[0]= npos[0] + t1*nray[0];
368                 p1[1]= npos[1] + t1*nray[1];
369                 p1[2]= npos[2] + t1*nray[2];
370                 p2[0]= npos[0] + t2*nray[0];
371                 p2[1]= npos[1] + t2*nray[1];
372                 p2[2]= npos[2] + t2*nray[2];
373                 
374                         
375                 /* now we have 2 points, make three lengths with it */
376                 
377                 a= sqrt(p1[0]*p1[0]+p1[1]*p1[1]+p1[2]*p1[2]);
378                 b= sqrt(p2[0]*p2[0]+p2[1]*p2[1]+p2[2]*p2[2]);
379                 c= VecLenf(p1, p2);
380                 
381                 a/= ladist;
382                 a= sqrt(a);
383                 b/= ladist; 
384                 b= sqrt(b);
385                 c/= ladist;
386                 
387                 *intens= c*( (1.0-a)+(1.0-b) );
388
389                 /* WATCH IT: do not clip a,b en c at 1.0, this gives nasty little overflows
390                         at the edges (especially with narrow halos) */
391                 if(*intens<=0.0) return;
392
393                 /* soft area */
394                 /* not needed because t0 has been used for p1/p2 as well */
395                 /* if(doclip && t0<t2) { */
396                 /*      *intens *= (t0-t1)/(t2-t1); */
397                 /* } */
398                 
399                 *intens *= haint;
400                 
401                 if(lar->shb && lar->shb->shadhalostep) {
402                         *intens *= shadow_halo(lar, p1, p2);
403                 }
404                 
405         }
406 }
407
408 static void renderspothalo(ShadeInput *shi, float *col, float alpha)
409 {
410         GroupObject *go;
411         LampRen *lar;
412         float i;
413         
414         if(alpha==0.0f) return;
415
416         for(go=R.lights.first; go; go= go->next) {
417                 lar= go->lampren;
418                 
419                 if(lar->type==LA_SPOT && (lar->mode & LA_HALO) && lar->haint>0) {
420         
421                         spothalo(lar, shi, &i);
422                         if(i>0.0) {
423                                 col[3]+= i*alpha;                       // all premul
424                                 col[0]+= i*lar->r*alpha;
425                                 col[1]+= i*lar->g*alpha;
426                                 col[2]+= i*lar->b*alpha;        
427                         }
428                 }
429         }
430         /* clip alpha, is needed for unified 'alpha threshold' (vanillaRenderPipe.c) */
431         if(col[3]>1.0) col[3]= 1.0;
432 }
433
434
435 static int calchalo_z(HaloRen *har, int zz)
436 {
437
438         if(har->type & HA_ONLYSKY) {
439                 if(zz!=0x7FFFFFFF) zz= - 0x7FFFFF;
440         }
441         else {
442                 zz= (zz>>8);
443         }
444         return zz;
445 }
446
447 static void scanlinehaloPS(int *rectz, long *rectdelta, float *rowbuf, short ys)
448 {
449         HaloRen *har = NULL;
450         PixStr *ps;
451         float dist, xsq, ysq, xn, yn;
452         float *rb;
453         float col[4], accol[4];
454         int a, *rz, zz, didgamma=0;
455         long *rd;
456         short minx, maxx, x, amount, amountm, flarec;
457
458         for(a=0; a<R.tothalo; a++) {
459                 if((a & 255)==0) {
460                         har= R.bloha[a>>8];
461                         if( RE_local_test_break() ) break;  
462                 }
463                 else har++;
464
465                 if(ys>har->maxy);
466                 else if(ys<har->miny);
467                 else {
468                         minx= floor(har->xs-har->rad);
469                         maxx= ceil(har->xs+har->rad);
470                         
471                         if(maxx<0);
472                         else if(R.rectx<minx);
473                         else {
474                                 if(minx<0) minx= 0;
475                                 if(maxx>=R.rectx) maxx= R.rectx-1;
476
477                                 rb= rowbuf + 4*minx;
478                                 rd= rectdelta + minx;
479                                 rz= rectz + minx;
480
481                                 yn= (ys-har->ys)*R.ycor;
482                                 ysq= yn*yn;
483                                 for(x=minx; x<=maxx; x++) {
484                                         
485                                         xn= x-har->xs;
486                                         xsq= xn*xn;
487                                         dist= xsq+ysq;
488                                         
489                                         if(dist<har->radsq) {
490                                                 
491                                                 /* well yah, halo adding shouldnt be done gamma corrected, have to bypass it this way */
492                                                 /* alternative is moving it outside of thread renderlineDA */
493                                                 /* on positive side; the invert correct cancels out correcting halo color */
494                                                 if(do_gamma && didgamma==0) {
495                                                         float *buf= rowbuf;
496                                                         int xt;
497                                                         for(xt=0; xt<R.rectx; xt++, buf+=4) {
498                                                                 buf[0]= sqrt(buf[0]);   // invers gamma 2.0
499                                                                 buf[1]= sqrt(buf[1]);
500                                                                 buf[2]= sqrt(buf[2]);
501                                                         }
502                                                         didgamma= 1;
503                                                 }
504                                                 
505                                                 flarec= har->flarec;    /* har->pixels is only allowed to count once */
506                                                 
507                                                 if(*rd) {                               /* theres a pixel struct */
508                                                         
509                                                         ps= (PixStr *)(*rd);
510                                                         amount= 0;
511                                                         accol[0]=accol[1]=accol[2]=accol[3]= 0.0;
512                                                         
513                                                         while(ps) {
514                                                                 amountm= count_mask(ps->mask);
515                                                                 amount+= amountm;
516
517                                                                 zz= calchalo_z(har, ps->z);
518                                                                 if(zz> har->zs) {
519                                                                         float fac;
520                                                                         
521                                                                         shadeHaloFloat(har, col, zz, dist, xn, yn, flarec);
522                                                                         fac= ((float)amountm)/(float)R.osa;
523                                                                         accol[0]+= fac*col[0];
524                                                                         accol[1]+= fac*col[1];
525                                                                         accol[2]+= fac*col[2];
526                                                                         accol[3]+= fac*col[3];
527                                                                         flarec= 0;
528                                                                 }
529
530                                                                 ps= ps->next;
531                                                         }
532                                                         /* now do the sky sub-pixels */
533                                                         amount= R.osa-amount;
534                                                         if(amount) {
535                                                                 float fac;
536
537                                                                 shadeHaloFloat(har, col, 0x7FFFFF, dist, xn, yn, flarec);
538                                                                 fac= ((float)amount)/(float)R.osa;
539                                                                 accol[0]+= fac*col[0];
540                                                                 accol[1]+= fac*col[1];
541                                                                 accol[2]+= fac*col[2];
542                                                                 accol[3]+= fac*col[3];
543                                                         }
544                                                         col[0]= accol[0];
545                                                         col[1]= accol[1];
546                                                         col[2]= accol[2];
547                                                         col[3]= accol[3];
548
549                                                         addalphaAddfacFloat(rb, col, har->add);
550                                                 }
551                                                 else {
552                                                         zz= calchalo_z(har, *rz);
553                                                         if(zz> har->zs) {
554
555                                                                 shadeHaloFloat(har, col, zz, dist, xn, yn, flarec);
556                                                                 addalphaAddfacFloat(rb, col, har->add);
557                                                         }
558                                                 }
559                                         }
560                                         rb+=4;
561                                         rz++;
562                                         rd++;
563                                 }
564                         }
565                 }
566         }
567
568         /* the entire scanline has to be put back in gammaspace */
569         if(didgamma) {
570                 float *buf= rowbuf;
571                 int xt;
572                 for(xt=0; xt<R.rectx; xt++, buf+=4) {
573                         buf[0]*= (buf[0]);      // gamma 2.0
574                         buf[1]*= (buf[1]);
575                         buf[2]*= (buf[2]);
576                 }
577         }
578
579 }
580
581 static void scanlinehalo(int *rectz, float *rowbuf, short ys)
582 {
583         HaloRen *har = NULL;
584         float dist, xsq, ysq, xn, yn, *rb;
585         float col[4];
586         int a, *rz, zz;
587         short minx, maxx, x;
588
589         for(a=0; a<R.tothalo; a++) {
590                 if((a & 255)==0) har= R.bloha[a>>8];
591                 else har++;
592
593                 if(RE_local_test_break() ) break; 
594
595                 if(ys>har->maxy);
596                 else if(ys<har->miny);
597                 else {
598                         minx= floor(har->xs-har->rad);
599                         maxx= ceil(har->xs+har->rad);
600                         
601                         if(maxx<0);
602                         else if(R.rectx<minx);
603                         else {
604                                 if(minx<0) minx= 0;
605                                 if(maxx>=R.rectx) maxx= R.rectx-1;
606
607                                 rb= rowbuf + 4*minx;
608                                 rz= rectz + minx;
609
610                                 yn= (ys-har->ys)*R.ycor;
611                                 ysq= yn*yn;
612                                 for(x=minx; x<=maxx; x++) {
613                                 
614                                         zz= calchalo_z(har, *rz);
615                                         if(zz> har->zs) {
616                                                 xn= x- har->xs;
617                                                 xsq= xn*xn;
618                                                 dist= xsq+ysq;
619                                                 if(dist<har->radsq) {
620                                                         shadeHaloFloat(har, col, zz, dist, xn, yn, har->flarec);
621                                                         addalphaAddfacFloat(rb, col, har->add);
622                                                 }
623                                         }
624
625                                         rb+=4;
626                                         rz++;
627                                 }
628                         }
629                 }
630         }
631 }
632
633 /* ---------------- shaders ----------------------- */
634
635 static double Normalise_d(double *n)
636 {
637         double d;
638         
639         d= n[0]*n[0]+n[1]*n[1]+n[2]*n[2];
640
641         if(d>0.00000000000000001) {
642                 d= sqrt(d);
643
644                 n[0]/=d; 
645                 n[1]/=d; 
646                 n[2]/=d;
647         } else {
648                 n[0]=n[1]=n[2]= 0.0;
649                 d= 0.0;
650         }
651         return d;
652 }
653
654 /* mix of 'real' fresnel and allowing control. grad defines blending gradient */
655 float fresnel_fac(float *view, float *vn, float grad, float fac)
656 {
657         float t1, t2;
658         
659         if(fac==0.0) return 1.0;
660         
661         t1= (view[0]*vn[0] + view[1]*vn[1] + view[2]*vn[2]);
662         if(t1>0.0)  t2= 1.0+t1;
663         else t2= 1.0-t1;
664         
665         t2= grad + (1.0-grad)*pow(t2, fac);
666         
667         if(t2<0.0) return 0.0;
668         else if(t2>1.0) return 1.0;
669         return t2;
670 }
671
672 static double saacos_d(double fac)
673 {
674         if(fac<= -1.0f) return M_PI;
675         else if(fac>=1.0f) return 0.0;
676         else return acos(fac);
677 }
678
679 /* Stoke's form factor. Need doubles here for extreme small area sizes */
680 static float area_lamp_energy(float *co, float *vn, LampRen *lar)
681 {
682         double fac;
683         double vec[4][3];       /* vectors of rendered co to vertices lamp */
684         double cross[4][3];     /* cross products of this */
685         double rad[4];          /* angles between vecs */
686
687         VECSUB(vec[0], co, lar->area[0]);
688         VECSUB(vec[1], co, lar->area[1]);
689         VECSUB(vec[2], co, lar->area[2]);
690         VECSUB(vec[3], co, lar->area[3]);
691         
692         Normalise_d(vec[0]);
693         Normalise_d(vec[1]);
694         Normalise_d(vec[2]);
695         Normalise_d(vec[3]);
696
697         /* cross product */
698         CROSS(cross[0], vec[0], vec[1]);
699         CROSS(cross[1], vec[1], vec[2]);
700         CROSS(cross[2], vec[2], vec[3]);
701         CROSS(cross[3], vec[3], vec[0]);
702
703         Normalise_d(cross[0]);
704         Normalise_d(cross[1]);
705         Normalise_d(cross[2]);
706         Normalise_d(cross[3]);
707
708         /* angles */
709         rad[0]= vec[0][0]*vec[1][0]+ vec[0][1]*vec[1][1]+ vec[0][2]*vec[1][2];
710         rad[1]= vec[1][0]*vec[2][0]+ vec[1][1]*vec[2][1]+ vec[1][2]*vec[2][2];
711         rad[2]= vec[2][0]*vec[3][0]+ vec[2][1]*vec[3][1]+ vec[2][2]*vec[3][2];
712         rad[3]= vec[3][0]*vec[0][0]+ vec[3][1]*vec[0][1]+ vec[3][2]*vec[0][2];
713
714         rad[0]= saacos_d(rad[0]);
715         rad[1]= saacos_d(rad[1]);
716         rad[2]= saacos_d(rad[2]);
717         rad[3]= saacos_d(rad[3]);
718
719         /* Stoke formula */
720         fac=  rad[0]*(vn[0]*cross[0][0]+ vn[1]*cross[0][1]+ vn[2]*cross[0][2]);
721         fac+= rad[1]*(vn[0]*cross[1][0]+ vn[1]*cross[1][1]+ vn[2]*cross[1][2]);
722         fac+= rad[2]*(vn[0]*cross[2][0]+ vn[1]*cross[2][1]+ vn[2]*cross[2][2]);
723         fac+= rad[3]*(vn[0]*cross[3][0]+ vn[1]*cross[3][1]+ vn[2]*cross[3][2]);
724
725         if(fac<=0.0) return 0.0;
726         return pow(fac*lar->areasize, lar->k);  // corrected for buttons size and lar->dist^2
727 }
728
729 float spec(float inp, int hard) 
730 {
731         float b1;
732         
733         if(inp>=1.0) return 1.0;
734         else if (inp<=0.0) return 0.0;
735         
736         b1= inp*inp;
737         /* avoid FPE */
738         if(b1<0.01) b1= 0.01;   
739         
740         if((hard & 1)==0)  inp= 1.0;
741         if(hard & 2)  inp*= b1;
742         b1*= b1;
743         if(hard & 4)  inp*= b1;
744         b1*= b1;
745         if(hard & 8)  inp*= b1;
746         b1*= b1;
747         if(hard & 16) inp*= b1;
748         b1*= b1;
749
750         /* avoid FPE */
751         if(b1<0.001) b1= 0.0;   
752
753         if(hard & 32) inp*= b1;
754         b1*= b1;
755         if(hard & 64) inp*=b1;
756         b1*= b1;
757         if(hard & 128) inp*=b1;
758
759         if(b1<0.001) b1= 0.0;   
760
761         if(hard & 256) {
762                 b1*= b1;
763                 inp*=b1;
764         }
765
766         return inp;
767 }
768
769 float Phong_Spec( float *n, float *l, float *v, int hard, int tangent )
770 {
771         float h[3];
772         float rslt;
773         
774         h[0] = l[0] + v[0];
775         h[1] = l[1] + v[1];
776         h[2] = l[2] + v[2];
777         Normalise(h);
778         
779         rslt = h[0]*n[0] + h[1]*n[1] + h[2]*n[2];
780         if(tangent) rslt= sasqrt(1.0 - rslt*rslt);
781                 
782         if( rslt > 0.0 ) rslt= spec(rslt, hard);
783         else rslt = 0.0;
784         
785         return rslt;
786 }
787
788
789 /* reduced cook torrance spec (for off-specular peak) */
790 float CookTorr_Spec(float *n, float *l, float *v, int hard, int tangent)
791 {
792         float i, nh, nv, h[3];
793
794         h[0]= v[0]+l[0];
795         h[1]= v[1]+l[1];
796         h[2]= v[2]+l[2];
797         Normalise(h);
798
799         nh= n[0]*h[0]+n[1]*h[1]+n[2]*h[2];
800         if(tangent) nh= sasqrt(1.0 - nh*nh);
801         else if(nh<0.0) return 0.0;
802         
803         nv= n[0]*v[0]+n[1]*v[1]+n[2]*v[2];
804         if(tangent) nv= sasqrt(1.0 - nv*nv);
805         else if(nv<0.0) nv= 0.0;
806
807         i= spec(nh, hard);
808
809         i= i/(0.1+nv);
810         return i;
811 }
812
813 /* Blinn spec */
814 float Blinn_Spec(float *n, float *l, float *v, float refrac, float spec_power, int tangent)
815 {
816         float i, nh, nv, nl, vh, h[3];
817         float a, b, c, g=0.0, p, f, ang;
818
819         if(refrac < 1.0) return 0.0;
820         if(spec_power == 0.0) return 0.0;
821         
822         /* conversion from 'hardness' (1-255) to 'spec_power' (50 maps at 0.1) */
823         if(spec_power<100.0)
824                 spec_power= sqrt(1.0/spec_power);
825         else spec_power= 10.0/spec_power;
826         
827         h[0]= v[0]+l[0];
828         h[1]= v[1]+l[1];
829         h[2]= v[2]+l[2];
830         Normalise(h);
831
832         nh= n[0]*h[0]+n[1]*h[1]+n[2]*h[2]; /* Dot product between surface normal and half-way vector */
833         if(tangent) nh= sasqrt(1.0f - nh*nh);
834         else if(nh<0.0) return 0.0;
835
836         nv= n[0]*v[0]+n[1]*v[1]+n[2]*v[2]; /* Dot product between surface normal and view vector */
837         if(tangent) nv= sasqrt(1.0f - nv*nv);
838         if(nv<=0.0) nv= 0.01;                           /* hrms... */
839
840         nl= n[0]*l[0]+n[1]*l[1]+n[2]*l[2]; /* Dot product between surface normal and light vector */
841         if(tangent) nl= sasqrt(1.0f - nl*nl);
842         if(nl<=0.0) {
843                 return 0.0;
844         }
845
846         vh= v[0]*h[0]+v[1]*h[1]+v[2]*h[2]; /* Dot product between view vector and half-way vector */
847         if(vh<=0.0) vh= 0.01;
848
849         a = 1.0;
850         b = (2.0*nh*nv)/vh;
851         c = (2.0*nh*nl)/vh;
852
853         if( a < b && a < c ) g = a;
854         else if( b < a && b < c ) g = b;
855         else if( c < a && c < b ) g = c;
856
857         p = sqrt( (double)((refrac * refrac)+(vh*vh)-1.0) );
858         f = (((p-vh)*(p-vh))/((p+vh)*(p+vh)))*(1+((((vh*(p+vh))-1.0)*((vh*(p+vh))-1.0))/(((vh*(p-vh))+1.0)*((vh*(p-vh))+1.0))));
859         ang = saacos(nh);
860
861         i= f * g * exp((double)(-(ang*ang) / (2.0*spec_power*spec_power)));
862         if(i<0.0) i= 0.0;
863         
864         return i;
865 }
866
867 /* cartoon render spec */
868 float Toon_Spec( float *n, float *l, float *v, float size, float smooth, int tangent)
869 {
870         float h[3];
871         float ang;
872         float rslt;
873         
874         h[0] = l[0] + v[0];
875         h[1] = l[1] + v[1];
876         h[2] = l[2] + v[2];
877         Normalise(h);
878         
879         rslt = h[0]*n[0] + h[1]*n[1] + h[2]*n[2];
880         if(tangent) rslt = sasqrt(1.0f - rslt*rslt);
881         
882         ang = saacos( rslt ); 
883         
884         if( ang < size ) rslt = 1.0;
885         else if( ang >= (size + smooth) || smooth == 0.0 ) rslt = 0.0;
886         else rslt = 1.0 - ((ang - size) / smooth);
887         
888         return rslt;
889 }
890
891 /* Ward isotropic gaussian spec */
892 float WardIso_Spec( float *n, float *l, float *v, float rms, int tangent)
893 {
894         float i, nh, nv, nl, h[3], angle, alpha;
895
896
897         /* half-way vector */
898         h[0] = l[0] + v[0];
899         h[1] = l[1] + v[1];
900         h[2] = l[2] + v[2];
901         Normalise(h);
902
903         nh = n[0]*h[0]+n[1]*h[1]+n[2]*h[2]; /* Dot product between surface normal and half-way vector */
904         if(tangent) nh = sasqrt(1.0f - nh*nh);
905         if(nh<=0.0) nh = 0.001f;
906         
907         nv = n[0]*v[0]+n[1]*v[1]+n[2]*v[2]; /* Dot product between surface normal and view vector */
908         if(tangent) nv = sasqrt(1.0f - nv*nv);
909         if(nv<=0.0) nv = 0.001f;
910
911         nl = n[0]*l[0]+n[1]*l[1]+n[2]*l[2]; /* Dot product between surface normal and light vector */
912         if(tangent) nl = sasqrt(1.0f - nl*nl);
913         if(nl<=0.0) nl = 0.001;
914
915         angle = tan(saacos(nh));
916         alpha = MAX2(rms,0.001);
917
918         i= nl * (1.0/(4*PI*alpha*alpha)) * (exp( -(angle*angle)/(alpha*alpha))/(sqrt(nv*nl)));
919
920         return i;
921 }
922
923 /* cartoon render diffuse */
924 float Toon_Diff( float *n, float *l, float *v, float size, float smooth )
925 {
926         float rslt, ang;
927
928         rslt = n[0]*l[0] + n[1]*l[1] + n[2]*l[2];
929
930         ang = saacos( (double)(rslt) );
931
932         if( ang < size ) rslt = 1.0;
933         else if( ang >= (size + smooth) || smooth == 0.0 ) rslt = 0.0;
934         else rslt = 1.0 - ((ang - size) / smooth);
935
936         return rslt;
937 }
938
939 /* Oren Nayar diffuse */
940
941 /* 'nl' is either dot product, or return value of area light */
942 /* in latter case, only last multiplication uses 'nl' */
943 static float OrenNayar_Diff_i(float nl, float *n, float *l, float *v, float rough )
944 {
945         float i, nh, nv, vh, realnl, h[3];
946         float a, b, t, A, B;
947         float Lit_A, View_A, Lit_B[3], View_B[3];
948         
949         h[0]= v[0]+l[0];
950         h[1]= v[1]+l[1];
951         h[2]= v[2]+l[2];
952         Normalise(h);
953         
954         nh= n[0]*h[0]+n[1]*h[1]+n[2]*h[2]; /* Dot product between surface normal and half-way vector */
955         if(nh<0.0) nh = 0.0;
956         
957         nv= n[0]*v[0]+n[1]*v[1]+n[2]*v[2]; /* Dot product between surface normal and view vector */
958         if(nv<=0.0) nv= 0.0;
959         
960         realnl= n[0]*l[0]+n[1]*l[1]+n[2]*l[2]; /* Dot product between surface normal and light vector */
961         if(realnl<=0.0) return 0.0;
962         if(nl<0.0) return 0.0;          /* value from area light */
963         
964         vh= v[0]*h[0]+v[1]*h[1]+v[2]*h[2]; /* Dot product between view vector and halfway vector */
965         if(vh<=0.0) vh= 0.0;
966         
967         Lit_A = saacos(realnl);
968         View_A = saacos( nv );
969         
970         Lit_B[0] = l[0] - (realnl * n[0]);
971         Lit_B[1] = l[1] - (realnl * n[1]);
972         Lit_B[2] = l[2] - (realnl * n[2]);
973         Normalise( Lit_B );
974         
975         View_B[0] = v[0] - (nv * n[0]);
976         View_B[1] = v[1] - (nv * n[1]);
977         View_B[2] = v[2] - (nv * n[2]);
978         Normalise( View_B );
979         
980         t = Lit_B[0]*View_B[0] + Lit_B[1]*View_B[1] + Lit_B[2]*View_B[2];
981         if( t < 0 ) t = 0;
982         
983         if( Lit_A > View_A ) {
984                 a = Lit_A;
985                 b = View_A;
986         }
987         else {
988                 a = View_A;
989                 b = Lit_A;
990         }
991         
992         A = 1 - (0.5 * ((rough * rough) / ((rough * rough) + 0.33)));
993         B = 0.45 * ((rough * rough) / ((rough * rough) + 0.09));
994         
995         b*= 0.95;       /* prevent tangens from shooting to inf, 'nl' can be not a dot product here. */
996                                 /* overflow only happens with extreme size area light, and higher roughness */
997         i = nl * ( A + ( B * t * sin(a) * tan(b) ) );
998         
999         return i;
1000 }
1001
1002 /* Oren Nayar diffuse */
1003 float OrenNayar_Diff(float *n, float *l, float *v, float rough )
1004 {
1005         float nl= n[0]*l[0] + n[1]*l[1] + n[2]*l[2];
1006         return OrenNayar_Diff_i(nl, n, l, v, rough);
1007 }
1008
1009 /* Minnaert diffuse */
1010 float Minnaert_Diff(float nl, float *n, float *v, float darkness)
1011 {
1012
1013         float i, nv;
1014
1015         /* nl = dot product between surface normal and light vector */
1016         if (nl <= 0.0)
1017                 return 0;
1018
1019         /* nv = dot product between surface normal and view vector */
1020         nv = n[0]*v[0]+n[1]*v[1]+n[2]*v[2];
1021         if (nv < 0.0)
1022                 nv = 0;
1023
1024         if (darkness <= 1)
1025                 i = nl * pow(MAX2(nv*nl, 0.1), (darkness - 1) ); /*The Real model*/
1026         else
1027                 i = nl * pow( (1.001 - nv), (darkness  - 1) ); /*Nvidia model*/
1028
1029         return i;
1030 }
1031
1032 float Fresnel_Diff(float *vn, float *lv, float *view, float fac_i, float fac)
1033 {
1034         return fresnel_fac(lv, vn, fac_i, fac);
1035 }
1036
1037 /* --------------------------------------------- */
1038 /* also called from texture.c */
1039 void calc_R_ref(ShadeInput *shi)
1040 {
1041         float i;
1042
1043         /* shi->vn dot shi->view */
1044         i= -2*(shi->vn[0]*shi->view[0]+shi->vn[1]*shi->view[1]+shi->vn[2]*shi->view[2]);
1045
1046         shi->ref[0]= (shi->view[0]+i*shi->vn[0]);
1047         shi->ref[1]= (shi->view[1]+i*shi->vn[1]);
1048         shi->ref[2]= (shi->view[2]+i*shi->vn[2]);
1049         if(shi->osatex) {
1050                 if(shi->vlr->flag & R_SMOOTH) {
1051                         i= -2*( (shi->vn[0]+shi->dxno[0])*(shi->view[0]+shi->dxview) +
1052                                 (shi->vn[1]+shi->dxno[1])*shi->view[1]+ (shi->vn[2]+shi->dxno[2])*shi->view[2] );
1053
1054                         shi->dxref[0]= shi->ref[0]- ( shi->view[0]+shi->dxview+i*(shi->vn[0]+shi->dxno[0]));
1055                         shi->dxref[1]= shi->ref[1]- (shi->view[1]+ i*(shi->vn[1]+shi->dxno[1]));
1056                         shi->dxref[2]= shi->ref[2]- (shi->view[2]+ i*(shi->vn[2]+shi->dxno[2]));
1057
1058                         i= -2*( (shi->vn[0]+shi->dyno[0])*shi->view[0]+
1059                                 (shi->vn[1]+shi->dyno[1])*(shi->view[1]+shi->dyview)+ (shi->vn[2]+shi->dyno[2])*shi->view[2] );
1060
1061                         shi->dyref[0]= shi->ref[0]- (shi->view[0]+ i*(shi->vn[0]+shi->dyno[0]));
1062                         shi->dyref[1]= shi->ref[1]- (shi->view[1]+shi->dyview+i*(shi->vn[1]+shi->dyno[1]));
1063                         shi->dyref[2]= shi->ref[2]- (shi->view[2]+ i*(shi->vn[2]+shi->dyno[2]));
1064
1065                 }
1066                 else {
1067
1068                         i= -2*( shi->vn[0]*(shi->view[0]+shi->dxview) +
1069                                 shi->vn[1]*shi->view[1]+ shi->vn[2]*shi->view[2] );
1070
1071                         shi->dxref[0]= shi->ref[0]- (shi->view[0]+shi->dxview+i*shi->vn[0]);
1072                         shi->dxref[1]= shi->ref[1]- (shi->view[1]+ i*shi->vn[1]);
1073                         shi->dxref[2]= shi->ref[2]- (shi->view[2]+ i*shi->vn[2]);
1074
1075                         i= -2*( shi->vn[0]*shi->view[0]+
1076                                 shi->vn[1]*(shi->view[1]+shi->dyview)+ shi->vn[2]*shi->view[2] );
1077
1078                         shi->dyref[0]= shi->ref[0]- (shi->view[0]+ i*shi->vn[0]);
1079                         shi->dyref[1]= shi->ref[1]- (shi->view[1]+shi->dyview+i*shi->vn[1]);
1080                         shi->dyref[2]= shi->ref[2]- (shi->view[2]+ i*shi->vn[2]);
1081                 }
1082         }
1083
1084 }
1085
1086 void shade_color(ShadeInput *shi, ShadeResult *shr)
1087 {
1088         Material *ma= shi->mat;
1089
1090         if(ma->mode & (MA_VERTEXCOLP|MA_FACETEXTURE)) {
1091                 shi->r= shi->vcol[0];
1092                 shi->g= shi->vcol[1];
1093                 shi->b= shi->vcol[2];
1094         }
1095         
1096         if(ma->texco) {
1097                 if(ma->mode & (MA_VERTEXCOLP|MA_FACETEXTURE)) {
1098                         shi->r= shi->vcol[0];
1099                         shi->g= shi->vcol[1];
1100                         shi->b= shi->vcol[2];
1101                 }
1102                 do_material_tex(shi);
1103         }
1104
1105         if(ma->mode & (MA_ZTRA|MA_RAYTRANSP)) {
1106                 if(ma->fresnel_tra!=0.0) 
1107                         shi->alpha*= fresnel_fac(shi->view, shi->vn, ma->fresnel_tra_i, ma->fresnel_tra);
1108         }
1109
1110         shr->diff[0]= shi->r;
1111         shr->diff[1]= shi->g;
1112         shr->diff[2]= shi->b;
1113         shr->alpha= shi->alpha;
1114 }
1115
1116 /* r g b = current value, col = new value, fac==0 is no change */
1117 /* if g==NULL, it only does r channel */
1118 void ramp_blend(int type, float *r, float *g, float *b, float fac, float *col)
1119 {
1120         float tmp, facm= 1.0-fac;
1121         
1122         switch (type) {
1123         case MA_RAMP_BLEND:
1124                 *r = facm*(*r) + fac*col[0];
1125                 if(g) {
1126                         *g = facm*(*g) + fac*col[1];
1127                         *b = facm*(*b) + fac*col[2];
1128                 }
1129                 break;
1130         case MA_RAMP_ADD:
1131                 *r += fac*col[0];
1132                 if(g) {
1133                         *g += fac*col[1];
1134                         *b += fac*col[2];
1135                 }
1136                 break;
1137         case MA_RAMP_MULT:
1138                 *r *= (facm + fac*col[0]);
1139                 if(g) {
1140                         *g *= (facm + fac*col[1]);
1141                         *b *= (facm + fac*col[2]);
1142                 }
1143                 break;
1144         case MA_RAMP_SCREEN:
1145                 *r = 1.0 - (facm + fac*(1.0 - col[0])) * (1.0 - *r);
1146                 if(g) {
1147                         *g = 1.0 - (facm + fac*(1.0 - col[1])) * (1.0 - *g);
1148                         *b = 1.0 - (facm + fac*(1.0 - col[2])) * (1.0 - *b);
1149                 }
1150                 break;
1151         case MA_RAMP_SUB:
1152                 *r -= fac*col[0];
1153                 if(g) {
1154                         *g -= fac*col[1];
1155                         *b -= fac*col[2];
1156                 }
1157                 break;
1158         case MA_RAMP_DIV:
1159                 if(col[0]!=0.0)
1160                         *r = facm*(*r) + fac*(*r)/col[0];
1161                 if(g) {
1162                         if(col[1]!=0.0)
1163                                 *g = facm*(*g) + fac*(*g)/col[1];
1164                         if(col[2]!=0.0)
1165                                 *b = facm*(*b) + fac*(*b)/col[2];
1166                 }
1167                 break;
1168         case MA_RAMP_DIFF:
1169                 *r = facm*(*r) + fac*fabs(*r-col[0]);
1170                 if(g) {
1171                         *g = facm*(*g) + fac*fabs(*g-col[1]);
1172                         *b = facm*(*b) + fac*fabs(*b-col[2]);
1173                 }
1174                 break;
1175         case MA_RAMP_DARK:
1176                 tmp= fac*col[0];
1177                 if(tmp < *r) *r= tmp; 
1178                 if(g) {
1179                         tmp= fac*col[1];
1180                         if(tmp < *g) *g= tmp; 
1181                         tmp= fac*col[2];
1182                         if(tmp < *b) *b= tmp; 
1183                         }
1184                 break;
1185         case MA_RAMP_LIGHT:
1186                 tmp= fac*col[0];
1187                 if(tmp > *r) *r= tmp; 
1188                 if(g) {
1189                         tmp= fac*col[1];
1190                         if(tmp > *g) *g= tmp; 
1191                         tmp= fac*col[2];
1192                         if(tmp > *b) *b= tmp; 
1193                 }
1194                 break;
1195         }
1196
1197 }
1198
1199 /* ramp for at end of shade */
1200 void ramp_diffuse_result(float *diff, ShadeInput *shi)
1201 {
1202         Material *ma= shi->mat;
1203         float col[4], fac=0;
1204
1205         if(ma->ramp_col) {
1206                 if(ma->rampin_col==MA_RAMP_IN_RESULT) {
1207                         
1208                         fac= 0.3*diff[0] + 0.58*diff[1] + 0.12*diff[2];
1209                         do_colorband(ma->ramp_col, fac, col);
1210                         
1211                         /* blending method */
1212                         fac= col[3]*ma->rampfac_col;
1213                         
1214                         ramp_blend(ma->rampblend_col, diff, diff+1, diff+2, fac, col);
1215                 }
1216         }
1217 }
1218
1219 /* r,g,b denote energy, ramp is used with different values to make new material color */
1220 void add_to_diffuse(float *diff, ShadeInput *shi, float is, float r, float g, float b)
1221 {
1222         Material *ma= shi->mat;
1223         float col[4], colt[3], fac=0;
1224         
1225         if(ma->ramp_col && (ma->mode & MA_RAMP_COL)) {
1226                 
1227                 /* MA_RAMP_IN_RESULT is exceptional */
1228                 if(ma->rampin_col==MA_RAMP_IN_RESULT) {
1229                         // normal add
1230                         diff[0] += r * shi->r;
1231                         diff[1] += g * shi->g;
1232                         diff[2] += b * shi->b;
1233                 }
1234                 else {
1235                         /* input */
1236                         switch(ma->rampin_col) {
1237                         case MA_RAMP_IN_ENERGY:
1238                                 fac= 0.3*r + 0.58*g + 0.12*b;
1239                                 break;
1240                         case MA_RAMP_IN_SHADER:
1241                                 fac= is;
1242                                 break;
1243                         case MA_RAMP_IN_NOR:
1244                                 fac= shi->view[0]*shi->vn[0] + shi->view[1]*shi->vn[1] + shi->view[2]*shi->vn[2];
1245                                 break;
1246                         }
1247         
1248                         do_colorband(ma->ramp_col, fac, col);
1249                         
1250                         /* blending method */
1251                         fac= col[3]*ma->rampfac_col;
1252                         colt[0]= shi->r; colt[1]= shi->g; colt[2]= shi->b;
1253
1254                         ramp_blend(ma->rampblend_col, colt, colt+1, colt+2, fac, col);
1255
1256                         /* output to */
1257                         diff[0] += r * colt[0];
1258                         diff[1] += g * colt[1];
1259                         diff[2] += b * colt[2];
1260                 }
1261         }
1262         else {
1263                 diff[0] += r * shi->r;
1264                 diff[1] += g * shi->g;
1265                 diff[2] += b * shi->b;
1266         }
1267 }
1268
1269 void ramp_spec_result(float *specr, float *specg, float *specb, ShadeInput *shi)
1270 {
1271         Material *ma= shi->mat;
1272         float col[4];
1273         float fac;
1274         
1275         if(ma->ramp_spec && (ma->rampin_spec==MA_RAMP_IN_RESULT)) {
1276                 fac= 0.3*(*specr) + 0.58*(*specg) + 0.12*(*specb);
1277                 do_colorband(ma->ramp_spec, fac, col);
1278                 
1279                 /* blending method */
1280                 fac= col[3]*ma->rampfac_spec;
1281                 
1282                 ramp_blend(ma->rampblend_spec, specr, specg, specb, fac, col);
1283                 
1284         }
1285 }
1286
1287 /* is = dot product shade, t = spec energy */
1288 void do_specular_ramp(ShadeInput *shi, float is, float t, float *spec)
1289 {
1290         Material *ma= shi->mat;
1291         float col[4];
1292         float fac=0.0;
1293         
1294         spec[0]= shi->specr;
1295         spec[1]= shi->specg;
1296         spec[2]= shi->specb;
1297
1298         /* MA_RAMP_IN_RESULT is exception */
1299         if(ma->ramp_spec && (ma->rampin_spec!=MA_RAMP_IN_RESULT)) {
1300                 
1301                 /* input */
1302                 switch(ma->rampin_spec) {
1303                 case MA_RAMP_IN_ENERGY:
1304                         fac= t;
1305                         break;
1306                 case MA_RAMP_IN_SHADER:
1307                         fac= is;
1308                         break;
1309                 case MA_RAMP_IN_NOR:
1310                         fac= shi->view[0]*shi->vn[0] + shi->view[1]*shi->vn[1] + shi->view[2]*shi->vn[2];
1311                         break;
1312                 }
1313                 
1314                 do_colorband(ma->ramp_spec, fac, col);
1315                 
1316                 /* blending method */
1317                 fac= col[3]*ma->rampfac_spec;
1318                 
1319                 ramp_blend(ma->rampblend_spec, spec, spec+1, spec+2, fac, col);
1320         }
1321 }
1322
1323
1324
1325 static void ambient_occlusion(World *wrld, ShadeInput *shi, ShadeResult *shr)
1326 {
1327         float f, shadfac[4];
1328         
1329         if((wrld->mode & WO_AMB_OCC) && (R.r.mode & R_RAYTRACE) && shi->amb!=0.0) {
1330                 ray_ao(shi, wrld, shadfac);
1331
1332                 if(wrld->aocolor==WO_AOPLAIN) {
1333                         if (wrld->aomix==WO_AOADDSUB) shadfac[3] = 2.0*shadfac[3]-1.0;
1334                         else if (wrld->aomix==WO_AOSUB) shadfac[3] = shadfac[3]-1.0;
1335
1336                         f= wrld->aoenergy*shadfac[3]*shi->amb;
1337                         add_to_diffuse(shr->diff, shi, f, f, f, f);
1338                 }
1339                 else {
1340                         if (wrld->aomix==WO_AOADDSUB) {
1341                                 shadfac[0] = 2.0*shadfac[0]-1.0;
1342                                 shadfac[1] = 2.0*shadfac[1]-1.0;
1343                                 shadfac[2] = 2.0*shadfac[2]-1.0;
1344                         }
1345                         else if (wrld->aomix==WO_AOSUB) {
1346                                 shadfac[0] = shadfac[0]-1.0;
1347                                 shadfac[1] = shadfac[1]-1.0;
1348                                 shadfac[2] = shadfac[2]-1.0;
1349                         }
1350                         f= wrld->aoenergy*shi->amb;
1351                         add_to_diffuse(shr->diff, shi, f, f*shadfac[0], f*shadfac[1], f*shadfac[2]);
1352                 }
1353         }
1354 }
1355
1356 void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
1357 {
1358         LampRen *lar;
1359         GroupObject *go;
1360         Material *ma= shi->mat;
1361         VlakRen *vlr= shi->vlr;
1362         ListBase *lights;
1363         float i, inp, inpr, is, t, lv[3], vnor[3], lacol[3], lampdist, ld = 0;
1364         float lvrot[3], *vn, *view, shadfac[4], soft, phongcorr;        // shadfac = rgba
1365
1366         vn= shi->vn;
1367         view= shi->view;
1368         
1369         memset(shr, 0, sizeof(ShadeResult));
1370         
1371         /* copy all relevant material vars, note, keep this synced with render_types.h */
1372         memcpy(&shi->r, &ma->r, 23*sizeof(float));
1373         /* set special cases */
1374         shi->har= ma->har;
1375         if((ma->mode & MA_RAYMIRROR)==0) shi->ray_mirror= 0.0;
1376         
1377         /* lights */
1378         if(ma->group)
1379                 lights= &ma->group->gobject;
1380         else
1381                 lights= &R.lights;
1382         
1383         /* separate loop */
1384         if(ma->mode & MA_ONLYSHADOW) {
1385                 float ir;
1386                 
1387                 if(R.r.mode & R_SHADOW) {
1388                         
1389                         shadfac[3]= ir= 0.0;
1390                         for(go=lights->first; go; go= go->next) {
1391                                 lar= go->lampren;
1392                                 if(lar==NULL) continue;
1393                                 
1394                                 /* yafray: ignore shading by photonlights, not used in Blender */
1395                                 if (lar->type==LA_YF_PHOTON) continue;
1396                                 
1397                                 if(lar->mode & LA_LAYER) if((lar->lay & vlr->lay)==0) continue;
1398                                 
1399                                 lv[0]= shi->co[0]-lar->co[0];
1400                                 lv[1]= shi->co[1]-lar->co[1];
1401                                 lv[2]= shi->co[2]-lar->co[2];
1402
1403                                 if(lar->type==LA_SPOT) {
1404                                         /* only test within spotbundel */
1405                                         if(lar->shb || (lar->mode & LA_SHAD_RAY)) {
1406
1407                                                 Normalise(lv);
1408                                                 inpr= lv[0]*lar->vec[0]+lv[1]*lar->vec[1]+lv[2]*lar->vec[2];
1409                                                 if(inpr>lar->spotsi) {
1410                                                         
1411                                                         inp= vn[0]*lv[0] + vn[1]*lv[1] + vn[2]*lv[2];
1412                                                         
1413                                                         if(lar->shb) i = testshadowbuf(lar->shb, shi->co, shi->dxco, shi->dyco, inp);
1414                                                         else {
1415                                                                 float shad[4];
1416                                                                 ray_shadow(shi, lar, shad);
1417                                                                 i= shad[3];
1418                                                         }
1419                                                         
1420                                                         t= inpr - lar->spotsi;
1421                                                         if(t<lar->spotbl && lar->spotbl!=0.0) {
1422                                                                 t/= lar->spotbl;
1423                                                                 t*= t;
1424                                                                 i= t*i+(1.0-t);
1425                                                         }
1426                                                         
1427                                                         shadfac[3]+= i;
1428                                                         ir+= 1.0;
1429                                                 }
1430                                                 else {
1431                                                         shadfac[3]+= 1.0;
1432                                                         ir+= 1.0;
1433                                                 }
1434                                         }
1435                                 }
1436                                 else if(lar->mode & LA_SHAD_RAY) {
1437                                         float shad[4];
1438                                         
1439                                         /* single sided? */
1440                                         if( shi->facenor[0]*lv[0] + shi->facenor[1]*lv[1] + shi->facenor[2]*lv[2] > -0.01) {
1441                                                 ray_shadow(shi, lar, shad);
1442                                                 shadfac[3]+= shad[3];
1443                                                 ir+= 1.0;
1444                                         }
1445                                 }
1446
1447                         }
1448                         if(ir>0.0) {
1449                                 shadfac[3]/= ir;
1450                                 shr->alpha= (shi->alpha)*(1.0-shadfac[3]);
1451                         }
1452                 }
1453                 
1454                 if((R.wrld.mode & WO_AMB_OCC) && (R.r.mode & R_RAYTRACE) && shi->amb!=0.0) {
1455                         float f;
1456
1457                         ray_ao(shi, &R.wrld, shadfac);  // shadfac==0: full light
1458                         shadfac[3]= 1.0-shadfac[3];
1459                         
1460                         f= R.wrld.aoenergy*shadfac[3]*shi->amb;
1461                         
1462                         if(R.wrld.aomix==WO_AOADD) {
1463                                 shr->alpha += f;
1464                                 shr->alpha *= f;
1465                         }
1466                         else if(R.wrld.aomix==WO_AOSUB) {
1467                                 shr->alpha += f;
1468                         }
1469                         else {
1470                                 shr->alpha *= f;
1471                                 shr->alpha += f;
1472                         }
1473                 }
1474                 
1475                 return;
1476         }
1477                 
1478         if(ma->mode & (MA_VERTEXCOLP|MA_FACETEXTURE)) {
1479                 shi->r= shi->vcol[0];
1480                 shi->g= shi->vcol[1];
1481                 shi->b= shi->vcol[2];
1482         }
1483         
1484         /* envmap hack, always reset */
1485         shi->refcol[0]= shi->refcol[1]= shi->refcol[2]= shi->refcol[3]= 0.0;
1486
1487         if(ma->texco) {
1488                 if(ma->mode & (MA_VERTEXCOLP|MA_FACETEXTURE)) {
1489                         shi->r= shi->vcol[0];
1490                         shi->g= shi->vcol[1];
1491                         shi->b= shi->vcol[2];
1492                 }
1493                 do_material_tex(shi);
1494         }
1495         
1496         if(ma->mode & MA_SHLESS) {
1497                 shr->diff[0]= shi->r;
1498                 shr->diff[1]= shi->g;
1499                 shr->diff[2]= shi->b;
1500                 shr->alpha= shi->alpha;
1501                 return;
1502         }
1503
1504         if( (ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))== MA_VERTEXCOL ) {        // vertexcolor light
1505                 // add_to_diffuse(shr->diff, shi, 1.0, ma->emit+shi->vcol[0], ma->emit+shi->vcol[1], ma->emit+shi->vcol[2]);
1506                 shr->diff[0]= shi->r*(shi->emit+shi->vcol[0]);
1507                 shr->diff[1]= shi->g*(shi->emit+shi->vcol[1]);
1508                 shr->diff[2]= shi->b*(shi->emit+shi->vcol[2]);
1509         }
1510         else {
1511                 // add_to_diffuse(shr->diff, shi, 1.0, ma->emit, ma->emit, ma->emit);
1512                 shr->diff[0]= shi->r*shi->emit;
1513                 shr->diff[1]= shi->g*shi->emit;
1514                 shr->diff[2]= shi->b*shi->emit;
1515         }
1516         
1517         ambient_occlusion(&R.wrld, shi, shr);
1518
1519         for(go=lights->first; go; go= go->next) {
1520                 lar= go->lampren;
1521                 if(lar==NULL) continue;
1522                 
1523                 /* yafray: ignore shading by photonlights, not used in Blender */
1524                 if (lar->type==LA_YF_PHOTON) continue;
1525
1526                 /* test for lamp layer */
1527                 if(lar->mode & LA_LAYER) if((lar->lay & vlr->lay)==0) continue;
1528                 
1529                 /* lampdist calculation */
1530                 if(lar->type==LA_SUN || lar->type==LA_HEMI) {
1531                         VECCOPY(lv, lar->vec);
1532                         lampdist= 1.0;
1533                 }
1534                 else {
1535                         lv[0]= shi->co[0]-lar->co[0];
1536                         lv[1]= shi->co[1]-lar->co[1];
1537                         lv[2]= shi->co[2]-lar->co[2];
1538                         ld= sqrt(lv[0]*lv[0]+lv[1]*lv[1]+lv[2]*lv[2]);
1539                         lv[0]/= ld;
1540                         lv[1]/= ld;
1541                         lv[2]/= ld;
1542                         
1543                         /* ld is re-used further on (texco's) */
1544                         if(lar->type==LA_AREA) {
1545                                 lampdist= 1.0;
1546                         }
1547                         else {
1548                                 if(lar->mode & LA_QUAD) {
1549                                         t= 1.0;
1550                                         if(lar->ld1>0.0)
1551                                                 t= lar->dist/(lar->dist+lar->ld1*ld);
1552                                         if(lar->ld2>0.0)
1553                                                 t*= lar->distkw/(lar->distkw+lar->ld2*ld*ld);
1554         
1555                                         lampdist= t;
1556                                 }
1557                                 else {
1558                                         lampdist= (lar->dist/(lar->dist+ld));
1559                                 }
1560         
1561                                 if(lar->mode & LA_SPHERE) {
1562                                         t= lar->dist - ld;
1563                                         if(t<0.0) continue;
1564                                         
1565                                         t/= lar->dist;
1566                                         lampdist*= (t);
1567                                 }
1568                         }
1569                 }
1570
1571                 lacol[0]= lar->r;
1572                 lacol[1]= lar->g;
1573                 lacol[2]= lar->b;
1574                 
1575                 /* init transp shadow */
1576                 shadfac[3]= 1.0;
1577                 if(ma->mode & MA_SHADOW_TRA) shadfac[0]= shadfac[1]= shadfac[2]= 1.0;
1578
1579                 if(lar->type==LA_SPOT) {
1580                         
1581                         if(lar->mode & LA_SQUARE) {
1582                                 if(lv[0]*lar->vec[0]+lv[1]*lar->vec[1]+lv[2]*lar->vec[2]>0.0) {
1583                                         float x;
1584                                         
1585                                         /* rotate view to lampspace */
1586                                         VECCOPY(lvrot, lv);
1587                                         MTC_Mat3MulVecfl(lar->imat, lvrot);
1588                                         
1589                                         x= MAX2(fabs(lvrot[0]/lvrot[2]) , fabs(lvrot[1]/lvrot[2]));
1590                                         /* 1.0/(sqrt(1+x*x)) is equivalent to cos(atan(x)) */
1591
1592                                         inpr= 1.0f/(sqrt(1.0f+x*x));
1593                                 }
1594                                 else inpr= 0.0;
1595                         }
1596                         else {
1597                                 inpr= lv[0]*lar->vec[0]+lv[1]*lar->vec[1]+lv[2]*lar->vec[2];
1598                         }
1599
1600                         t= lar->spotsi;
1601                         if(inpr<t) continue;
1602                         else {
1603                                 t= inpr-t;
1604                                 i= 1.0;
1605                                 soft= 1.0;
1606                                 if(t<lar->spotbl && lar->spotbl!=0.0) {
1607                                         /* soft area */
1608                                         i= t/lar->spotbl;
1609                                         t= i*i;
1610                                         soft= (3.0*t-2.0*t*i);
1611                                         inpr*= soft;
1612                                 }
1613                                 lampdist*=inpr;
1614                         }
1615
1616                         if(lar->mode & LA_OSATEX) {
1617                                 shi->osatex= 1; /* signal for multitex() */
1618                                 
1619                                 shi->dxlv[0]= lv[0] - (shi->co[0]-lar->co[0]+shi->dxco[0])/ld;
1620                                 shi->dxlv[1]= lv[1] - (shi->co[1]-lar->co[1]+shi->dxco[1])/ld;
1621                                 shi->dxlv[2]= lv[2] - (shi->co[2]-lar->co[2]+shi->dxco[2])/ld;
1622
1623                                 shi->dylv[0]= lv[0] - (shi->co[0]-lar->co[0]+shi->dyco[0])/ld;
1624                                 shi->dylv[1]= lv[1] - (shi->co[1]-lar->co[1]+shi->dyco[1])/ld;
1625                                 shi->dylv[2]= lv[2] - (shi->co[2]-lar->co[2]+shi->dyco[2])/ld;
1626                         }
1627                         
1628                 }
1629
1630                 if(lar->mode & LA_TEXTURE)  do_lamp_tex(lar, lv, shi, lacol);
1631                 
1632                 /* dot product and reflectivity */
1633                 /* inp = dotproduct, is = shader result, i = lamp energy (with shadow) */
1634                 
1635                 /* tangent case; calculate fake face normal, aligned with lampvector */
1636                 if(vlr->flag & R_TANGENT) {
1637                         float cross[3];
1638                         Crossf(cross, lv, vn);
1639                         Crossf(vnor, cross, shi->vn);
1640                         vnor[0]= -vnor[0];vnor[1]= -vnor[1];vnor[2]= -vnor[2];
1641                         vn= vnor;
1642                 }
1643                 
1644                 inp= vn[0]*lv[0] + vn[1]*lv[1] + vn[2]*lv[2];
1645         
1646                 /* phong threshold to prevent backfacing faces having artefacts on ray shadow (terminator problem) */
1647                 if((ma->mode & MA_RAYBIAS) && (lar->mode & LA_SHAD_RAY) && (vlr->flag & R_SMOOTH)) {
1648                         float thresh= vlr->ob->smoothresh;
1649                         if(inp>thresh)
1650                                 phongcorr= (inp-thresh)/(inp*(1.0-thresh));
1651                         else
1652                                 phongcorr= 0.0;
1653                 }
1654                 else phongcorr= 1.0;
1655                 
1656                 /* diffuse shaders */
1657                 if(lar->mode & LA_NO_DIFF) {
1658                         is= 0.0;        // skip shaders
1659                 }
1660                 else if(lar->type==LA_HEMI) {
1661                         is= 0.5*inp + 0.5;
1662                 }
1663                 else {
1664                 
1665                         if(lar->type==LA_AREA) {
1666                                 /* single sided */
1667                                 if(lv[0]*lar->vec[0]+lv[1]*lar->vec[1]+lv[2]*lar->vec[2]>0.0) {
1668                                         inp= area_lamp_energy(shi->co, vn, lar);
1669                                 }
1670                                 else inp= 0.0;
1671                         }
1672                         
1673                         /* diffuse shaders (oren nayer gets inp from area light) */
1674                         if(ma->diff_shader==MA_DIFF_ORENNAYAR) is= OrenNayar_Diff_i(inp, vn, lv, view, ma->roughness);
1675                         else if(ma->diff_shader==MA_DIFF_TOON) is= Toon_Diff(vn, lv, view, ma->param[0], ma->param[1]);
1676                         else if(ma->diff_shader==MA_DIFF_MINNAERT) is= Minnaert_Diff(inp, vn, view, ma->darkness);
1677                         else if(ma->diff_shader==MA_DIFF_FRESNEL) is= Fresnel_Diff(vn, lv, view, ma->param[0], ma->param[1]);
1678                         else is= inp;   // Lambert
1679                 }
1680                 
1681                 i= is*phongcorr;
1682                 
1683                 if(i>0.0) {
1684                         i*= lampdist*shi->refl;
1685                 }
1686                 
1687                 vn= shi->vn;    // bring back original vector, we use special specular shaders for tangent
1688                 
1689                 /* shadow and spec, (lampdist==0 outside spot) */
1690                 if(lampdist> 0.0) {
1691                         
1692                         if(i>0.0 && (R.r.mode & R_SHADOW)) {
1693                                 if(ma->mode & MA_SHADOW) {
1694                                         if(lar->type==LA_HEMI); // no shadow
1695                                         else {
1696                                                 if(lar->shb) {
1697                                                         shadfac[3] = testshadowbuf(lar->shb, shi->co, shi->dxco, shi->dyco, inp);
1698                                                 }
1699                                                 else if(lar->mode & LA_SHAD_RAY) {
1700                                                         ray_shadow(shi, lar, shadfac);
1701                                                 }
1702         
1703                                                 /* warning, here it skips the loop */
1704                                                 if(lar->mode & LA_ONLYSHADOW) {
1705                                                         
1706                                                         shadfac[3]= i*lar->energy*(1.0-shadfac[3]);
1707                                                         shr->diff[0] -= shadfac[3]*shi->r;
1708                                                         shr->diff[1] -= shadfac[3]*shi->g;
1709                                                         shr->diff[2] -= shadfac[3]*shi->b;
1710                                                         
1711                                                         continue;
1712                                                 }
1713                                                 
1714                                                 if(shadfac[3]==0.0) continue;
1715         
1716                                                 i*= shadfac[3];
1717                                         }
1718                                 }
1719                         }
1720                         
1721                         if(R.r.mode & R_RAYTRACE) {
1722                                 extern void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co);
1723                                 float co[3], distfac;
1724                                 
1725                                 ray_translucent(shi, lar, &distfac, co);
1726                                 
1727                                 if(distfac<0.01f*G.rt) {
1728                                 //      printf("distfac %f\n", distfac);
1729                                         distfac= 1.0f - distfac/(0.01f*G.rt);
1730                                         shr->diff[0]+= distfac;
1731                                         shr->diff[1]+= distfac;
1732                                         shr->diff[2]+= distfac;
1733                                 }
1734                         }
1735                         
1736                 
1737                         /* specularity */
1738                         if(shadfac[3]>0.0 && shi->spec!=0.0 && !(lar->mode & LA_NO_SPEC)) {
1739                                 
1740                                 if(lar->type==LA_HEMI) {
1741                                         /* hemi uses no spec shaders (yet) */
1742                                         
1743                                         lv[0]+= view[0];
1744                                         lv[1]+= view[1];
1745                                         lv[2]+= view[2];
1746                                         
1747                                         Normalise(lv);
1748                                         
1749                                         t= vn[0]*lv[0]+vn[1]*lv[1]+vn[2]*lv[2];
1750                                         
1751                                         if(lar->type==LA_HEMI) {
1752                                                 t= 0.5*t+0.5;
1753                                         }
1754                                         
1755                                         t= shadfac[3]*shi->spec*spec(t, shi->har);
1756                                         shr->spec[0]+= t*(lacol[0] * shi->specr);
1757                                         shr->spec[1]+= t*(lacol[1] * shi->specg);
1758                                         shr->spec[2]+= t*(lacol[2] * shi->specb);
1759                                 }
1760                                 else {
1761                                         /* specular shaders */
1762                                         float specfac;
1763
1764                                         if(ma->spec_shader==MA_SPEC_PHONG) 
1765                                                 specfac= Phong_Spec(vn, lv, view, shi->har, vlr->flag & R_TANGENT);
1766                                         else if(ma->spec_shader==MA_SPEC_COOKTORR) 
1767                                                 specfac= CookTorr_Spec(vn, lv, view, shi->har, vlr->flag & R_TANGENT);
1768                                         else if(ma->spec_shader==MA_SPEC_BLINN) 
1769                                                 specfac= Blinn_Spec(vn, lv, view, ma->refrac, (float)shi->har, vlr->flag & R_TANGENT);
1770                                         else if(ma->spec_shader==MA_SPEC_WARDISO)
1771                                                 specfac= WardIso_Spec( vn, lv, view, ma->rms, vlr->flag & R_TANGENT);
1772                                         else 
1773                                                 specfac= Toon_Spec(vn, lv, view, ma->param[2], ma->param[3], vlr->flag & R_TANGENT);
1774                                 
1775                                         /* area lamp correction */
1776                                         if(lar->type==LA_AREA) specfac*= inp;
1777                                         
1778                                         t= shadfac[3]*shi->spec*lampdist*specfac;
1779                                         
1780                                         if(ma->mode & MA_RAMP_SPEC) {
1781                                                 float spec[3];
1782                                                 do_specular_ramp(shi, specfac, t, spec);
1783                                                 shr->spec[0]+= t*(lacol[0] * spec[0]);
1784                                                 shr->spec[1]+= t*(lacol[1] * spec[1]);
1785                                                 shr->spec[2]+= t*(lacol[2] * spec[2]);
1786                                         }
1787                                         else {
1788                                                 shr->spec[0]+= t*(lacol[0] * shi->specr);
1789                                                 shr->spec[1]+= t*(lacol[1] * shi->specg);
1790                                                 shr->spec[2]+= t*(lacol[2] * shi->specb);
1791                                         }
1792                                 }
1793                         }
1794                 }
1795                 
1796                 /* in case 'no diffuse' we still do most calculus, spec can be in shadow */
1797                 if(i>0.0 && !(lar->mode & LA_NO_DIFF)) {
1798                         if(ma->mode & MA_SHADOW_TRA) {
1799                                 add_to_diffuse(shr->diff, shi, is, i*shadfac[0]*lacol[0], i*shadfac[1]*lacol[1], i*shadfac[2]*lacol[2]);
1800                         }
1801                         else {
1802                                 add_to_diffuse(shr->diff, shi, is, i*lacol[0], i*lacol[1], i*lacol[2]);
1803                         }
1804                 }
1805         }
1806
1807         if(ma->mode & (MA_ZTRA|MA_RAYTRANSP)) {
1808                 if(ma->fresnel_tra!=0.0) 
1809                         shi->alpha*= fresnel_fac(shi->view, shi->vn, ma->fresnel_tra_i, ma->fresnel_tra);
1810
1811                 if(shi->spectra!=0.0) {
1812
1813                         t = MAX3(shr->spec[0], shr->spec[1], shr->spec[2]);
1814                         t *= shi->spectra;
1815                         if(t>1.0) t= 1.0;
1816                         shi->alpha= (1.0-t)*shi->alpha+t;
1817                 }
1818         }
1819
1820         shr->alpha= shi->alpha;
1821
1822         shr->diff[0]+= shi->r*shi->amb*shi->rad[0];
1823         shr->diff[0]+= shi->ambr;
1824         
1825         shr->diff[1]+= shi->g*shi->amb*shi->rad[1];
1826         shr->diff[1]+= shi->ambg;
1827         
1828         shr->diff[2]+= shi->b*shi->amb*shi->rad[2];
1829         shr->diff[2]+= shi->ambb;
1830         
1831         if(ma->mode & MA_RAMP_COL) ramp_diffuse_result(shr->diff, shi);
1832         if(ma->mode & MA_RAMP_SPEC) ramp_spec_result(shr->spec, shr->spec+1, shr->spec+2, shi);
1833         
1834         /* refcol is for envmap only */
1835         if(shi->refcol[0]!=0.0) {
1836                 shr->diff[0]= shi->mirr*shi->refcol[1] + (1.0 - shi->mirr*shi->refcol[0])*shr->diff[0];
1837                 shr->diff[1]= shi->mirg*shi->refcol[2] + (1.0 - shi->mirg*shi->refcol[0])*shr->diff[1];
1838                 shr->diff[2]= shi->mirb*shi->refcol[3] + (1.0 - shi->mirb*shi->refcol[0])*shr->diff[2];
1839         }
1840
1841 }
1842
1843 /* this function sets all coords for render (shared with raytracer) */
1844 /* warning; exception for ortho render is here, can be done better! */
1845 void shade_input_set_coords(ShadeInput *shi, float u, float v, int i1, int i2, int i3)
1846 {
1847         VertRen *v1, *v2, *v3;
1848         VlakRen *vlr= shi->vlr;
1849         float l, dl;
1850         short texco= shi->mat->texco;
1851         int mode= shi->mat->mode_l;             /* or-ed result for all layers */
1852         char p1, p2, p3;
1853         
1854         /* for rendering of quads, the following values are used to denote vertices:
1855            0 1 2        scanline tria & first half quad, and ray tria
1856            0 2 3    scanline 2nd half quad
1857            0 1 3    raytracer first half quad
1858            2 1 3    raytracer 2nd half quad
1859         */
1860
1861         if(i1==0) {
1862                 v1= vlr->v1;
1863                 p1= ME_FLIPV1;
1864         } else {
1865                 v1= vlr->v3;
1866                 p1= ME_FLIPV3;
1867         }
1868
1869         if(i2==1) {
1870                 v2= vlr->v2;
1871                 p2= ME_FLIPV2;
1872         } else {
1873                 v2= vlr->v3;
1874                 p2= ME_FLIPV3;
1875         }
1876         
1877         if(i3==2) {
1878                 v3= vlr->v3;
1879                 p3= ME_FLIPV3;
1880         } else {
1881                 v3= vlr->v4;
1882                 p3= ME_FLIPV4;
1883         }
1884
1885         /* calculate U and V, for scanline (normal u and v are -1 to 0) */
1886         if(u==1.0) {
1887                 /* exception case for wire render of edge */
1888                 if(vlr->v2==vlr->v3);
1889                 else if( (vlr->flag & R_SMOOTH) || (texco & NEED_UV) ) {
1890                         float detsh, t00, t10, t01, t11;
1891                         
1892                         if(vlr->snproj==0) {
1893                                 t00= v3->co[0]-v1->co[0]; t01= v3->co[1]-v1->co[1];
1894                                 t10= v3->co[0]-v2->co[0]; t11= v3->co[1]-v2->co[1];
1895                         }
1896                         else if(vlr->snproj==1) {
1897                                 t00= v3->co[0]-v1->co[0]; t01= v3->co[2]-v1->co[2];
1898                                 t10= v3->co[0]-v2->co[0]; t11= v3->co[2]-v2->co[2];
1899                         }
1900                         else {
1901                                 t00= v3->co[1]-v1->co[1]; t01= v3->co[2]-v1->co[2];
1902                                 t10= v3->co[1]-v2->co[1]; t11= v3->co[2]-v2->co[2];
1903                         }
1904                         
1905                         detsh= 1.0/(t00*t11-t10*t01);
1906                         t00*= detsh; t01*=detsh; 
1907                         t10*=detsh; t11*=detsh;
1908                 
1909                         if(vlr->snproj==0) {
1910                                 u= (shi->co[0]-v3->co[0])*t11-(shi->co[1]-v3->co[1])*t10;
1911                                 v= (shi->co[1]-v3->co[1])*t00-(shi->co[0]-v3->co[0])*t01;
1912                                 if(shi->osatex) {
1913                                         shi->dxuv[0]=  shi->dxco[0]*t11- shi->dxco[1]*t10;
1914                                         shi->dxuv[1]=  shi->dxco[1]*t00- shi->dxco[0]*t01;
1915                                         shi->dyuv[0]=  shi->dyco[0]*t11- shi->dyco[1]*t10;
1916                                         shi->dyuv[1]=  shi->dyco[1]*t00- shi->dyco[0]*t01;
1917                                 }
1918                         }
1919                         else if(vlr->snproj==1) {
1920                                 u= (shi->co[0]-v3->co[0])*t11-(shi->co[2]-v3->co[2])*t10;
1921                                 v= (shi->co[2]-v3->co[2])*t00-(shi->co[0]-v3->co[0])*t01;
1922                                 if(shi->osatex) {
1923                                         shi->dxuv[0]=  shi->dxco[0]*t11- shi->dxco[2]*t10;
1924                                         shi->dxuv[1]=  shi->dxco[2]*t00- shi->dxco[0]*t01;
1925                                         shi->dyuv[0]=  shi->dyco[0]*t11- shi->dyco[2]*t10;
1926                                         shi->dyuv[1]=  shi->dyco[2]*t00- shi->dyco[0]*t01;
1927                                 }
1928                         }
1929                         else {
1930                                 u= (shi->co[1]-v3->co[1])*t11-(shi->co[2]-v3->co[2])*t10;
1931                                 v= (shi->co[2]-v3->co[2])*t00-(shi->co[1]-v3->co[1])*t01;
1932                                 if(shi->osatex) {
1933                                         shi->dxuv[0]=  shi->dxco[1]*t11- shi->dxco[2]*t10;
1934                                         shi->dxuv[1]=  shi->dxco[2]*t00- shi->dxco[1]*t01;
1935                                         shi->dyuv[0]=  shi->dyco[1]*t11- shi->dyco[2]*t10;
1936                                         shi->dyuv[1]=  shi->dyco[2]*t00- shi->dyco[1]*t01;
1937                                 }
1938                         }
1939                 }
1940         
1941         }
1942         l= 1.0+u+v;
1943         
1944         /* calculate punos (vertexnormals) */
1945         if(vlr->flag & R_SMOOTH) { 
1946                 float n1[3], n2[3], n3[3];
1947                 
1948                 if(shi->puno & p1) {
1949                         n1[0]= -v1->n[0]; n1[1]= -v1->n[1]; n1[2]= -v1->n[2];
1950                 } else {
1951                         n1[0]= v1->n[0]; n1[1]= v1->n[1]; n1[2]= v1->n[2];
1952                 }
1953                 if(shi->puno & p2) {
1954                         n2[0]= -v2->n[0]; n2[1]= -v2->n[1]; n2[2]= -v2->n[2];
1955                 } else {
1956                         n2[0]= v2->n[0]; n2[1]= v2->n[1]; n2[2]= v2->n[2];
1957                 }
1958                 
1959                 if(shi->puno & p3) {
1960                         n3[0]= -v3->n[0]; n3[1]= -v3->n[1]; n3[2]= -v3->n[2];
1961                 } else {
1962                         n3[0]= v3->n[0]; n3[1]= v3->n[1]; n3[2]= v3->n[2];
1963                 }
1964
1965                 shi->vn[0]= l*n3[0]-u*n1[0]-v*n2[0];
1966                 shi->vn[1]= l*n3[1]-u*n1[1]-v*n2[1];
1967                 shi->vn[2]= l*n3[2]-u*n1[2]-v*n2[2];
1968
1969                 Normalise(shi->vn);
1970
1971                 if(shi->osatex && (texco & (TEXCO_NORM|TEXCO_REFL)) ) {
1972                         dl= shi->dxuv[0]+shi->dxuv[1];
1973                         shi->dxno[0]= dl*n3[0]-shi->dxuv[0]*n1[0]-shi->dxuv[1]*n2[0];
1974                         shi->dxno[1]= dl*n3[1]-shi->dxuv[0]*n1[1]-shi->dxuv[1]*n2[1];
1975                         shi->dxno[2]= dl*n3[2]-shi->dxuv[0]*n1[2]-shi->dxuv[1]*n2[2];
1976                         dl= shi->dyuv[0]+shi->dyuv[1];
1977                         shi->dyno[0]= dl*n3[0]-shi->dyuv[0]*n1[0]-shi->dyuv[1]*n2[0];
1978                         shi->dyno[1]= dl*n3[1]-shi->dyuv[0]*n1[1]-shi->dyuv[1]*n2[1];
1979                         shi->dyno[2]= dl*n3[2]-shi->dyuv[0]*n1[2]-shi->dyuv[1]*n2[2];
1980
1981                 }
1982         }
1983         else {
1984                 VECCOPY(shi->vn, shi->facenor);
1985         }
1986
1987         /* texture coordinates. shi->dxuv shi->dyuv have been set */
1988         if(texco & NEED_UV) {
1989                 if(texco & TEXCO_ORCO) {
1990                         if(v1->orco) {
1991                                 float *o1, *o2, *o3;
1992                                 
1993                                 o1= v1->orco;
1994                                 o2= v2->orco;
1995                                 o3= v3->orco;
1996                                 
1997                                 shi->lo[0]= l*o3[0]-u*o1[0]-v*o2[0];
1998                                 shi->lo[1]= l*o3[1]-u*o1[1]-v*o2[1];
1999                                 shi->lo[2]= l*o3[2]-u*o1[2]-v*o2[2];
2000         
2001                                 if(shi->osatex) {
2002                                         dl= shi->dxuv[0]+shi->dxuv[1];
2003                                         shi->dxlo[0]= dl*o3[0]-shi->dxuv[0]*o1[0]-shi->dxuv[1]*o2[0];
2004                                         shi->dxlo[1]= dl*o3[1]-shi->dxuv[0]*o1[1]-shi->dxuv[1]*o2[1];
2005                                         shi->dxlo[2]= dl*o3[2]-shi->dxuv[0]*o1[2]-shi->dxuv[1]*o2[2];
2006                                         dl= shi->dyuv[0]+shi->dyuv[1];
2007                                         shi->dylo[0]= dl*o3[0]-shi->dyuv[0]*o1[0]-shi->dyuv[1]*o2[0];
2008                                         shi->dylo[1]= dl*o3[1]-shi->dyuv[0]*o1[1]-shi->dyuv[1]*o2[1];
2009                                         shi->dylo[2]= dl*o3[2]-shi->dyuv[0]*o1[2]-shi->dyuv[1]*o2[2];
2010                                 }
2011                         }
2012                 }
2013                 
2014                 if(texco & TEXCO_GLOB) {
2015                         VECCOPY(shi->gl, shi->co);
2016                         MTC_Mat4MulVecfl(R.viewinv, shi->gl);
2017                         if(shi->osatex) {
2018                                 VECCOPY(shi->dxgl, shi->dxco);
2019                                 MTC_Mat3MulVecfl(R.imat, shi->dxco);
2020                                 VECCOPY(shi->dygl, shi->dyco);
2021                                 MTC_Mat3MulVecfl(R.imat, shi->dyco);
2022                         }
2023                 }
2024                 if(texco & TEXCO_STRAND) {
2025                         shi->strand= (l*v3->accum - u*v1->accum - v*v2->accum);
2026                         if(shi->osatex) {
2027                                 dl= shi->dxuv[0]+shi->dxuv[1];
2028                                 shi->dxstrand= dl*v3->accum-shi->dxuv[0]*v1->accum-shi->dxuv[1]*v2->accum;
2029                                 dl= shi->dyuv[0]+shi->dyuv[1];
2030                                 shi->dystrand= dl*v3->accum-shi->dyuv[0]*v1->accum-shi->dyuv[1]*v2->accum;
2031                         }
2032                 }
2033                 if((texco & TEXCO_UV) || (mode & (MA_VERTEXCOL|MA_VERTEXCOLP|MA_FACETEXTURE)))  {
2034                         int j1=i1, j2=i2, j3=i3;
2035                         
2036                         /* to prevent storing new tfaces or vcols, we check a split runtime */
2037                         /*              4---3           4---3 */
2038                         /*              |\ 1|   or  |1 /| */
2039                         /*              |0\ |           |/ 0| */
2040                         /*              1---2           1---2   0 = orig face, 1 = new face */
2041                         
2042                         /* Update vert nums to point to correct verts of original face */
2043                         if(vlr->flag & R_DIVIDE_24) {  
2044                                 if(vlr->flag & R_FACE_SPLIT) {
2045                                         j1++; j2++; j3++;
2046                                 }
2047                                 else {
2048                                         j3++;
2049                                 }
2050                         }
2051                         else if(vlr->flag & R_FACE_SPLIT) {
2052                                 j2++; j3++; 
2053                         }
2054                         
2055                         if(mode & (MA_VERTEXCOL|MA_VERTEXCOLP)) {
2056                                 
2057                                 if(vlr->vcol) {
2058                                         char *cp1, *cp2, *cp3;
2059                                         
2060                                         cp1= (char *)(vlr->vcol+j1);
2061                                         cp2= (char *)(vlr->vcol+j2);
2062                                         cp3= (char *)(vlr->vcol+j3);
2063
2064                                         shi->vcol[0]= (l*cp3[3]-u*cp1[3]-v*cp2[3])/255.0;
2065                                         shi->vcol[1]= (l*cp3[2]-u*cp1[2]-v*cp2[2])/255.0;
2066                                         shi->vcol[2]= (l*cp3[1]-u*cp1[1]-v*cp2[1])/255.0;
2067                                         
2068                                 }
2069                                 else {
2070                                         shi->vcol[0]= 0.0;
2071                                         shi->vcol[1]= 0.0;
2072                                         shi->vcol[2]= 0.0;
2073                                 }
2074                         }
2075                         if(vlr->tface) {
2076                                 float *uv1, *uv2, *uv3;
2077                                 
2078                                 uv1= vlr->tface->uv[j1];
2079                                 uv2= vlr->tface->uv[j2];
2080                                 uv3= vlr->tface->uv[j3];
2081                                 
2082                                 shi->uv[0]= -1.0 + 2.0*(l*uv3[0]-u*uv1[0]-v*uv2[0]);
2083                                 shi->uv[1]= -1.0 + 2.0*(l*uv3[1]-u*uv1[1]-v*uv2[1]);
2084                                 shi->uv[2]= 0.0;        // texture.c assumes there are 3 coords
2085                                 
2086                                 if(shi->osatex) {
2087                                         float duv[2];
2088                                         
2089                                         dl= shi->dxuv[0]+shi->dxuv[1];
2090                                         duv[0]= shi->dxuv[0]; 
2091                                         duv[1]= shi->dxuv[1];
2092                                         
2093                                         shi->dxuv[0]= 2.0*(dl*uv3[0]-duv[0]*uv1[0]-duv[1]*uv2[0]);
2094                                         shi->dxuv[1]= 2.0*(dl*uv3[1]-duv[0]*uv1[1]-duv[1]*uv2[1]);
2095         
2096                                         dl= shi->dyuv[0]+shi->dyuv[1];
2097                                         duv[0]= shi->dyuv[0]; 
2098                                         duv[1]= shi->dyuv[1];
2099         
2100                                         shi->dyuv[0]= 2.0*(dl*uv3[0]-duv[0]*uv1[0]-duv[1]*uv2[0]);
2101                                         shi->dyuv[1]= 2.0*(dl*uv3[1]-duv[0]*uv1[1]-duv[1]*uv2[1]);
2102                                 }
2103 #if 0
2104                                 {       /* tangent derived from UV, comes back later! (ton) */
2105                                         //float s1= uv2[0] - uv1[0];
2106                                         //float s2= uv3[0] - uv1[0];
2107                                         float t1= uv2[1] - uv1[1];
2108                                         float t2= uv3[1] - uv1[1];
2109                                         
2110                                         shi->vn[0]= (t2 * (v2->co[0]-v1->co[0]) - t1 * (v3->co[0]-v1->co[0])); 
2111                                         shi->vn[1]= (t2 * (v2->co[1]-v1->co[1]) - t1 * (v3->co[1]-v1->co[1]));
2112                                         shi->vn[2]= (t2 * (v2->co[2]-v1->co[2]) - t1 * (v3->co[2]-v1->co[2]));
2113                                         Normalise(shi->vn);
2114                                         vlr->flag |= R_TANGENT;
2115                                 }                                       
2116 #endif
2117                                 if(mode & MA_FACETEXTURE) {
2118                                         if((mode & (MA_VERTEXCOL|MA_VERTEXCOLP))==0) {
2119                                                 shi->vcol[0]= 1.0;
2120                                                 shi->vcol[1]= 1.0;
2121                                                 shi->vcol[2]= 1.0;
2122                                         }
2123                                         if(vlr->tface) render_realtime_texture(shi);
2124                                 }
2125                         }
2126                         else {
2127                                 shi->uv[0]= 2.0*(u+.5);
2128                                 shi->uv[1]= 2.0*(v+.5);
2129                                 shi->uv[2]= 0.0;        // texture.c assumes there are 3 coords
2130                                 if(mode & MA_FACETEXTURE) {
2131                                         /* no tface? set at 1.0 */
2132                                         shi->vcol[0]= 1.0;
2133                                         shi->vcol[1]= 1.0;
2134                                         shi->vcol[2]= 1.0;
2135                                 }
2136                         }
2137                 }
2138                 if(texco & TEXCO_NORM) {
2139                         shi->orn[0]= -shi->vn[0];
2140                         shi->orn[1]= -shi->vn[1];
2141                         shi->orn[2]= -shi->vn[2];
2142                 }
2143                 if(mode & MA_RADIO) {
2144                         shi->rad[0]= (l*v3->rad[0] - u*v1->rad[0] - v*v2->rad[0]);
2145                         shi->rad[1]= (l*v3->rad[1] - u*v1->rad[1] - v*v2->rad[1]);
2146                         shi->rad[2]= (l*v3->rad[2] - u*v1->rad[2] - v*v2->rad[2]);
2147                 }
2148                 else {
2149                         shi->rad[0]= shi->rad[1]= shi->rad[2]= 0.0;
2150                 }
2151                 if(texco & TEXCO_REFL) {
2152                         /* mirror reflection colour textures (and envmap) */
2153                         calc_R_ref(shi);
2154                 }
2155                 
2156         }
2157         else {
2158                 shi->rad[0]= shi->rad[1]= shi->rad[2]= 0.0;
2159         }
2160 }
2161
2162 #if 0
2163 /* return labda for view vector being closest to line v3-v4 */
2164 /* was used for wire render */
2165 static float isec_view_line(float *view, float *v3, float *v4)
2166 {
2167         float vec[3];
2168         float dot0, dot1, dot2, veclen, viewlen;
2169         float fac, div;
2170         
2171         vec[0]= v4[0] - v3[0];
2172         vec[1]= v4[1] - v3[1];
2173         vec[2]= v4[2] - v3[2];
2174         
2175         dot0 = v3[0]*vec[0] + v3[1]*vec[1] + v3[2]*vec[2];
2176         dot1 = vec[0]*view[0] + vec[1]*view[1] + vec[2]*view[2];
2177         dot2 = v3[0]*view[0] + v3[1]*view[1] + v3[2]*view[2];
2178         
2179         veclen = vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2];
2180         viewlen = view[0]*view[0] + view[1]*view[1] + view[2]*view[2];
2181         
2182         div = viewlen*veclen - dot1*dot1;
2183         if (div==0.0) return 0.0;
2184         
2185         fac = dot2*veclen - dot0*dot1;
2186         return fac/div;
2187 }
2188 #endif
2189
2190 void matlayer_blend(MaterialLayer *ml, float blendfac, ShadeResult *target, ShadeResult *src)
2191 {
2192         
2193         if(ml->flag & ML_DIFFUSE)
2194                 ramp_blend(ml->blendmethod, target->diff, target->diff+1, target->diff+2, blendfac*src->alpha, src->diff);
2195         
2196         if(ml->flag & ML_SPECULAR)
2197                 ramp_blend(ml->blendmethod, target->spec, target->spec+1, target->spec+2, blendfac*src->alpha, src->spec);
2198         
2199         if(ml->flag & ML_ALPHA)
2200                 ramp_blend(ml->blendmethod, &target->alpha, NULL, NULL, blendfac, &src->alpha);
2201 }
2202
2203
2204 /* x,y: window coordinate from 0 to rectx,y */
2205 /* return pointer to rendered face */
2206 void *shadepixel(float x, float y, int z, int facenr, int mask, float *col, float *rco)
2207 {
2208         ShadeResult shr;
2209         ShadeInput shi;
2210         VlakRen *vlr=NULL;
2211         
2212         if(facenr< 0) { /* error */
2213                 return NULL;
2214         }
2215         /* currently in use for dithering (soft shadow) and detecting thread */
2216         shi.xs= x;
2217         shi.ys= y;
2218         
2219         /* mask is used to indicate amount of samples (ray shad/mir and AO) */
2220         shi.mask= mask;
2221         shi.depth= 0;   // means first hit, not raytracing
2222         
2223         if(facenr==0) { /* sky */
2224                 col[0]= 0.0; col[1]= 0.0; col[2]= 0.0; col[3]= 0.0;
2225                 VECCOPY(rco, col);
2226         }
2227         else if( (facenr & 0x7FFFFF) <= R.totvlak) {
2228                 VertRen *v1, *v2, *v3;
2229                 Material *mat;
2230                 MaterialLayer *ml;
2231                 float alpha, fac, zcor;
2232                 
2233                 vlr= RE_findOrAddVlak( (facenr-1) & 0x7FFFFF);
2234                 
2235                 shi.vlr= vlr;
2236                 mat= shi.mat= vlr->mat;
2237                 
2238                 shi.osatex= (shi.mat->texco & TEXCO_OSA);
2239                 
2240                 /* copy the face normal (needed because it gets flipped for tracing */
2241                 VECCOPY(shi.facenor, vlr->n);
2242                 shi.puno= vlr->puno;
2243                 
2244                 v1= vlr->v1;
2245                 
2246                 /* COXYZ AND VIEW VECTOR  */
2247                 calc_view_vector(shi.view, x, y);
2248
2249                 /* wire cannot use normal for calculating shi.co */
2250                 if(shi.mat->mode & MA_WIRE) {
2251                         float zco;
2252                         /* inverse of zbuf calc: zbuf = MAXZ*hoco_z/hoco_w */
2253                         
2254                         zco= ((float)z)/(float)0x7FFFFFFF;
2255                         shi.co[2]= R.winmat[3][2]/( R.winmat[2][3]*zco - R.winmat[2][2] );
2256                         
2257                         fac= zcor= shi.co[2]/shi.view[2];
2258                         
2259                         shi.co[0]= fac*shi.view[0];
2260                         shi.co[1]= fac*shi.view[1];
2261                 }
2262                 else {
2263                         float dface;
2264                         
2265                         dface= v1->co[0]*shi.facenor[0]+v1->co[1]*shi.facenor[1]+v1->co[2]*shi.facenor[2];
2266                         
2267                         /* ortho viewplane cannot intersect using view vector originating in (0,0,0) */
2268                         if(R.r.mode & R_ORTHO) {
2269                                 /* x and y 3d coordinate can be derived from pixel coord and winmat */
2270                                 float fx= 2.0/(R.rectx*R.winmat[0][0]);
2271                                 float fy= 2.0/(R.recty*R.winmat[1][1]);
2272                                 
2273                                 shi.co[0]= (0.5 + x - 0.5*R.rectx)*fx - R.winmat[3][0]/R.winmat[0][0];
2274                                 shi.co[1]= (0.5 + y - 0.5*R.recty)*fy - R.winmat[3][1]/R.winmat[1][1];
2275                                 
2276                                 /* using a*x + b*y + c*z = d equation, (a b c) is normal */
2277                                 shi.co[2]= (dface - shi.facenor[0]*shi.co[0] - shi.facenor[1]*shi.co[1])/shi.facenor[2];
2278                                 
2279                                 zcor= 1.0; // only to prevent not-initialize
2280                                 
2281                                 if(shi.osatex || (R.r.mode & R_SHADOW) ) {
2282                                         shi.dxco[0]= fx;
2283                                         shi.dxco[1]= 0.0;
2284                                         shi.dxco[2]= (shi.facenor[0]*fx)/shi.facenor[2];
2285                                         
2286                                         shi.dyco[0]= 0.0;
2287                                         shi.dyco[1]= fy;
2288                                         shi.dyco[2]= (shi.facenor[1]*fy)/shi.facenor[2];
2289                                 }
2290                         }
2291                         else {
2292                                 float div;
2293                                 
2294                                 div= shi.facenor[0]*shi.view[0] + shi.facenor[1]*shi.view[1] + shi.facenor[2]*shi.view[2];
2295                                 if (div!=0.0) fac= zcor= dface/div;
2296                                 else fac= zcor= 0.0;
2297                                 
2298                                 shi.co[0]= fac*shi.view[0];
2299                                 shi.co[1]= fac*shi.view[1];
2300                                 shi.co[2]= fac*shi.view[2];
2301                         
2302                                 /* pixel dx/dy for render coord */
2303                                 if(shi.osatex || (R.r.mode & R_SHADOW) ) {
2304                                         float u= dface/(div-shi.facenor[0]);
2305                                         float v= dface/(div- R.ycor*shi.facenor[1]);
2306
2307                                         shi.dxco[0]= shi.co[0]- (shi.view[0]-1.0)*u;
2308                                         shi.dxco[1]= shi.co[1]- (shi.view[1])*u;
2309                                         shi.dxco[2]= shi.co[2]- (shi.view[2])*u;
2310
2311                                         shi.dyco[0]= shi.co[0]- (shi.view[0])*v;
2312                                         shi.dyco[1]= shi.co[1]- (shi.view[1]-1.0*R.ycor)*v;
2313                                         shi.dyco[2]= shi.co[2]- (shi.view[2])*v;
2314
2315                                 }
2316                         }
2317                 }
2318                 /* rco might be used for sky texture */
2319                 VECCOPY(rco, shi.co);
2320                 
2321                 /* cannot normalise earlier, code above needs it at pixel level */
2322                 fac= Normalise(shi.view);
2323                 zcor*= fac;     // for mist, distance of point from camera
2324                 
2325                 if(shi.osatex) {
2326                         if( (shi.mat->texco & TEXCO_REFL) ) {
2327                                 shi.dxview= -1.0/fac;
2328                                 shi.dyview= -R.ycor/fac;
2329                         }
2330                 }
2331                 
2332                 /* calcuate normals, texture coords, vertex colors, etc */
2333                 if(facenr & 0x800000)
2334                         shade_input_set_coords(&shi, 1.0, 1.0, 0, 2, 3);
2335                 else 
2336                         shade_input_set_coords(&shi, 1.0, 1.0, 0, 1, 2);
2337
2338                 /* this only avalailable for scanline */
2339                 if(shi.mat->texco & TEXCO_WINDOW) {
2340                         shi.winco[0]= (x+(R.xstart))/(float)R.afmx;
2341                         shi.winco[1]= (y+(R.ystart))/(float)R.afmy;
2342                         shi.winco[2]= 0.0;
2343                         if(shi.osatex) {
2344                                 shi.dxwin[0]= 0.5/(float)R.r.xsch;
2345                                 shi.dywin[1]= 0.5/(float)R.r.ysch;
2346                                 shi.dxwin[1]= shi.dxwin[2]= 0.0;
2347                                 shi.dywin[0]= shi.dywin[2]= 0.0;
2348                         }
2349                 }
2350                 /* after this the u and v AND shi.dxuv and shi.dyuv are incorrect */
2351                 if(shi.mat->texco & TEXCO_STICKY) {
2352                         if(v1->sticky) {
2353                                 extern float Zmulx, Zmuly;
2354                                 float *o1, *o2, *o3, hox, hoy, l, dl, u, v;
2355                                 float s00, s01, s10, s11, detsh;
2356                                 
2357                                 if(facenr & 0x800000) {
2358                                         v2= vlr->v3; v3= vlr->v4;
2359                                 } else {
2360                                         v2= vlr->v2; v3= vlr->v3;
2361                                 }
2362                                 
2363                                 s00= v3->ho[0]/v3->ho[3] - v1->ho[0]/v1->ho[3];
2364                                 s01= v3->ho[1]/v3->ho[3] - v1->ho[1]/v1->ho[3];
2365                                 s10= v3->ho[0]/v3->ho[3] - v2->ho[0]/v2->ho[3];
2366                                 s11= v3->ho[1]/v3->ho[3] - v2->ho[1]/v2->ho[3];
2367                                 
2368                                 detsh= s00*s11-s10*s01;
2369                                 s00/= detsh; s01/=detsh; 
2370                                 s10/=detsh; s11/=detsh;
2371         
2372                                 /* recalc u and v again */
2373                                 hox= x/Zmulx -1.0;
2374                                 hoy= y/Zmuly -1.0;
2375                                 u= (hox - v3->ho[0]/v3->ho[3])*s11 - (hoy - v3->ho[1]/v3->ho[3])*s10;
2376                                 v= (hoy - v3->ho[1]/v3->ho[3])*s00 - (hox - v3->ho[0]/v3->ho[3])*s01;
2377                                 l= 1.0+u+v;
2378                                 
2379                                 o1= v1->sticky;
2380                                 o2= v2->sticky;
2381                                 o3= v3->sticky;
2382                                 
2383                                 shi.sticky[0]= l*o3[0]-u*o1[0]-v*o2[0];
2384                                 shi.sticky[1]= l*o3[1]-u*o1[1]-v*o2[1];
2385                                 shi.sticky[2]= 0.0;
2386                                 
2387                                 if(shi.osatex) {
2388                                         shi.dxuv[0]=  s11/Zmulx;
2389                                         shi.dxuv[1]=  - s01/Zmulx;
2390                                         shi.dyuv[0]=  - s10/Zmuly;
2391                                         shi.dyuv[1]=  s00/Zmuly;
2392                                         
2393                                         dl= shi.dxuv[0]+shi.dxuv[1];
2394                                         shi.dxsticky[0]= dl*o3[0]-shi.dxuv[0]*o1[0]-shi.dxuv[1]*o2[0];
2395                                         shi.dxsticky[1]= dl*o3[1]-shi.dxuv[0]*o1[1]-shi.dxuv[1]*o2[1];
2396                                         dl= shi.dyuv[0]+shi.dyuv[1];
2397                                         shi.dysticky[0]= dl*o3[0]-shi.dyuv[0]*o1[0]-shi.dyuv[1]*o2[0];
2398                                         shi.dysticky[1]= dl*o3[1]-shi.dyuv[0]*o1[1]-shi.dyuv[1]*o2[1];
2399                                 }
2400                         }
2401                 }
2402                 
2403                 /* ------  main shading loop -------- */
2404                 VECCOPY(shi.vno, shi.vn);
2405                 
2406                 if(shi.mat->ml_flag & ML_RENDER) {
2407
2408                         shade_lamp_loop(&shi, &shr);    /* clears shr */
2409
2410                         if(shi.translucency!=0.0) {
2411                                 ShadeResult shr_t;
2412                                 
2413                                 VECCOPY(shi.vn, shi.vno);
2414                                 VecMulf(shi.vn, -1.0);
2415                                 VecMulf(shi.facenor, -1.0);
2416                                 shade_lamp_loop(&shi, &shr_t);
2417                                 
2418                                 shr.diff[0]+= shi.translucency*shr_t.diff[0];
2419                                 shr.diff[1]+= shi.translucency*shr_t.diff[1];
2420                                 shr.diff[2]+= shi.translucency*shr_t.diff[2];
2421                                 VecMulf(shi.vn, -1.0);
2422                                 VecMulf(shi.facenor, -1.0);
2423                         }
2424                         
2425                         if(R.r.mode & R_RAYTRACE) {
2426                                 if(shi.ray_mirror!=0.0 || ((shi.mat->mode & MA_RAYTRANSP) && shr.alpha!=1.0)) {
2427                                         ray_trace(&shi, &shr);
2428                                 }
2429                         }
2430                         else {
2431                                 /* doesnt look 'correct', but is better for preview, plus envmaps dont raytrace this */
2432                                 if(shi.mat->mode & MA_RAYTRANSP) shr.alpha= 1.0;
2433                         }
2434                 }
2435                 else {
2436                         memset(&shr, 0, sizeof(ShadeResult));
2437                         shr.alpha= 1.0f;
2438                 }
2439                 
2440                 for(ml= shi.mat->layers.first; ml; ml= ml->next) {
2441                         if(ml->mat && (ml->flag & ML_RENDER)) {
2442                                 ShadeResult shrlay;
2443                                 
2444                                 shi.mat= ml->mat;
2445                                 shi.layerfac= ml->blendfac;
2446                                 VECCOPY(shi.vn, shi.vno);
2447                                 if(ml->flag & ML_NEG_NORMAL)
2448                                         VecMulf(shi.vn, -1.0);
2449                                 
2450                                 shade_lamp_loop(&shi, &shrlay); /* clears shrlay */
2451                                 
2452                                 if(R.r.mode & R_RAYTRACE) {
2453                                         if(shi.ray_mirror!=0.0 || ((shi.mat->mode & MA_RAYTRANSP) && shr.alpha!=1.0)) {
2454                                                 ray_trace(&shi, &shr);
2455                                         }
2456                                 }
2457                                 else {
2458                                         /* doesnt look 'correct', but is better for preview, plus envmaps dont raytrace this */
2459                                         if(shi.mat->mode & MA_RAYTRANSP) shr.alpha= 1.0;
2460                                 }
2461                                 
2462                                 matlayer_blend(ml, shi.layerfac, &shr, &shrlay);
2463                         }
2464                 }
2465                 shi.mat= mat;
2466                 
2467                 /* after shading and composit layers */
2468                 if(shr.spec[0]<0.0f) shr.spec[0]= 0.0f;
2469                 if(shr.spec[1]<0.0f) shr.spec[1]= 0.0f;
2470                 if(shr.spec[2]<0.0f) shr.spec[2]= 0.0f;
2471                 
2472                 if(shr.diff[0]<0.0f) shr.diff[0]= 0.0f;
2473                 if(shr.diff[1]<0.0f) shr.diff[1]= 0.0f;
2474                 if(shr.diff[2]<0.0f) shr.diff[2]= 0.0f;
2475                 
2476                 VECADD(col, shr.diff, shr.spec);
2477                 
2478                 /* exposure correction */
2479                 if(R.wrld.exp!=0.0 || R.wrld.range!=1.0) {
2480                         if((shi.mat->mode & MA_SHLESS)==0) {
2481                                 col[0]= R.wrld.linfac*(1.0-exp( col[0]*R.wrld.logfac) );
2482                                 col[1]= R.wrld.linfac*(1.0-exp( col[1]*R.wrld.logfac) );
2483                                 col[2]= R.wrld.linfac*(1.0-exp( col[2]*R.wrld.logfac) );
2484                         }
2485                 }
2486                 
2487                 /* MIST */
2488                 if((R.wrld.mode & WO_MIST) && (shi.mat->mode & MA_NOMIST)==0 ) {
2489                         if(R.r.mode & R_ORTHO)
2490                                 alpha= mistfactor(-shi.co[2], shi.co);
2491                         else
2492                                 alpha= mistfactor(zcor, shi.co);
2493                 }
2494                 else alpha= 1.0;
2495
2496                 if(shr.alpha!=1.0 || alpha!=1.0) {
2497                         if(shi.mat->mode & MA_RAYTRANSP) {
2498                                 // sky was applied allready for ray transp, only do mist
2499                                 col[3]= shr.alpha;
2500                                 fac= alpha;     
2501                         }
2502                         else {
2503                                 fac= alpha*(shr.alpha);
2504                                 col[3]= fac;
2505                         }                       
2506                         col[0]*= fac;
2507                         col[1]*= fac;
2508                         col[2]*= fac;
2509                 }
2510                 else col[3]= 1.0;
2511         }
2512         
2513         if(R.flag & R_LAMPHALO) {
2514                 if(facenr<=0) { /* calc view vector and put shi.co at far */
2515                         if(R.r.mode & R_ORTHO) {
2516                                 /* x and y 3d coordinate can be derived from pixel coord and winmat */
2517                                 float fx= 2.0/(R.rectx*R.winmat[0][0]);
2518                                 float fy= 2.0/(R.recty*R.winmat[1][1]);
2519                                 
2520                                 shi.co[0]= (0.5 + x - 0.5*R.rectx)*fx - R.winmat[3][0]/R.winmat[0][0];
2521                                 shi.co[1]= (0.5 + y - 0.5*R.recty)*fy - R.winmat[3][1]/R.winmat[1][1];
2522                         }
2523                         
2524                         calc_view_vector(shi.view, x, y);
2525                         shi.co[2]= 0.0;
2526                         
2527                         renderspothalo(&shi, col, 1.0);
2528                 }
2529                 else
2530                         renderspothalo(&shi, col, col[3]);
2531         }
2532         
2533         return vlr;
2534 }
2535
2536 static void shadepixel_sky(float x, float y, int z, int facenr, int mask, float *colf)
2537 {
2538         VlakRen *vlr;
2539         float collector[4], rco[3];
2540         
2541         vlr= shadepixel(x, y, z, facenr, mask, colf, rco);
2542         if(colf[3] != 1.0) {
2543                 /* bail out when raytrace transparency (sky included already) */
2544                 if(vlr && (R.r.mode & R_RAYTRACE))
2545                         if(vlr->mat->mode & MA_RAYTRANSP) return;
2546                 
2547                 renderSkyPixelFloat(collector, x, y, vlr?rco:NULL);
2548                 addAlphaOverFloat(collector, colf);
2549                 QUATCOPY(colf, collector);
2550         }
2551 }
2552
2553 /* ************* pixel struct ******** */
2554
2555 static PixStrMain psmfirst;
2556 static int psmteller;
2557
2558 static PixStr *addpsmain(void)
2559 {
2560         PixStrMain *psm;
2561
2562         psm= &psmfirst;
2563
2564         while(psm->next) {
2565                 psm= psm->next;
2566         }
2567
2568         psm->next= (PixStrMain *)MEM_mallocN(sizeof(PixStrMain),"pixstrMain");
2569
2570         psm= psm->next;
2571         psm->next=0;
2572         psm->ps= (PixStr *)MEM_mallocN(4096*sizeof(PixStr),"pixstr");
2573         psmteller= 0;
2574
2575         return psm->ps;
2576 }
2577
2578 static void freeps(void)
2579 {
2580         PixStrMain *psm,*next;
2581
2582         psm= &psmfirst;
2583
2584         while(psm) {
2585                 next= psm->next;
2586                 if(psm->ps) {
2587                         MEM_freeN(psm->ps);
2588                         psm->ps= 0;
2589                 }
2590                 if(psm!= &psmfirst) MEM_freeN(psm);
2591                 psm= next;
2592         }
2593
2594         psmfirst.next= 0;
2595         psmfirst.ps= 0;
2596 }
2597
2598 static void addps(long *rd, int facenr, int z, unsigned short mask)
2599 {
2600         static PixStr *cur;
2601         PixStr *ps, *last = NULL;
2602
2603         if(*rd) {       
2604                 ps= (PixStr *)(*rd);
2605                 
2606                 while(ps) {
2607                         if( ps->facenr == facenr ) {
2608                                 ps->mask |= mask;
2609                                 return;
2610                         }
2611                         last= ps;
2612                         ps= ps->next;
2613                 }
2614         }
2615
2616         /* make new PS (pixel struct) */
2617         if((psmteller & 4095)==0) cur= addpsmain();
2618         else cur++;
2619         psmteller++;
2620
2621         if(last) last->next= cur;
2622         else *rd= (long)cur;
2623
2624         cur->next= NULL;
2625         cur->facenr= facenr;
2626         cur->z= z;
2627         cur->mask = mask;
2628 }
2629
2630
2631 int count_mask(unsigned short mask)
2632 {
2633         extern char cmask[256];
2634         return (cmask[mask & 255]+cmask[mask>>8]);
2635 }
2636
2637 static void edge_enhance(void)
2638 {
2639         /* use zbuffer to define edges, add it to the image */
2640         int val, y, x, col, *rz, *rz1, *rz2, *rz3;
2641         int zval1, zval2, zval3;
2642         char *cp;
2643         
2644         /* shift values in zbuffer 4 to the right, for filter we need multiplying with 12 max */
2645         rz= (int *)R.rectz;
2646         if(rz==NULL) return;
2647         
2648         for(y=0; y<R.recty; y++) {
2649                 for(x=0; x<R.rectx; x++, rz++) (*rz)>>= 4;
2650         }
2651         
2652         rz1= (int *)R.rectz;
2653         rz2= rz1+R.rectx;
2654         rz3= rz2+R.rectx;
2655
2656         if(R.r.mode & R_OSA) {
2657                 cp= (char *)(R.rectaccu+R.rectx);
2658         }
2659         else {
2660                 cp= (char *)(R.rectot+R.rectx);
2661         }
2662         cp+= 4;
2663         
2664         for(y=0; y<R.recty-2; y++) {
2665
2666                 for(x=0; x<R.rectx-2; x++, rz++, rz1++, rz2++, rz3++, cp+=4) {
2667                         
2668                         /* prevent overflow with sky z values */
2669                         zval1=   rz1[0] + 2*rz1[1] +   rz1[2];
2670                         zval2=  2*rz2[0]           + 2*rz2[2];
2671                         zval3=   rz3[0] + 2*rz3[1] +   rz3[2];
2672                         
2673                         col= abs ( 4*rz2[1] - (zval1 + zval2 + zval3)/3 );
2674                         
2675                         col >>= 5;
2676                         if(col > (1<<16)) col= (1<<16);
2677                         else col= (R.r.edgeint*col)>>8;
2678                         
2679                         if(col>0) {
2680                                 if(col>255) col= 255;
2681                                 
2682                                 if(R.r.mode & R_OSA) {
2683                                         col/= R.osa;
2684                                         
2685                                         val= cp[3]+col;
2686                                         if(val>255) cp[3]= 255; else cp[3]= val;
2687                                 }
2688                                 else {
2689                                         val= cp[0]- col;
2690                                         if(val<0) cp[0]= 0; else cp[0]= val;
2691                                         val= cp[1]- col;
2692                                         if(val<0) cp[1]= 0; else cp[1]= val;
2693                                         val= cp[2]- col;
2694                                         if(val<0) cp[2]= 0; else cp[2]= val;
2695                                 }
2696                         }
2697                 }
2698                 rz++;
2699                 rz1+= 2;
2700                 rz2+= 2;
2701                 rz3+= 2;
2702                 cp+= 8;
2703         }
2704
2705 }
2706
2707 /* ********************* MAINLOOPS ******************** */
2708 struct renderlineDA {
2709         long *rd;
2710         int *rz;
2711         float *rb1, *rb2, *rb3;
2712         float *acol;
2713         int y;
2714 };
2715
2716 static int do_renderlineDA(void *poin)
2717 {
2718         struct renderlineDA *rl= poin;
2719         PixStr *ps;
2720         float xs, ys;
2721         float fcol[4], *acol=NULL, *rb1, *rb2, *rb3;
2722         long *rd= rl->rd;
2723         int zbuf, samp, curmask, face, mask, fullmask;
2724         int b, x, full_osa, seed;
2725         
2726         /* we set per pixel a fixed seed, for random AO and shadow samples */
2727         seed= (R.ystart + rl->y + R.afmy)*R.r.xsch + R.xstart + R.afmx;
2728         
2729         fullmask= (1<<R.osa)-1;
2730         rb1= rl->rb1;
2731         rb2= rl->rb2;
2732         rb3= rl->rb3;
2733         
2734         if(R.flag & R_ZTRA) {           /* zbuf tra */
2735                 abufsetrow(rl->acol, rl->y); 
2736                 acol= rl->acol;
2737         }
2738
2739         for(x=0; x<R.rectx; x++, rd++) {
2740                 
2741                 BLI_thread_srandom(rl->y & 1, seed+x);
2742                 
2743                 ps= (PixStr *)(*rd);
2744                 mask= 0;
2745                 
2746                 /* complex loop, because empty spots are sky, without mask */
2747                 while(TRUE) {
2748                         
2749                         if(ps==NULL) {
2750                                 face= 0;
2751                                 curmask= (~mask) & fullmask;
2752                                 zbuf= *(rl->rz+x);
2753                         }
2754                         else {
2755                                 face= ps->facenr;
2756                                 curmask= ps->mask;
2757                                 zbuf= ps->z;
2758                         }
2759                         
2760                         /* check osa level */
2761                         if(face==0) full_osa= 0;
2762                         else {
2763                                 VlakRen *vlr= RE_findOrAddVlak( (face-1) & 0x7FFFFF);
2764                                 full_osa= (vlr->flag & R_FULL_OSA);
2765                         }
2766                         
2767                         if(full_osa) {
2768                                 for(samp=0; samp<R.osa; samp++) {
2769                                         if(curmask & (1<<samp)) {
2770                                                 xs= (float)x + jit[samp][0];
2771                                                 ys= (float)rl->y + jit[samp][1];
2772                                                 shadepixel_sky(xs, ys, zbuf, face, (1<<samp), fcol);
2773                                                 
2774                                                 if(acol && acol[3]!=0.0) addAlphaOverFloat(fcol, acol);
2775                                                 if(do_gamma) {
2776                                                         fcol[0]= gammaCorrect(fcol[0]);
2777                                                         fcol[1]= gammaCorrect(fcol[1]);
2778                                                         fcol[2]= gammaCorrect(fcol[2]);
2779                                                 }
2780                                                 add_filt_fmask(1<<samp, fcol, rb1, rb2, rb3);
2781                                         }
2782                                 }
2783                         }
2784                         else {
2785                                 extern char *centmask;  // initrender.c
2786                                 extern float centLut[16];
2787                                 
2788                                 b= centmask[curmask];
2789                                 xs= (float)x+centLut[b & 15];
2790                                 ys= (float)rl->y+centLut[b>>4];
2791                                 shadepixel_sky(xs, ys, zbuf, face, curmask, fcol);
2792                                 
2793                                 if(acol && acol[3]!=0.0) addAlphaOverFloat(fcol, acol);
2794                                 
2795                                 if(do_gamma) {
2796                                         fcol[0]= gammaCorrect(fcol[0]);
2797                                         fcol[1]= gammaCorrect(fcol[1]);
2798                                         fcol[2]= gammaCorrect(fcol[2]);
2799                                 }
2800                                 add_filt_fmask(curmask, fcol, rb1, rb2, rb3);
2801                         }
2802                         
2803                         mask |= curmask;
2804                         
2805                         if(ps==NULL) break;
2806                         else ps= ps->next;
2807                 }
2808                 
2809                 rb1+=4; 
2810                 rb2+=4; 
2811                 rb3+=4;
2812                 if(acol) acol+=4;
2813         }
2814
2815         return 1;
2816 }
2817
2818 void zbufshadeDA(void)  /* Delta Accum Pixel Struct */
2819 {
2820         extern float Zjitx,Zjity;
2821         struct renderlineDA rl1, rl2;
2822         float xd, yd, *rf;
2823         long *rd;
2824         int *rz, *rp, *rt;
2825         float  *rowbuf1, *rowbuf2, *rowbuf3, *rowbuf0, *rowbuf1a, *rowbuf2a, *rb3;
2826         int a;
2827         short v, x, y;
2828
2829         R.rectdaps= MEM_callocN(sizeof(long)*R.rectx*R.recty+4,"zbufDArectd");
2830         
2831         if(R.flag & R_ZTRA) {
2832                 bgnaccumbuf();
2833                 rl1.acol= MEM_callocN((R.rectx+4)*4*sizeof(float), "Acol");
2834                 rl2.acol= MEM_callocN((R.rectx+4)*4*sizeof(float), "Acol");
2835         }
2836         
2837         psmteller= 0;
2838
2839         if(R.r.mode & R_EDGE) {
2840                 R.rectaccu= (int *)MEM_callocN(sizeof(int)*R.rectx*R.recty,"zbufshadeDA");