Cleanup: trailing space
[blender.git] / source / blender / render / intern / source / shadeoutput.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2006 Blender Foundation
19  * All rights reserved.
20  *
21  * Contributors: Hos, Robert Wenzlaff.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/render/intern/source/shadeoutput.c
27  *  \ingroup render
28  */
29
30 #include <stdio.h>
31 #include <float.h>
32 #include <math.h>
33 #include <string.h>
34
35 #include "BLI_math.h"
36 #include "BLI_utildefines.h"
37
38 #include "BKE_colorband.h"
39 #include "BKE_colortools.h"
40 #include "BKE_material.h"
41
42 #include "DNA_group_types.h"
43 #include "DNA_lamp_types.h"
44 #include "DNA_material_types.h"
45
46 /* local include */
47 #include "occlusion.h"
48 #include "render_types.h"
49 #include "rendercore.h"
50 #include "shadbuf.h"
51 #include "sss.h"
52 #include "texture.h"
53
54 #include "shading.h" /* own include */
55
56 #include "IMB_colormanagement.h"
57
58 /* could enable at some point but for now there are far too many conversions */
59 #ifdef __GNUC__
60 #  pragma GCC diagnostic ignored "-Wdouble-promotion"
61 #endif
62
63 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
64 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
65 /* only to be used here in this file, it's for speed */
66 extern struct Render R;
67 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
68
69 ListBase *get_lights(ShadeInput *shi)
70 {
71
72         if (R.r.scemode & R_BUTS_PREVIEW)
73                 return &R.lights;
74         if (shi->light_override)
75                 return &shi->light_override->gobject;
76         if (shi->mat && shi->mat->group)
77                 return &shi->mat->group->gobject;
78
79         return &R.lights;
80 }
81
82 #if 0
83 static void fogcolor(const float colf[3], float *rco, float *view)
84 {
85         float alpha, stepsize, startdist, dist, hor[4], zen[3], vec[3], dview[3];
86         float div=0.0f, distfac;
87
88         hor[0]= R.wrld.horr; hor[1]= R.wrld.horg; hor[2]= R.wrld.horb;
89         zen[0]= R.wrld.zenr; zen[1]= R.wrld.zeng; zen[2]= R.wrld.zenb;
90
91         copy_v3_v3(vec, rco);
92
93         /* we loop from cur coord to mist start in steps */
94         stepsize= 1.0f;
95
96         div= ABS(view[2]);
97         dview[0]= view[0]/(stepsize*div);
98         dview[1]= view[1]/(stepsize*div);
99         dview[2]= -stepsize;
100
101         startdist= -rco[2] + BLI_frand();
102         for (dist= startdist; dist>R.wrld.miststa; dist-= stepsize) {
103
104                 hor[0]= R.wrld.horr; hor[1]= R.wrld.horg; hor[2]= R.wrld.horb;
105                 alpha= 1.0f;
106                 do_sky_tex(vec, vec, NULL, hor, zen, &alpha);
107
108                 distfac= (dist-R.wrld.miststa)/R.wrld.mistdist;
109
110                 hor[3]= hor[0]*distfac*distfac;
111
112                 /* premul! */
113                 alpha= hor[3];
114                 hor[0]= hor[0]*alpha;
115                 hor[1]= hor[1]*alpha;
116                 hor[2]= hor[2]*alpha;
117                 addAlphaOverFloat(colf, hor);
118
119                 sub_v3_v3(vec, dview);
120         }
121 }
122 #endif
123
124 /* zcor is distance, co the 3d coordinate in eye space, return alpha */
125 float mistfactor(float zcor, float const co[3])
126 {
127         float fac, hi;
128
129         fac = zcor - R.wrld.miststa;    /* zcor is calculated per pixel */
130
131         /* fac= -co[2]-R.wrld.miststa; */
132
133         if (fac > 0.0f) {
134                 if (fac < R.wrld.mistdist) {
135
136                         fac = (fac / R.wrld.mistdist);
137
138                         if (R.wrld.mistype == 0) {
139                                 fac *= fac;
140                         }
141                         else if (R.wrld.mistype == 1) {
142                                 /* pass */
143                         }
144                         else {
145                                 fac = sqrtf(fac);
146                         }
147                 }
148                 else {
149                         fac = 1.0f;
150                 }
151         }
152         else {
153                 fac = 0.0f;
154         }
155
156         /* height switched off mist */
157         if (R.wrld.misthi!=0.0f && fac!=0.0f) {
158                 /* at height misthi the mist is completely gone */
159
160                 hi = R.viewinv[0][2] * co[0] +
161                      R.viewinv[1][2] * co[1] +
162                      R.viewinv[2][2] * co[2] +
163                      R.viewinv[3][2];
164
165                 if (hi > R.wrld.misthi) {
166                         fac = 0.0f;
167                 }
168                 else if (hi>0.0f) {
169                         hi= (R.wrld.misthi-hi)/R.wrld.misthi;
170                         fac*= hi*hi;
171                 }
172         }
173
174         return (1.0f-fac)* (1.0f-R.wrld.misi);
175 }
176
177 static void spothalo(struct LampRen *lar, ShadeInput *shi, float *intens)
178 {
179         double a, b, c, disc, nray[3], npos[3];
180         double t0, t1 = 0.0f, t2= 0.0f, t3;
181         float p1[3], p2[3], ladist, maxz = 0.0f, maxy = 0.0f, haint;
182         int cuts;
183         bool do_clip = true, use_yco = false;
184
185         *intens= 0.0f;
186         haint= lar->haint;
187
188         if (R.r.mode & R_ORTHO) {
189                 /* camera pos (view vector) cannot be used... */
190                 /* camera position (cox,coy,0) rotate around lamp */
191                 p1[0]= shi->co[0]-lar->co[0];
192                 p1[1]= shi->co[1]-lar->co[1];
193                 p1[2]= -lar->co[2];
194                 mul_m3_v3(lar->imat, p1);
195                 copy_v3db_v3fl(npos, p1);  /* npos is double! */
196
197                 /* pre-scale */
198                 npos[2] *= (double)lar->sh_zfac;
199         }
200         else {
201                 copy_v3db_v3fl(npos, lar->sh_invcampos);        /* in initlamp calculated */
202         }
203
204         /* rotate view */
205         copy_v3db_v3fl(nray, shi->view);
206         mul_m3_v3_double(lar->imat, nray);
207
208         if (R.wrld.mode & WO_MIST) {
209                 /* patchy... */
210                 haint *= mistfactor(-lar->co[2], lar->co);
211                 if (haint==0.0f) {
212                         return;
213                 }
214         }
215
216
217         /* rotate maxz */
218         if (shi->co[2]==0.0f) {
219                 do_clip = false;  /* for when halo at sky */
220         }
221         else {
222                 p1[0]= shi->co[0]-lar->co[0];
223                 p1[1]= shi->co[1]-lar->co[1];
224                 p1[2]= shi->co[2]-lar->co[2];
225
226                 maxz= lar->imat[0][2]*p1[0]+lar->imat[1][2]*p1[1]+lar->imat[2][2]*p1[2];
227                 maxz*= lar->sh_zfac;
228                 maxy= lar->imat[0][1]*p1[0]+lar->imat[1][1]*p1[1]+lar->imat[2][1]*p1[2];
229
230                 if (fabs(nray[2]) < FLT_EPSILON) {
231                         use_yco = true;
232                 }
233         }
234
235         /* scale z to make sure volume is normalized */
236         nray[2] *= (double)lar->sh_zfac;
237         /* nray does not need normalization */
238
239         ladist= lar->sh_zfac*lar->dist;
240
241         /* solve */
242         a = nray[0] * nray[0] + nray[1] * nray[1] - nray[2]*nray[2];
243         b = nray[0] * npos[0] + nray[1] * npos[1] - nray[2]*npos[2];
244         c = npos[0] * npos[0] + npos[1] * npos[1] - npos[2]*npos[2];
245
246         cuts= 0;
247         if (fabs(a) < DBL_EPSILON) {
248                 /*
249                  * Only one intersection point...
250                  */
251                 return;
252         }
253         else {
254                 disc = b*b - a*c;
255
256                 if (disc==0.0) {
257                         t1=t2= (-b)/ a;
258                         cuts= 2;
259                 }
260                 else if (disc > 0.0) {
261                         disc = sqrt(disc);
262                         t1 = (-b + disc) / a;
263                         t2 = (-b - disc) / a;
264                         cuts= 2;
265                 }
266         }
267         if (cuts==2) {
268                 int ok1=0, ok2=0;
269
270                 /* sort */
271                 if (t1>t2) {
272                         a= t1; t1= t2; t2= a;
273                 }
274
275                 /* z of intersection points with diabolo */
276                 p1[2]= npos[2] + t1*nray[2];
277                 p2[2]= npos[2] + t2*nray[2];
278
279                 /* evaluate both points */
280                 if (p1[2]<=0.0f) ok1= 1;
281                 if (p2[2]<=0.0f && t1!=t2) ok2= 1;
282
283                 /* at least 1 point with negative z */
284                 if (ok1==0 && ok2==0) return;
285
286                 /* intersction point with -ladist, the bottom of the cone */
287                 if (use_yco == false) {
288                         t3= ((double)(-ladist)-npos[2])/nray[2];
289
290                         /* de we have to replace one of the intersection points? */
291                         if (ok1) {
292                                 if (p1[2]<-ladist) t1= t3;
293                         }
294                         else {
295                                 t1= t3;
296                         }
297                         if (ok2) {
298                                 if (p2[2]<-ladist) t2= t3;
299                         }
300                         else {
301                                 t2= t3;
302                         }
303                 }
304                 else if (ok1==0 || ok2==0) return;
305
306                 /* at least 1 visible interesction point */
307                 if (t1<0.0 && t2<0.0) return;
308
309                 if (t1<0.0) t1= 0.0;
310                 if (t2<0.0) t2= 0.0;
311
312                 if (t1==t2) return;
313
314                 /* sort again to be sure */
315                 if (t1>t2) {
316                         a= t1; t1= t2; t2= a;
317                 }
318
319                 /* calculate t0: is the maximum visible z (when halo is intersected by face) */
320                 if (do_clip) {
321                         if (use_yco == false) t0 = ((double)maxz - npos[2]) / nray[2];
322                         else                  t0 = ((double)maxy - npos[1]) / nray[1];
323
324                         if (t0 < t1) return;
325                         if (t0 < t2) t2= t0;
326                 }
327
328                 /* calc points */
329                 p1[0]= npos[0] + t1*nray[0];
330                 p1[1]= npos[1] + t1*nray[1];
331                 p1[2]= npos[2] + t1*nray[2];
332                 p2[0]= npos[0] + t2*nray[0];
333                 p2[1]= npos[1] + t2*nray[1];
334                 p2[2]= npos[2] + t2*nray[2];
335
336
337                 /* now we have 2 points, make three lengths with it */
338
339                 a = len_v3(p1);
340                 b = len_v3(p2);
341                 c = len_v3v3(p1, p2);
342
343                 a/= ladist;
344                 a= sqrt(a);
345                 b/= ladist;
346                 b= sqrt(b);
347                 c/= ladist;
348
349                 *intens= c*( (1.0-a)+(1.0-b) );
350
351                 /* WATCH IT: do not clip a,b en c at 1.0, this gives nasty little overflows
352                  * at the edges (especially with narrow halos) */
353                 if (*intens<=0.0f) return;
354
355                 /* soft area */
356                 /* not needed because t0 has been used for p1/p2 as well */
357                 /* if (doclip && t0<t2) { */
358                 /*      *intens *= (t0-t1)/(t2-t1); */
359                 /* } */
360
361                 *intens *= haint;
362
363                 if (lar->shb && lar->shb->shadhalostep) {
364                         *intens *= shadow_halo(lar, p1, p2);
365                 }
366
367         }
368 }
369
370 void renderspothalo(ShadeInput *shi, float col[4], float alpha)
371 {
372         ListBase *lights;
373         GroupObject *go;
374         LampRen *lar;
375         float i;
376
377         if (alpha==0.0f) return;
378
379         lights= get_lights(shi);
380         for (go=lights->first; go; go= go->next) {
381                 lar= go->lampren;
382                 if (lar==NULL) continue;
383
384                 if (lar->type==LA_SPOT && (lar->mode & LA_HALO) && (lar->buftype != LA_SHADBUF_DEEP) && lar->haint>0) {
385
386                         if (lar->mode & LA_LAYER)
387                                 if (shi->vlr && (lar->lay & shi->obi->lay)==0)
388                                         continue;
389                         if ((lar->lay & shi->lay)==0)
390                                 continue;
391
392                         spothalo(lar, shi, &i);
393                         if (i > 0.0f) {
394                                 const float i_alpha = i * alpha;
395                                 col[0] += i_alpha * lar->r;
396                                 col[1] += i_alpha * lar->g;
397                                 col[2] += i_alpha * lar->b;
398                                 col[3] += i_alpha;  /* all premul */
399                         }
400                 }
401         }
402         /* clip alpha, is needed for unified 'alpha threshold' (vanillaRenderPipe.c) */
403         if (col[3]>1.0f) col[3]= 1.0f;
404 }
405
406
407
408 /* ---------------- shaders ----------------------- */
409
410 static double Normalize_d(double *n)
411 {
412         double d;
413
414         d= n[0]*n[0]+n[1]*n[1]+n[2]*n[2];
415
416         if (d>0.00000000000000001) {
417                 d= sqrt(d);
418
419                 n[0]/=d;
420                 n[1]/=d;
421                 n[2]/=d;
422         }
423         else {
424                 n[0]=n[1]=n[2]= 0.0;
425                 d= 0.0;
426         }
427         return d;
428 }
429
430 /* mix of 'real' fresnel and allowing control. grad defines blending gradient */
431 float fresnel_fac(const float view[3], const float vn[3], float grad, float fac)
432 {
433         float t1, t2;
434
435         if (fac==0.0f) return 1.0f;
436
437         t1 = dot_v3v3(view, vn);
438         if (t1>0.0f)  t2= 1.0f+t1;
439         else t2= 1.0f-t1;
440
441         t2= grad + (1.0f-grad)*powf(t2, fac);
442
443         if (t2<0.0f) return 0.0f;
444         else if (t2>1.0f) return 1.0f;
445         return t2;
446 }
447
448 static double saacos_d(double fac)
449 {
450         if (fac<= -1.0) return M_PI;
451         else if (fac>=1.0) return 0.0;
452         else return acos(fac);
453 }
454
455 /* Stoke's form factor. Need doubles here for extreme small area sizes */
456 static float area_lamp_energy(float (*area)[3], const float co[3], const float vn[3])
457 {
458         double fac;
459         double vec[4][3];       /* vectors of rendered co to vertices lamp */
460         double cross[4][3];     /* cross products of this */
461         double rad[4];          /* angles between vecs */
462
463         VECSUB(vec[0], co, area[0]);
464         VECSUB(vec[1], co, area[1]);
465         VECSUB(vec[2], co, area[2]);
466         VECSUB(vec[3], co, area[3]);
467
468         Normalize_d(vec[0]);
469         Normalize_d(vec[1]);
470         Normalize_d(vec[2]);
471         Normalize_d(vec[3]);
472
473         /* cross product */
474 #define CROSS(dest, a, b) \
475         { \
476                 dest[0]= a[1] * b[2] - a[2] * b[1]; \
477                 dest[1]= a[2] * b[0] - a[0] * b[2]; \
478                 dest[2]= a[0] * b[1] - a[1] * b[0]; \
479         } (void)0
480
481         CROSS(cross[0], vec[0], vec[1]);
482         CROSS(cross[1], vec[1], vec[2]);
483         CROSS(cross[2], vec[2], vec[3]);
484         CROSS(cross[3], vec[3], vec[0]);
485
486 #undef CROSS
487
488         Normalize_d(cross[0]);
489         Normalize_d(cross[1]);
490         Normalize_d(cross[2]);
491         Normalize_d(cross[3]);
492
493         /* angles */
494         rad[0]= vec[0][0]*vec[1][0]+ vec[0][1]*vec[1][1]+ vec[0][2]*vec[1][2];
495         rad[1]= vec[1][0]*vec[2][0]+ vec[1][1]*vec[2][1]+ vec[1][2]*vec[2][2];
496         rad[2]= vec[2][0]*vec[3][0]+ vec[2][1]*vec[3][1]+ vec[2][2]*vec[3][2];
497         rad[3]= vec[3][0]*vec[0][0]+ vec[3][1]*vec[0][1]+ vec[3][2]*vec[0][2];
498
499         rad[0]= saacos_d(rad[0]);
500         rad[1]= saacos_d(rad[1]);
501         rad[2]= saacos_d(rad[2]);
502         rad[3]= saacos_d(rad[3]);
503
504         /* Stoke formula */
505         fac=  rad[0]*(vn[0]*cross[0][0]+ vn[1]*cross[0][1]+ vn[2]*cross[0][2]);
506         fac+= rad[1]*(vn[0]*cross[1][0]+ vn[1]*cross[1][1]+ vn[2]*cross[1][2]);
507         fac+= rad[2]*(vn[0]*cross[2][0]+ vn[1]*cross[2][1]+ vn[2]*cross[2][2]);
508         fac+= rad[3]*(vn[0]*cross[3][0]+ vn[1]*cross[3][1]+ vn[2]*cross[3][2]);
509
510         if (fac<=0.0) return 0.0;
511         return fac;
512 }
513
514 static float area_lamp_energy_multisample(LampRen *lar, const float co[3], float *vn)
515 {
516         /* corner vectors are moved around according lamp jitter */
517         float *jitlamp= lar->jitter, vec[3];
518         float area[4][3], intens= 0.0f;
519         int a= lar->ray_totsamp;
520
521         /* test if co is behind lamp */
522         sub_v3_v3v3(vec, co, lar->co);
523         if (dot_v3v3(vec, lar->vec) < 0.0f)
524                 return 0.0f;
525
526         while (a--) {
527                 vec[0]= jitlamp[0];
528                 vec[1]= jitlamp[1];
529                 vec[2]= 0.0f;
530                 mul_m3_v3(lar->mat, vec);
531
532                 add_v3_v3v3(area[0], lar->area[0], vec);
533                 add_v3_v3v3(area[1], lar->area[1], vec);
534                 add_v3_v3v3(area[2], lar->area[2], vec);
535                 add_v3_v3v3(area[3], lar->area[3], vec);
536
537                 intens+= area_lamp_energy(area, co, vn);
538
539                 jitlamp+= 2;
540         }
541         intens /= (float)lar->ray_totsamp;
542
543         return pow(intens * lar->areasize, lar->k);     /* corrected for buttons size and lar->dist^2 */
544 }
545
546 static float spec(float inp, int hard)
547 {
548         float b1;
549
550         if (inp>=1.0f) return 1.0f;
551         else if (inp<=0.0f) return 0.0f;
552
553         b1= inp*inp;
554         /* avoid FPE */
555         if (b1<0.01f) b1= 0.01f;
556
557         if ((hard & 1)==0)  inp= 1.0f;
558         if (hard & 2)  inp*= b1;
559         b1*= b1;
560         if (hard & 4)  inp*= b1;
561         b1*= b1;
562         if (hard & 8)  inp*= b1;
563         b1*= b1;
564         if (hard & 16) inp*= b1;
565         b1*= b1;
566
567         /* avoid FPE */
568         if (b1<0.001f) b1= 0.0f;
569
570         if (hard & 32) inp*= b1;
571         b1*= b1;
572         if (hard & 64) inp*=b1;
573         b1*= b1;
574         if (hard & 128) inp*=b1;
575
576         if (b1<0.001f) b1= 0.0f;
577
578         if (hard & 256) {
579                 b1*= b1;
580                 inp*=b1;
581         }
582
583         return inp;
584 }
585
586 static float Phong_Spec(const float n[3], const float l[3], const float v[3], int hard, int tangent )
587 {
588         float h[3];
589         float rslt;
590
591         h[0] = l[0] + v[0];
592         h[1] = l[1] + v[1];
593         h[2] = l[2] + v[2];
594         normalize_v3(h);
595
596         rslt = h[0]*n[0] + h[1]*n[1] + h[2]*n[2];
597         if (tangent) rslt= sasqrt(1.0f - rslt*rslt);
598
599         if ( rslt > 0.0f ) rslt= spec(rslt, hard);
600         else rslt = 0.0f;
601
602         return rslt;
603 }
604
605
606 /* reduced cook torrance spec (for off-specular peak) */
607 static float CookTorr_Spec(const float n[3], const float l[3], const float v[3], int hard, int tangent)
608 {
609         float i, nh, nv, h[3];
610
611         h[0]= v[0]+l[0];
612         h[1]= v[1]+l[1];
613         h[2]= v[2]+l[2];
614         normalize_v3(h);
615
616         nh= n[0]*h[0]+n[1]*h[1]+n[2]*h[2];
617         if (tangent) nh= sasqrt(1.0f - nh*nh);
618         else if (nh<0.0f) return 0.0f;
619
620         nv= n[0]*v[0]+n[1]*v[1]+n[2]*v[2];
621         if (tangent) nv= sasqrt(1.0f - nv*nv);
622         else if (nv<0.0f) nv= 0.0f;
623
624         i= spec(nh, hard);
625
626         i= i/(0.1f+nv);
627         return i;
628 }
629
630 /* Blinn spec */
631 static float Blinn_Spec(const float n[3], const float l[3], const float v[3], float refrac, float spec_power, int tangent)
632 {
633         float i, nh, nv, nl, vh, h[3];
634         float a, b, c, g=0.0f, p, f, ang;
635
636         if (refrac < 1.0f) return 0.0f;
637         if (spec_power == 0.0f) return 0.0f;
638
639         /* conversion from 'hardness' (1-255) to 'spec_power' (50 maps at 0.1) */
640         if (spec_power<100.0f)
641                 spec_power = sqrtf(1.0f / spec_power);
642         else spec_power= 10.0f/spec_power;
643
644         h[0]= v[0]+l[0];
645         h[1]= v[1]+l[1];
646         h[2]= v[2]+l[2];
647         normalize_v3(h);
648
649         nh= n[0]*h[0]+n[1]*h[1]+n[2]*h[2]; /* Dot product between surface normal and half-way vector */
650         if (tangent) nh= sasqrt(1.0f - nh*nh);
651         else if (nh<0.0f) return 0.0f;
652
653         nv= n[0]*v[0]+n[1]*v[1]+n[2]*v[2]; /* Dot product between surface normal and view vector */
654         if (tangent) nv= sasqrt(1.0f - nv*nv);
655         if (nv<=0.01f) nv= 0.01f;                               /* hrms... */
656
657         nl= n[0]*l[0]+n[1]*l[1]+n[2]*l[2]; /* Dot product between surface normal and light vector */
658         if (tangent) nl= sasqrt(1.0f - nl*nl);
659         if (nl<=0.01f) {
660                 return 0.0f;
661         }
662
663         vh= v[0]*h[0]+v[1]*h[1]+v[2]*h[2]; /* Dot product between view vector and half-way vector */
664         if (vh<=0.0f) vh= 0.01f;
665
666         a = 1.0f;
667         b = (2.0f*nh*nv)/vh;
668         c = (2.0f*nh*nl)/vh;
669
670         if ( a < b && a < c ) g = a;
671         else if ( b < a && b < c ) g = b;
672         else if ( c < a && c < b ) g = c;
673
674         p = sqrt((double)((refrac * refrac)+(vh * vh) - 1.0f));
675         f = (((p-vh)*(p-vh))/((p+vh)*(p+vh)))*(1+((((vh*(p+vh))-1.0f)*((vh*(p+vh))-1.0f))/(((vh*(p-vh))+1.0f)*((vh*(p-vh))+1.0f))));
676         ang = saacos(nh);
677
678         i= f * g * exp((double)(-(ang*ang) / (2.0f*spec_power*spec_power)));
679         if (i<0.0f) i= 0.0f;
680
681         return i;
682 }
683
684 /* cartoon render spec */
685 static float Toon_Spec(const float n[3], const float l[3], const float v[3], float size, float smooth, int tangent)
686 {
687         float h[3];
688         float ang;
689         float rslt;
690
691         h[0] = l[0] + v[0];
692         h[1] = l[1] + v[1];
693         h[2] = l[2] + v[2];
694         normalize_v3(h);
695
696         rslt = h[0]*n[0] + h[1]*n[1] + h[2]*n[2];
697         if (tangent) rslt = sasqrt(1.0f - rslt*rslt);
698
699         ang = saacos( rslt );
700
701         if ( ang < size ) rslt = 1.0f;
702         else if ( ang >= (size + smooth) || smooth == 0.0f ) rslt = 0.0f;
703         else rslt = 1.0f - ((ang - size) / smooth);
704
705         return rslt;
706 }
707
708 /* Ward isotropic gaussian spec */
709 static float WardIso_Spec(const float n[3], const float l[3], const float v[3], float rms, int tangent)
710 {
711         float i, nh, nv, nl, h[3], angle, alpha;
712
713
714         /* half-way vector */
715         h[0] = l[0] + v[0];
716         h[1] = l[1] + v[1];
717         h[2] = l[2] + v[2];
718         normalize_v3(h);
719
720         nh = n[0]*h[0]+n[1]*h[1]+n[2]*h[2]; /* Dot product between surface normal and half-way vector */
721         if (tangent) nh = sasqrt(1.0f - nh*nh);
722         if (nh<=0.0f) nh = 0.001f;
723
724         nv = n[0]*v[0]+n[1]*v[1]+n[2]*v[2]; /* Dot product between surface normal and view vector */
725         if (tangent) nv = sasqrt(1.0f - nv*nv);
726         if (nv<=0.0f) nv = 0.001f;
727
728         nl = n[0]*l[0]+n[1]*l[1]+n[2]*l[2]; /* Dot product between surface normal and light vector */
729         if (tangent) nl = sasqrt(1.0f - nl*nl);
730         if (nl<=0.0f) nl = 0.001f;
731
732         angle = tanf(saacos(nh));
733         alpha = MAX2(rms, 0.001f);
734
735         i= nl * (1.0f/(4.0f*(float)M_PI*alpha*alpha)) * (expf( -(angle*angle)/(alpha*alpha))/(sqrtf(nv*nl)));
736
737         return i;
738 }
739
740 /* cartoon render diffuse */
741 static float Toon_Diff(const float n[3], const float l[3], const float UNUSED(v[3]), float size, float smooth)
742 {
743         float rslt, ang;
744
745         rslt = n[0]*l[0] + n[1]*l[1] + n[2]*l[2];
746
747         ang = saacos(rslt);
748
749         if ( ang < size ) rslt = 1.0f;
750         else if ( ang >= (size + smooth) || smooth == 0.0f ) rslt = 0.0f;
751         else rslt = 1.0f - ((ang - size) / smooth);
752
753         return rslt;
754 }
755
756 /* Oren Nayar diffuse */
757
758 /* 'nl' is either dot product, or return value of area light */
759 /* in latter case, only last multiplication uses 'nl' */
760 static float OrenNayar_Diff(float nl, const float n[3], const float l[3], const float v[3], float rough )
761 {
762         float i/*, nh*/, nv /*, vh */, realnl, h[3];
763         float a, b, t, A, B;
764         float Lit_A, View_A, Lit_B[3], View_B[3];
765
766         h[0]= v[0]+l[0];
767         h[1]= v[1]+l[1];
768         h[2]= v[2]+l[2];
769         normalize_v3(h);
770
771         /* nh= n[0]*h[0]+n[1]*h[1]+n[2]*h[2]; */ /* Dot product between surface normal and half-way vector */
772         /* if (nh<0.0f) nh = 0.0f; */
773
774         nv= n[0]*v[0]+n[1]*v[1]+n[2]*v[2]; /* Dot product between surface normal and view vector */
775         if (nv<=0.0f) nv= 0.0f;
776
777         realnl= n[0]*l[0]+n[1]*l[1]+n[2]*l[2]; /* Dot product between surface normal and light vector */
778         if (realnl<=0.0f) return 0.0f;
779         if (nl<0.0f) return 0.0f;               /* value from area light */
780
781         /* vh= v[0]*h[0]+v[1]*h[1]+v[2]*h[2]; */ /* Dot product between view vector and halfway vector */
782         /* if (vh<=0.0f) vh= 0.0f; */
783
784         Lit_A = saacos(realnl);
785         View_A = saacos( nv );
786
787         Lit_B[0] = l[0] - (realnl * n[0]);
788         Lit_B[1] = l[1] - (realnl * n[1]);
789         Lit_B[2] = l[2] - (realnl * n[2]);
790         normalize_v3(Lit_B);
791
792         View_B[0] = v[0] - (nv * n[0]);
793         View_B[1] = v[1] - (nv * n[1]);
794         View_B[2] = v[2] - (nv * n[2]);
795         normalize_v3(View_B);
796
797         t = Lit_B[0]*View_B[0] + Lit_B[1]*View_B[1] + Lit_B[2]*View_B[2];
798         if ( t < 0 ) t = 0;
799
800         if ( Lit_A > View_A ) {
801                 a = Lit_A;
802                 b = View_A;
803         }
804         else {
805                 a = View_A;
806                 b = Lit_A;
807         }
808
809         A = 1.0f - (0.5f * ((rough * rough) / ((rough * rough) + 0.33f)));
810         B = 0.45f * ((rough * rough) / ((rough * rough) + 0.09f));
811
812         b*= 0.95f;      /* prevent tangens from shooting to inf, 'nl' can be not a dot product here. */
813                                 /* overflow only happens with extreme size area light, and higher roughness */
814         i = nl * ( A + ( B * t * sinf(a) * tanf(b) ) );
815
816         return i;
817 }
818
819 /* Minnaert diffuse */
820 static float Minnaert_Diff(float nl, const float n[3], const float v[3], float darkness)
821 {
822         float i, nv;
823
824         /* nl = dot product between surface normal and light vector */
825         if (nl <= 0.0f)
826                 return 0.0f;
827
828         /* nv = dot product between surface normal and view vector */
829         nv = dot_v3v3(n, v);
830         if (nv < 0.0f)
831                 nv = 0.0f;
832
833         if (darkness <= 1.0f)
834                 i = nl * pow(max_ff(nv * nl, 0.1f), (darkness - 1.0f) ); /*The Real model*/
835         else
836                 i = nl * pow( (1.001f - nv), (darkness  - 1.0f) ); /*Nvidia model*/
837
838         return i;
839 }
840
841 static float Fresnel_Diff(float *vn, float *lv, float *UNUSED(view), float fac_i, float fac)
842 {
843         return fresnel_fac(lv, vn, fac_i, fac);
844 }
845
846 /* --------------------------------------------- */
847 /* also called from texture.c */
848 void calc_R_ref(ShadeInput *shi)
849 {
850         float i;
851
852         /* shi->vn dot shi->view */
853         i= -2*(shi->vn[0]*shi->view[0]+shi->vn[1]*shi->view[1]+shi->vn[2]*shi->view[2]);
854
855         shi->ref[0]= (shi->view[0]+i*shi->vn[0]);
856         shi->ref[1]= (shi->view[1]+i*shi->vn[1]);
857         shi->ref[2]= (shi->view[2]+i*shi->vn[2]);
858         if (shi->osatex) {
859                 if (shi->vlr->flag & R_SMOOTH) {
860                         i= -2*( (shi->vn[0]+shi->dxno[0])*(shi->view[0]+shi->dxview) +
861                                 (shi->vn[1]+shi->dxno[1])*shi->view[1]+ (shi->vn[2]+shi->dxno[2])*shi->view[2] );
862
863                         shi->dxref[0]= shi->ref[0]- ( shi->view[0]+shi->dxview+i*(shi->vn[0]+shi->dxno[0]));
864                         shi->dxref[1]= shi->ref[1]- (shi->view[1]+ i*(shi->vn[1]+shi->dxno[1]));
865                         shi->dxref[2]= shi->ref[2]- (shi->view[2]+ i*(shi->vn[2]+shi->dxno[2]));
866
867                         i= -2*( (shi->vn[0]+shi->dyno[0])*shi->view[0]+
868                                 (shi->vn[1]+shi->dyno[1])*(shi->view[1]+shi->dyview)+ (shi->vn[2]+shi->dyno[2])*shi->view[2] );
869
870                         shi->dyref[0]= shi->ref[0]- (shi->view[0]+ i*(shi->vn[0]+shi->dyno[0]));
871                         shi->dyref[1]= shi->ref[1]- (shi->view[1]+shi->dyview+i*(shi->vn[1]+shi->dyno[1]));
872                         shi->dyref[2]= shi->ref[2]- (shi->view[2]+ i*(shi->vn[2]+shi->dyno[2]));
873
874                 }
875                 else {
876
877                         i= -2*( shi->vn[0]*(shi->view[0]+shi->dxview) +
878                                 shi->vn[1]*shi->view[1]+ shi->vn[2]*shi->view[2] );
879
880                         shi->dxref[0]= shi->ref[0]- (shi->view[0]+shi->dxview+i*shi->vn[0]);
881                         shi->dxref[1]= shi->ref[1]- (shi->view[1]+ i*shi->vn[1]);
882                         shi->dxref[2]= shi->ref[2]- (shi->view[2]+ i*shi->vn[2]);
883
884                         i= -2*( shi->vn[0]*shi->view[0]+
885                                 shi->vn[1]*(shi->view[1]+shi->dyview)+ shi->vn[2]*shi->view[2] );
886
887                         shi->dyref[0]= shi->ref[0]- (shi->view[0]+ i*shi->vn[0]);
888                         shi->dyref[1]= shi->ref[1]- (shi->view[1]+shi->dyview+i*shi->vn[1]);
889                         shi->dyref[2]= shi->ref[2]- (shi->view[2]+ i*shi->vn[2]);
890                 }
891         }
892
893 }
894
895 /* called from rayshade.c */
896 void shade_color(ShadeInput *shi, ShadeResult *shr)
897 {
898         Material *ma= shi->mat;
899
900         if (ma->mode & (MA_FACETEXTURE)) {
901                 shi->r= shi->vcol[0];
902                 shi->g= shi->vcol[1];
903                 shi->b= shi->vcol[2];
904                 if (ma->mode & (MA_FACETEXTURE_ALPHA))
905                         shi->alpha= shi->vcol[3];
906         }
907         else if (ma->mode & (MA_VERTEXCOLP)) {
908                 float neg_alpha = 1.0f - shi->vcol[3];
909                 shi->r= shi->r*neg_alpha + shi->vcol[0]*shi->vcol[3];
910                 shi->g= shi->g*neg_alpha + shi->vcol[1]*shi->vcol[3];
911                 shi->b= shi->b*neg_alpha + shi->vcol[2]*shi->vcol[3];
912         }
913
914         if (ma->texco)
915                 do_material_tex(shi, &R);
916
917         if (ma->fresnel_tra!=0.0f)
918                 shi->alpha*= fresnel_fac(shi->view, shi->vn, ma->fresnel_tra_i, ma->fresnel_tra);
919
920         if (!(shi->mode & MA_TRANSP)) shi->alpha= 1.0f;
921
922         shr->diff[0]= shi->r;
923         shr->diff[1]= shi->g;
924         shr->diff[2]= shi->b;
925         shr->alpha= shi->alpha;
926
927         /* modulate by the object color */
928         if ((ma->shade_flag & MA_OBCOLOR) && shi->obr->ob) {
929                 float obcol[4];
930
931                 copy_v4_v4(obcol, shi->obr->ob->col);
932                 CLAMP(obcol[3], 0.0f, 1.0f);
933
934                 shr->diff[0] *= obcol[0];
935                 shr->diff[1] *= obcol[1];
936                 shr->diff[2] *= obcol[2];
937                 if (shi->mode & MA_TRANSP) shr->alpha *= obcol[3];
938         }
939
940         copy_v3_v3(shr->diffshad, shr->diff);
941 }
942
943 /* ramp for at end of shade */
944 static void ramp_diffuse_result(float *diff, ShadeInput *shi)
945 {
946         Material *ma= shi->mat;
947         float col[4];
948
949         if (ma->ramp_col) {
950                 if (ma->rampin_col==MA_RAMP_IN_RESULT) {
951                         float fac = IMB_colormanagement_get_luminance(diff);
952                         BKE_colorband_evaluate(ma->ramp_col, fac, col);
953
954                         /* blending method */
955                         fac= col[3]*ma->rampfac_col;
956
957                         ramp_blend(ma->rampblend_col, diff, fac, col);
958                 }
959         }
960 }
961
962 /* r,g,b denote energy, ramp is used with different values to make new material color */
963 static void add_to_diffuse(float diff[3], const ShadeInput *shi, const float is, const float rgb[3])
964 {
965         Material *ma= shi->mat;
966
967         if (ma->ramp_col && (ma->mode & MA_RAMP_COL)) {
968
969                 /* MA_RAMP_IN_RESULT is exceptional */
970                 if (ma->rampin_col==MA_RAMP_IN_RESULT) {
971                         /* normal add */
972                         diff[0] += rgb[0] * shi->r;
973                         diff[1] += rgb[1] * shi->g;
974                         diff[2] += rgb[2] * shi->b;
975                 }
976                 else {
977                         float colt[3], col[4];
978                         float fac;
979
980                         /* input */
981                         switch (ma->rampin_col) {
982                                 case MA_RAMP_IN_ENERGY:
983                                         fac = IMB_colormanagement_get_luminance(rgb);
984                                         break;
985                                 case MA_RAMP_IN_SHADER:
986                                         fac = is;
987                                         break;
988                                 case MA_RAMP_IN_NOR:
989                                         fac = dot_v3v3(shi->view, shi->vn);
990                                         break;
991                                 default:
992                                         fac = 0.0f;
993                                         break;
994                         }
995
996                         BKE_colorband_evaluate(ma->ramp_col, fac, col);
997
998                         /* blending method */
999                         fac = col[3] * ma->rampfac_col;
1000                         copy_v3_v3(colt, &shi->r);
1001
1002                         ramp_blend(ma->rampblend_col, colt, fac, col);
1003
1004                         /* output to */
1005                         diff[0] += rgb[0] * colt[0];
1006                         diff[1] += rgb[1] * colt[1];
1007                         diff[2] += rgb[2] * colt[2];
1008                 }
1009         }
1010         else {
1011                 diff[0] += rgb[0] * shi->r;
1012                 diff[1] += rgb[1] * shi->g;
1013                 diff[2] += rgb[2] * shi->b;
1014         }
1015 }
1016
1017 static void ramp_spec_result(float spec_col[3], ShadeInput *shi)
1018 {
1019         Material *ma= shi->mat;
1020
1021         if (ma->ramp_spec && (ma->rampin_spec==MA_RAMP_IN_RESULT)) {
1022                 float col[4];
1023                 float fac = IMB_colormanagement_get_luminance(spec_col);
1024
1025                 BKE_colorband_evaluate(ma->ramp_spec, fac, col);
1026
1027                 /* blending method */
1028                 fac= col[3]*ma->rampfac_spec;
1029
1030                 ramp_blend(ma->rampblend_spec, spec_col, fac, col);
1031
1032         }
1033 }
1034
1035 /* is = dot product shade, t = spec energy */
1036 static void do_specular_ramp(ShadeInput *shi, float is, float t, float spec[3])
1037 {
1038         Material *ma= shi->mat;
1039
1040         spec[0]= shi->specr;
1041         spec[1]= shi->specg;
1042         spec[2]= shi->specb;
1043
1044         /* MA_RAMP_IN_RESULT is exception */
1045         if (ma->ramp_spec && (ma->rampin_spec!=MA_RAMP_IN_RESULT)) {
1046                 float fac;
1047                 float col[4];
1048
1049                 /* input */
1050                 switch (ma->rampin_spec) {
1051                 case MA_RAMP_IN_ENERGY:
1052                         fac= t;
1053                         break;
1054                 case MA_RAMP_IN_SHADER:
1055                         fac= is;
1056                         break;
1057                 case MA_RAMP_IN_NOR:
1058                         fac= shi->view[0]*shi->vn[0] + shi->view[1]*shi->vn[1] + shi->view[2]*shi->vn[2];
1059                         break;
1060                 default:
1061                         fac= 0.0f;
1062                         break;
1063                 }
1064
1065                 BKE_colorband_evaluate(ma->ramp_spec, fac, col);
1066
1067                 /* blending method */
1068                 fac= col[3]*ma->rampfac_spec;
1069
1070                 ramp_blend(ma->rampblend_spec, spec, fac, col);
1071         }
1072 }
1073
1074 /* pure AO, check for raytrace and world should have been done */
1075 /* preprocess, textures were not done, don't use shi->amb for that reason */
1076 void ambient_occlusion(ShadeInput *shi)
1077 {
1078         if ((R.wrld.ao_gather_method == WO_AOGATHER_APPROX) && shi->mat->amb!=0.0f) {
1079                 sample_occ(&R, shi);
1080         }
1081         else if ((R.r.mode & R_RAYTRACE) && shi->mat->amb!=0.0f) {
1082                 ray_ao(shi, shi->ao, shi->env);
1083         }
1084         else {
1085                 shi->ao[0]= shi->ao[1]= shi->ao[2]= 1.0f;
1086                 zero_v3(shi->env);
1087                 zero_v3(shi->indirect);
1088         }
1089 }
1090
1091
1092 /* wrld mode was checked for */
1093 static void ambient_occlusion_apply(ShadeInput *shi, ShadeResult *shr)
1094 {
1095         float f= R.wrld.aoenergy;
1096         float tmp[3], tmpspec[3];
1097
1098         if (!((R.r.mode & R_RAYTRACE) || R.wrld.ao_gather_method == WO_AOGATHER_APPROX))
1099                 return;
1100         if (f == 0.0f)
1101                 return;
1102
1103         if (R.wrld.aomix==WO_AOADD) {
1104                 shr->combined[0] += shi->ao[0]*shi->r*shi->refl*f;
1105                 shr->combined[1] += shi->ao[1]*shi->g*shi->refl*f;
1106                 shr->combined[2] += shi->ao[2]*shi->b*shi->refl*f;
1107         }
1108         else if (R.wrld.aomix==WO_AOMUL) {
1109                 mul_v3_v3v3(tmp, shr->combined, shi->ao);
1110                 mul_v3_v3v3(tmpspec, shr->spec, shi->ao);
1111
1112                 if (f == 1.0f) {
1113                         copy_v3_v3(shr->combined, tmp);
1114                         copy_v3_v3(shr->spec, tmpspec);
1115                 }
1116                 else {
1117                         interp_v3_v3v3(shr->combined, shr->combined, tmp, f);
1118                         interp_v3_v3v3(shr->spec, shr->spec, tmpspec, f);
1119                 }
1120         }
1121 }
1122
1123 void environment_lighting_apply(ShadeInput *shi, ShadeResult *shr)
1124 {
1125         float f= R.wrld.ao_env_energy*shi->amb;
1126
1127         if (!((R.r.mode & R_RAYTRACE) || R.wrld.ao_gather_method == WO_AOGATHER_APPROX))
1128                 return;
1129         if (f == 0.0f)
1130                 return;
1131
1132         shr->combined[0] += shi->env[0]*shi->r*shi->refl*f;
1133         shr->combined[1] += shi->env[1]*shi->g*shi->refl*f;
1134         shr->combined[2] += shi->env[2]*shi->b*shi->refl*f;
1135 }
1136
1137 static void indirect_lighting_apply(ShadeInput *shi, ShadeResult *shr)
1138 {
1139         float f= R.wrld.ao_indirect_energy;
1140
1141         if (!((R.r.mode & R_RAYTRACE) || R.wrld.ao_gather_method == WO_AOGATHER_APPROX))
1142                 return;
1143         if (f == 0.0f)
1144                 return;
1145
1146         shr->combined[0] += shi->indirect[0]*shi->r*shi->refl*f;
1147         shr->combined[1] += shi->indirect[1]*shi->g*shi->refl*f;
1148         shr->combined[2] += shi->indirect[2]*shi->b*shi->refl*f;
1149 }
1150
1151 /* result written in shadfac */
1152 void lamp_get_shadow(LampRen *lar, ShadeInput *shi, float inp, float shadfac[4], int do_real)
1153 {
1154         LampShadowSubSample *lss= &(lar->shadsamp[shi->thread].s[shi->sample]);
1155
1156         if (do_real || lss->samplenr!=shi->samplenr) {
1157
1158                 shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 1.0f;
1159
1160                 if (lar->shb) {
1161                         if (lar->buftype==LA_SHADBUF_IRREGULAR)
1162                                 shadfac[3]= ISB_getshadow(shi, lar->shb);
1163                         else
1164                                 shadfac[3] = testshadowbuf(&R, lar->shb, shi->co, shi->dxco, shi->dyco, inp, shi->mat->lbias);
1165                 }
1166                 else if (lar->mode & LA_SHAD_RAY) {
1167                         ray_shadow(shi, lar, shadfac);
1168                 }
1169
1170                 if (shi->depth==0) {
1171                         copy_v4_v4(lss->shadfac, shadfac);
1172                         lss->samplenr= shi->samplenr;
1173                 }
1174         }
1175         else {
1176                 copy_v4_v4(shadfac, lss->shadfac);
1177         }
1178 }
1179
1180 /* lampdistance and spot angle, writes in lv and dist */
1181 float lamp_get_visibility(LampRen *lar, const float co[3], float lv[3], float *dist)
1182 {
1183         if (lar->type==LA_SUN || lar->type==LA_HEMI) {
1184                 *dist= 1.0f;
1185                 copy_v3_v3(lv, lar->vec);
1186                 return 1.0f;
1187         }
1188         else {
1189                 float visifac= 1.0f, visifac_r;
1190
1191                 sub_v3_v3v3(lv, co, lar->co);
1192                 mul_v3_fl(lv, 1.0f / (*dist = len_v3(lv)));
1193
1194                 /* area type has no quad or sphere option */
1195                 if (lar->type==LA_AREA) {
1196                         /* area is single sided */
1197                         //if (dot_v3v3(lv, lar->vec) > 0.0f)
1198                         //      visifac= 1.0f;
1199                         //else
1200                         //      visifac= 0.0f;
1201                 }
1202                 else {
1203                         switch (lar->falloff_type) {
1204                                 case LA_FALLOFF_CONSTANT:
1205                                         visifac = 1.0f;
1206                                         break;
1207                                 case LA_FALLOFF_INVLINEAR:
1208                                         visifac = lar->dist/(lar->dist + dist[0]);
1209                                         break;
1210                                 case LA_FALLOFF_INVSQUARE:
1211                                         /* NOTE: This seems to be a hack since commit r12045 says this
1212                                          * option is similar to old Quad, but with slight changes.
1213                                          * Correct inv square would be (which would be old Quad):
1214                                          * visifac = lar->distkw / (lar->distkw + dist[0]*dist[0]);
1215                                          */
1216                                         visifac = lar->dist / (lar->dist + dist[0]*dist[0]);
1217                                         break;
1218                                 case LA_FALLOFF_SLIDERS:
1219                                         if (lar->ld1>0.0f)
1220                                                 visifac= lar->dist/(lar->dist+lar->ld1*dist[0]);
1221                                         if (lar->ld2>0.0f)
1222                                                 visifac*= lar->distkw/(lar->distkw+lar->ld2*dist[0]*dist[0]);
1223                                         break;
1224                                 case LA_FALLOFF_INVCOEFFICIENTS:
1225                                         visifac_r = lar->coeff_const +
1226                                                                 lar->coeff_lin * dist[0] +
1227                                                                 lar->coeff_quad * dist[0] * dist[0];
1228                                         if (visifac_r > 0.0)
1229                                                 visifac = 1.0 / visifac_r;
1230                                         else
1231                                                 visifac = 0.0;
1232                                         break;
1233                                 case LA_FALLOFF_CURVE:
1234                                         /* curvemapping_initialize is called from #add_render_lamp */
1235                                         visifac = curvemapping_evaluateF(lar->curfalloff, 0, dist[0]/lar->dist);
1236                                         break;
1237                         }
1238
1239                         if (lar->mode & LA_SPHERE) {
1240                                 float t= lar->dist - dist[0];
1241                                 if (t<=0.0f)
1242                                         visifac= 0.0f;
1243                                 else
1244                                         visifac*= t/lar->dist;
1245                         }
1246
1247                         if (visifac > 0.0f) {
1248                                 if (lar->type==LA_SPOT) {
1249                                         float inpr, t;
1250
1251                                         if (lar->mode & LA_SQUARE) {
1252                                                 if (dot_v3v3(lv, lar->vec) > 0.0f) {
1253                                                         float lvrot[3], x;
1254
1255                                                         /* rotate view to lampspace */
1256                                                         copy_v3_v3(lvrot, lv);
1257                                                         mul_m3_v3(lar->imat, lvrot);
1258
1259                                                         x = max_ff(fabsf(lvrot[0]/lvrot[2]), fabsf(lvrot[1]/lvrot[2]));
1260                                                         /* 1.0f/(sqrt(1+x*x)) is equivalent to cos(atan(x)) */
1261
1262                                                         inpr = 1.0f / (sqrtf(1.0f + x * x));
1263                                                 }
1264                                                 else inpr= 0.0f;
1265                                         }
1266                                         else {
1267                                                 inpr= lv[0]*lar->vec[0]+lv[1]*lar->vec[1]+lv[2]*lar->vec[2];
1268                                         }
1269
1270                                         t= lar->spotsi;
1271                                         if (inpr<=t)
1272                                                 visifac= 0.0f;
1273                                         else {
1274                                                 t= inpr-t;
1275                                                 if (t<lar->spotbl && lar->spotbl!=0.0f) {
1276                                                         /* soft area */
1277                                                         float i= t/lar->spotbl;
1278                                                         t= i*i;
1279                                                         inpr*= (3.0f*t-2.0f*t*i);
1280                                                 }
1281                                                 visifac*= inpr;
1282                                         }
1283                                 }
1284                         }
1285                 }
1286                 if (visifac <= 0.001f) visifac = 0.0f;
1287                 return visifac;
1288         }
1289 }
1290
1291 /* function returns raw diff, spec and full shadowed diff in the 'shad' pass */
1292 static void shade_one_light(LampRen *lar, ShadeInput *shi, ShadeResult *shr, int passflag)
1293 {
1294         Material *ma= shi->mat;
1295         VlakRen *vlr= shi->vlr;
1296         float lv[3], lampdist, lacol[3], shadfac[4], lashdw[3];
1297         float i, is, i_noshad, inp, *vn, *view, vnor[3], phongcorr=1.0f;
1298         float visifac;
1299
1300         vn= shi->vn;
1301         view= shi->view;
1302
1303
1304         if (lar->energy == 0.0f) return;
1305         /* only shadow lamps shouldn't affect shadow-less materials at all */
1306         if ((lar->mode & LA_ONLYSHADOW) && (!(ma->mode & MA_SHADOW) || !(R.r.mode & R_SHADOW)))
1307                 return;
1308         /* optimization, don't render fully black lamps */
1309         if (!(lar->mode & LA_TEXTURE) && (lar->r + lar->g + lar->b == 0.0f))
1310                 return;
1311
1312         /* lampdist, spot angle, area side, ... */
1313         visifac= lamp_get_visibility(lar, shi->co, lv, &lampdist);
1314         if (visifac==0.0f)
1315                 return;
1316
1317         if (lar->type==LA_SPOT) {
1318                 if (lar->mode & LA_OSATEX) {
1319                         shi->osatex= 1; /* signal for multitex() */
1320
1321                         shi->dxlv[0]= lv[0] - (shi->co[0]-lar->co[0]+shi->dxco[0])/lampdist;
1322                         shi->dxlv[1]= lv[1] - (shi->co[1]-lar->co[1]+shi->dxco[1])/lampdist;
1323                         shi->dxlv[2]= lv[2] - (shi->co[2]-lar->co[2]+shi->dxco[2])/lampdist;
1324
1325                         shi->dylv[0]= lv[0] - (shi->co[0]-lar->co[0]+shi->dyco[0])/lampdist;
1326                         shi->dylv[1]= lv[1] - (shi->co[1]-lar->co[1]+shi->dyco[1])/lampdist;
1327                         shi->dylv[2]= lv[2] - (shi->co[2]-lar->co[2]+shi->dyco[2])/lampdist;
1328                 }
1329         }
1330
1331         /* lamp color texture */
1332         lacol[0]= lar->r;
1333         lacol[1]= lar->g;
1334         lacol[2]= lar->b;
1335
1336         lashdw[0]= lar->shdwr;
1337         lashdw[1]= lar->shdwg;
1338         lashdw[2]= lar->shdwb;
1339
1340         if (lar->mode & LA_TEXTURE)     do_lamp_tex(lar, lv, shi, lacol, LA_TEXTURE);
1341         if (lar->mode & LA_SHAD_TEX)    do_lamp_tex(lar, lv, shi, lashdw, LA_SHAD_TEX);
1342
1343                 /* tangent case; calculate fake face normal, aligned with lampvector */
1344                 /* note, vnor==vn is used as tangent trigger for buffer shadow */
1345         if (vlr->flag & R_TANGENT) {
1346                 float cross[3], nstrand[3], blend;
1347
1348                 if (ma->mode & MA_STR_SURFDIFF) {
1349                         cross_v3_v3v3(cross, shi->surfnor, vn);
1350                         cross_v3_v3v3(nstrand, vn, cross);
1351
1352                         blend= dot_v3v3(nstrand, shi->surfnor);
1353                         blend= 1.0f - blend;
1354                         CLAMP(blend, 0.0f, 1.0f);
1355
1356                         interp_v3_v3v3(vnor, nstrand, shi->surfnor, blend);
1357                         normalize_v3(vnor);
1358                 }
1359                 else {
1360                         cross_v3_v3v3(cross, lv, vn);
1361                         cross_v3_v3v3(vnor, cross, vn);
1362                         normalize_v3(vnor);
1363                 }
1364
1365                 if (ma->strand_surfnor > 0.0f) {
1366                         if (ma->strand_surfnor > shi->surfdist) {
1367                                 blend= (ma->strand_surfnor - shi->surfdist)/ma->strand_surfnor;
1368                                 interp_v3_v3v3(vnor, vnor, shi->surfnor, blend);
1369                                 normalize_v3(vnor);
1370                         }
1371                 }
1372
1373                 vnor[0]= -vnor[0];vnor[1]= -vnor[1];vnor[2]= -vnor[2];
1374                 vn= vnor;
1375         }
1376         else if (ma->mode & MA_TANGENT_V) {
1377                 float cross[3];
1378                 cross_v3_v3v3(cross, lv, shi->tang);
1379                 cross_v3_v3v3(vnor, cross, shi->tang);
1380                 normalize_v3(vnor);
1381                 vnor[0]= -vnor[0];vnor[1]= -vnor[1];vnor[2]= -vnor[2];
1382                 vn= vnor;
1383         }
1384
1385         /* dot product and reflectivity */
1386         /* inp = dotproduct, is = shader result, i = lamp energy (with shadow), i_noshad = i without shadow */
1387         inp= dot_v3v3(vn, lv);
1388
1389         /* phong threshold to prevent backfacing faces having artifacts on ray shadow (terminator problem) */
1390         /* this complex construction screams for a nicer implementation! (ton) */
1391         if (R.r.mode & R_SHADOW) {
1392                 if (ma->mode & MA_SHADOW) {
1393                         if (lar->type == LA_HEMI || lar->type == LA_AREA) {
1394                                 /* pass */
1395                         }
1396                         else if ((ma->mode & MA_RAYBIAS) && (lar->mode & LA_SHAD_RAY) && (vlr->flag & R_SMOOTH)) {
1397                                 float thresh= shi->obr->ob->smoothresh;
1398                                 if (inp>thresh)
1399                                         phongcorr= (inp-thresh)/(inp*(1.0f-thresh));
1400                                 else
1401                                         phongcorr= 0.0f;
1402                         }
1403                         else if (ma->sbias!=0.0f && ((lar->mode & LA_SHAD_RAY) || lar->shb)) {
1404                                 if (inp>ma->sbias)
1405                                         phongcorr= (inp-ma->sbias)/(inp*(1.0f-ma->sbias));
1406                                 else
1407                                         phongcorr= 0.0f;
1408                         }
1409                 }
1410         }
1411
1412         /* diffuse shaders */
1413         if (lar->mode & LA_NO_DIFF) {
1414                 is = 0.0f;  /* skip shaders */
1415         }
1416         else if (lar->type==LA_HEMI) {
1417                 is = 0.5f * inp + 0.5f;
1418         }
1419         else {
1420
1421                 if (lar->type==LA_AREA)
1422                         inp= area_lamp_energy_multisample(lar, shi->co, vn);
1423
1424                 /* diffuse shaders (oren nayer gets inp from area light) */
1425                 if (ma->diff_shader==MA_DIFF_ORENNAYAR) is= OrenNayar_Diff(inp, vn, lv, view, ma->roughness);
1426                 else if (ma->diff_shader==MA_DIFF_TOON) is= Toon_Diff(vn, lv, view, ma->param[0], ma->param[1]);
1427                 else if (ma->diff_shader==MA_DIFF_MINNAERT) is= Minnaert_Diff(inp, vn, view, ma->darkness);
1428                 else if (ma->diff_shader==MA_DIFF_FRESNEL) is= Fresnel_Diff(vn, lv, view, ma->param[0], ma->param[1]);
1429                 else is= inp;  /* Lambert */
1430         }
1431
1432         /* 'is' is diffuse */
1433         if ((ma->shade_flag & MA_CUBIC) && is > 0.0f && is < 1.0f) {
1434                 is= 3.0f * is * is - 2.0f * is * is * is;  /* nicer termination of shades */
1435         }
1436
1437         i= is*phongcorr;
1438
1439         if (i>0.0f) {
1440                 i*= visifac*shi->refl;
1441         }
1442         i_noshad= i;
1443
1444         vn = shi->vn;  /* bring back original vector, we use special specular shaders for tangent */
1445         if (ma->mode & MA_TANGENT_V)
1446                 vn= shi->tang;
1447
1448         /* init transp shadow */
1449         shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 1.0f;
1450
1451         /* shadow and spec, (visifac==0 outside spot) */
1452         if (visifac> 0.0f) {
1453
1454                 if ((R.r.mode & R_SHADOW)) {
1455                         if (ma->mode & MA_SHADOW) {
1456                                 if (lar->shb || (lar->mode & LA_SHAD_RAY)) {
1457
1458                                         if (vn==vnor)   /* tangent trigger */
1459                                                 lamp_get_shadow(lar, shi, dot_v3v3(shi->vn, lv), shadfac, shi->depth);
1460                                         else
1461                                                 lamp_get_shadow(lar, shi, inp, shadfac, shi->depth);
1462
1463                                         /* warning, here it skips the loop */
1464                                         if ((lar->mode & LA_ONLYSHADOW) && i>0.0f) {
1465
1466                                                 shadfac[3]= i*lar->energy*(1.0f-shadfac[3]);
1467                                                 shr->shad[0] -= shadfac[3]*shi->r*(1.0f-lashdw[0]);
1468                                                 shr->shad[1] -= shadfac[3]*shi->g*(1.0f-lashdw[1]);
1469                                                 shr->shad[2] -= shadfac[3]*shi->b*(1.0f-lashdw[2]);
1470
1471                                                 if (!(lar->mode & LA_NO_SPEC)) {
1472                                                         shr->spec[0] -= shadfac[3]*shi->specr*(1.0f-lashdw[0]);
1473                                                         shr->spec[1] -= shadfac[3]*shi->specg*(1.0f-lashdw[1]);
1474                                                         shr->spec[2] -= shadfac[3]*shi->specb*(1.0f-lashdw[2]);
1475                                                 }
1476
1477                                                 return;
1478                                         }
1479
1480                                         i*= shadfac[3];
1481                                         shr->shad[3] = shadfac[3]; /* store this for possible check in troublesome cases */
1482                                 }
1483                                 else {
1484                                         shr->shad[3] = 1.0f;  /* No shadow at all! */
1485                                 }
1486                         }
1487                 }
1488
1489                 /* in case 'no diffuse' we still do most calculus, spec can be in shadow.*/
1490                 if (!(lar->mode & LA_NO_DIFF)) {
1491                         if (i>0.0f) {
1492                                 if (ma->mode & MA_SHADOW_TRA) {
1493                                         const float tcol[3] = {
1494                                             i * shadfac[0] * lacol[0],
1495                                             i * shadfac[1] * lacol[1],
1496                                             i * shadfac[2] * lacol[2],
1497                                         };
1498                                         add_to_diffuse(shr->shad, shi, is, tcol);
1499                                 }
1500                                 else {
1501                                         const float tcol[3] = {
1502                                             i * lacol[0],
1503                                             i * lacol[1],
1504                                             i * lacol[2],
1505                                         };
1506                                         add_to_diffuse(shr->shad, shi, is, tcol);
1507                                 }
1508                         }
1509                         /* add light for colored shadow */
1510                         if (i_noshad>i && !(lashdw[0]==0 && lashdw[1]==0 && lashdw[2]==0)) {
1511                                 const float tcol[3] = {
1512                                     lashdw[0] * (i_noshad - i) * lacol[0],
1513                                     lashdw[1] * (i_noshad - i) * lacol[1],
1514                                     lashdw[2] * (i_noshad - i) * lacol[2],
1515                                 };
1516                                 add_to_diffuse(shr->shad, shi, is, tcol);
1517                         }
1518                         if (i_noshad>0.0f) {
1519                                 if (passflag & (SCE_PASS_DIFFUSE|SCE_PASS_SHADOW) ||
1520                                     ((passflag & SCE_PASS_COMBINED) && !(shi->combinedflag & SCE_PASS_SHADOW)))
1521                                 {
1522                                         const float tcol[3] = {
1523                                             i_noshad * lacol[0],
1524                                             i_noshad * lacol[1],
1525                                             i_noshad * lacol[2]
1526                                         };
1527                                         add_to_diffuse(shr->diff, shi, is, tcol);
1528                                 }
1529                                 else {
1530                                         copy_v3_v3(shr->diff, shr->shad);
1531                                 }
1532                         }
1533                 }
1534
1535                 /* specularity */
1536                 shadfac[3]*= phongcorr; /* note, shadfac not allowed to be stored nonlocal */
1537
1538                 if (shadfac[3]>0.0f && shi->spec!=0.0f && !(lar->mode & LA_NO_SPEC) && !(lar->mode & LA_ONLYSHADOW)) {
1539
1540                         if (!(passflag & (SCE_PASS_COMBINED | SCE_PASS_SPEC))) {
1541                                 /* pass */
1542                         }
1543                         else if (lar->type == LA_HEMI) {
1544                                 float t;
1545                                 /* hemi uses no spec shaders (yet) */
1546
1547                                 lv[0]+= view[0];
1548                                 lv[1]+= view[1];
1549                                 lv[2]+= view[2];
1550
1551                                 normalize_v3(lv);
1552
1553                                 t= vn[0]*lv[0]+vn[1]*lv[1]+vn[2]*lv[2];
1554
1555                                 if (lar->type==LA_HEMI) {
1556                                         t= 0.5f*t+0.5f;
1557                                 }
1558
1559                                 t= shadfac[3]*shi->spec*spec(t, shi->har);
1560
1561                                 shr->spec[0]+= t*(lacol[0] * shi->specr);
1562                                 shr->spec[1]+= t*(lacol[1] * shi->specg);
1563                                 shr->spec[2]+= t*(lacol[2] * shi->specb);
1564                         }
1565                         else {
1566                                 /* specular shaders */
1567                                 float specfac, t;
1568
1569                                 if (ma->spec_shader==MA_SPEC_PHONG)
1570                                         specfac= Phong_Spec(vn, lv, view, shi->har, (vlr->flag & R_TANGENT) || (ma->mode & MA_TANGENT_V));
1571                                 else if (ma->spec_shader==MA_SPEC_COOKTORR)
1572                                         specfac= CookTorr_Spec(vn, lv, view, shi->har, (vlr->flag & R_TANGENT) || (ma->mode & MA_TANGENT_V));
1573                                 else if (ma->spec_shader==MA_SPEC_BLINN)
1574                                         specfac= Blinn_Spec(vn, lv, view, ma->refrac, (float)shi->har, (vlr->flag & R_TANGENT) || (ma->mode & MA_TANGENT_V));
1575                                 else if (ma->spec_shader==MA_SPEC_WARDISO)
1576                                         specfac= WardIso_Spec( vn, lv, view, ma->rms, (vlr->flag & R_TANGENT) || (ma->mode & MA_TANGENT_V));
1577                                 else
1578                                         specfac= Toon_Spec(vn, lv, view, ma->param[2], ma->param[3], (vlr->flag & R_TANGENT) || (ma->mode & MA_TANGENT_V));
1579
1580                                 /* area lamp correction */
1581                                 if (lar->type==LA_AREA) specfac*= inp;
1582
1583                                 t= shadfac[3]*shi->spec*visifac*specfac;
1584
1585                                 if (ma->mode & MA_RAMP_SPEC) {
1586                                         float spec[3];
1587                                         do_specular_ramp(shi, specfac, t, spec);
1588                                         shr->spec[0]+= t*(lacol[0] * spec[0]);
1589                                         shr->spec[1]+= t*(lacol[1] * spec[1]);
1590                                         shr->spec[2]+= t*(lacol[2] * spec[2]);
1591                                 }
1592                                 else {
1593                                         shr->spec[0]+= t*(lacol[0] * shi->specr);
1594                                         shr->spec[1]+= t*(lacol[1] * shi->specg);
1595                                         shr->spec[2]+= t*(lacol[2] * shi->specb);
1596                                 }
1597                         }
1598                 }
1599         }
1600 }
1601
1602 static void shade_lamp_loop_only_shadow(ShadeInput *shi, ShadeResult *shr)
1603 {
1604
1605         if (R.r.mode & R_SHADOW) {
1606                 ListBase *lights;
1607                 LampRen *lar;
1608                 GroupObject *go;
1609                 float inpr, lv[3];
1610                 float /* *view, */ shadfac[4];
1611                 float ir, accum, visifac, lampdist;
1612                 float shaded = 0.0f, lightness = 0.0f;
1613
1614
1615                 /* view= shi->view; */ /* UNUSED */
1616                 accum= ir= 0.0f;
1617
1618                 lights= get_lights(shi);
1619                 for (go=lights->first; go; go= go->next) {
1620                         lar= go->lampren;
1621                         if (lar==NULL) continue;
1622
1623                         if (lar->mode & LA_LAYER) if ((lar->lay & shi->obi->lay)==0) continue;
1624                         if ((lar->lay & shi->lay)==0) continue;
1625
1626                         if (lar->shb || (lar->mode & LA_SHAD_RAY)) {
1627                                 visifac= lamp_get_visibility(lar, shi->co, lv, &lampdist);
1628                                 ir+= 1.0f;
1629
1630                                 if (visifac <= 0.0f) {
1631                                         if (shi->mat->shadowonly_flag == MA_SO_OLD)
1632                                                 accum+= 1.0f;
1633
1634                                         continue;
1635                                 }
1636                                 inpr= dot_v3v3(shi->vn, lv);
1637                                 if (inpr <= 0.0f) {
1638                                         if (shi->mat->shadowonly_flag == MA_SO_OLD)
1639                                                 accum+= 1.0f;
1640
1641                                         continue;
1642                                 }
1643
1644                                 lamp_get_shadow(lar, shi, inpr, shadfac, shi->depth);
1645
1646                                 if (shi->mat->shadowonly_flag == MA_SO_OLD) {
1647                                         /* Old "Shadows Only" */
1648                                         accum+= (1.0f-visifac) + (visifac)*IMB_colormanagement_get_luminance(shadfac)*shadfac[3];
1649                                 }
1650                                 else {
1651                                         shaded += IMB_colormanagement_get_luminance(shadfac)*shadfac[3] * visifac * lar->energy;
1652
1653                                         if (shi->mat->shadowonly_flag == MA_SO_SHADOW) {
1654                                                 lightness += visifac * lar->energy;
1655                                         }
1656                                 }
1657                         }
1658                 }
1659
1660                 /* Apply shadows as alpha */
1661                 if (ir>0.0f) {
1662                         if (shi->mat->shadowonly_flag == MA_SO_OLD) {
1663                                 accum = 1.0f - accum/ir;
1664                         }
1665                         else {
1666                                 if (shi->mat->shadowonly_flag == MA_SO_SHADOW) {
1667                                         if (lightness > 0.0f) {
1668                                                 /* Get shadow value from between 0.0f and non-shadowed lightness */
1669                                                 accum = (lightness - shaded) / (lightness);
1670                                         }
1671                                         else {
1672                                                 accum = 0.0f;
1673                                         }
1674                                 }
1675                                 else { /* shadowonly_flag == MA_SO_SHADED */
1676                                         /* Use shaded value */
1677                                         accum = 1.0f - shaded;
1678                                 }
1679                         }
1680
1681                         shr->alpha= (shi->alpha)*(accum);
1682                         if (shr->alpha<0.0f) shr->alpha=0.0f;
1683                 }
1684                 else {
1685                         /* If "fully shaded", use full alpha even on areas that have no lights */
1686                         if (shi->mat->shadowonly_flag == MA_SO_SHADED) shr->alpha=shi->alpha;
1687                         else shr->alpha= 0.f;
1688                 }
1689         }
1690
1691         /* quite disputable this...  also note it doesn't mirror-raytrace */
1692         if ((R.wrld.mode & (WO_AMB_OCC|WO_ENV_LIGHT)) && shi->amb!=0.0f) {
1693                 float f;
1694
1695                 if (R.wrld.mode & WO_AMB_OCC) {
1696                         f= R.wrld.aoenergy*shi->amb;
1697
1698                         if (R.wrld.aomix==WO_AOADD) {
1699                                 if (shi->mat->shadowonly_flag == MA_SO_OLD) {
1700                                         f= f*(1.0f - IMB_colormanagement_get_luminance(shi->ao));
1701                                         shr->alpha= (shr->alpha + f)*f;
1702                                 }
1703                                 else {
1704                                         shr->alpha -= f*IMB_colormanagement_get_luminance(shi->ao);
1705                                         if (shr->alpha<0.0f) shr->alpha=0.0f;
1706                                 }
1707                         }
1708                         else /* AO Multiply */
1709                                 shr->alpha= (1.0f - f)*shr->alpha + f*(1.0f - (1.0f - shr->alpha)*IMB_colormanagement_get_luminance(shi->ao));
1710                 }
1711
1712                 if (R.wrld.mode & WO_ENV_LIGHT) {
1713                         if (shi->mat->shadowonly_flag == MA_SO_OLD) {
1714                                 f= R.wrld.ao_env_energy*shi->amb*(1.0f - IMB_colormanagement_get_luminance(shi->env));
1715                                 shr->alpha= (shr->alpha + f)*f;
1716                         }
1717                         else {
1718                                 f= R.wrld.ao_env_energy*shi->amb;
1719                                 shr->alpha -= f*IMB_colormanagement_get_luminance(shi->env);
1720                                 if (shr->alpha<0.0f) shr->alpha=0.0f;
1721                         }
1722                 }
1723         }
1724 }
1725
1726 /* let's map negative light as if it mirrors positive light, otherwise negative values disappear */
1727 static void wrld_exposure_correct(float diff[3])
1728 {
1729
1730         diff[0]= R.wrld.linfac*(1.0f-expf( diff[0]*R.wrld.logfac) );
1731         diff[1]= R.wrld.linfac*(1.0f-expf( diff[1]*R.wrld.logfac) );
1732         diff[2]= R.wrld.linfac*(1.0f-expf( diff[2]*R.wrld.logfac) );
1733 }
1734
1735 void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr)
1736 {
1737         /* Passes which might need to know material color.
1738          *
1739          * It seems to be faster to just calculate material color
1740          * even if the pass doesn't really need it than trying to
1741          * figure out whether color is really needed or not.
1742          */
1743         const int color_passes =
1744                 SCE_PASS_COMBINED | SCE_PASS_RGBA | SCE_PASS_DIFFUSE | SCE_PASS_SPEC |
1745                 SCE_PASS_REFLECT | SCE_PASS_NORMAL | SCE_PASS_REFRACT | SCE_PASS_EMIT | SCE_PASS_SHADOW;
1746
1747         Material *ma= shi->mat;
1748         int passflag= shi->passflag;
1749
1750         memset(shr, 0, sizeof(ShadeResult));
1751
1752         if (!(shi->mode & MA_TRANSP)) shi->alpha = 1.0f;
1753
1754         /* separate loop */
1755         if (ma->mode & MA_ONLYSHADOW) {
1756                 shade_lamp_loop_only_shadow(shi, shr);
1757                 return;
1758         }
1759
1760         /* envmap hack, always reset */
1761         shi->refcol[0]= shi->refcol[1]= shi->refcol[2]= shi->refcol[3]= 0.0f;
1762
1763         /* material color itself */
1764         if (passflag & color_passes) {
1765                 if (ma->mode & (MA_FACETEXTURE)) {
1766                         shi->r= shi->vcol[0];
1767                         shi->g= shi->vcol[1];
1768                         shi->b= shi->vcol[2];
1769                         if (ma->mode & (MA_FACETEXTURE_ALPHA))
1770                                 shi->alpha= shi->vcol[3];
1771                 }
1772 #ifdef WITH_FREESTYLE
1773                 else if (ma->vcol_alpha) {
1774                         shi->r= shi->vcol[0];
1775                         shi->g= shi->vcol[1];
1776                         shi->b= shi->vcol[2];
1777                         shi->alpha= shi->vcol[3];
1778                 }
1779 #endif
1780                 else if (ma->mode & (MA_VERTEXCOLP)) {
1781                         float neg_alpha = 1.0f - shi->vcol[3];
1782                         shi->r= shi->r*neg_alpha + shi->vcol[0]*shi->vcol[3];
1783                         shi->g= shi->g*neg_alpha + shi->vcol[1]*shi->vcol[3];
1784                         shi->b= shi->b*neg_alpha + shi->vcol[2]*shi->vcol[3];
1785                 }
1786                 if (ma->texco) {
1787                         do_material_tex(shi, &R);
1788                         if (!(shi->mode & MA_TRANSP)) shi->alpha = 1.0f;
1789                 }
1790
1791                 shr->col[0]= shi->r*shi->alpha;
1792                 shr->col[1]= shi->g*shi->alpha;
1793                 shr->col[2]= shi->b*shi->alpha;
1794                 shr->col[3]= shi->alpha;
1795
1796                 if ((ma->sss_flag & MA_DIFF_SSS) && !sss_pass_done(&R, ma)) {
1797                         if (ma->sss_texfac == 0.0f) {
1798                                 shi->r= shi->g= shi->b= shi->alpha= 1.0f;
1799                                 shr->col[0]= shr->col[1]= shr->col[2]= shr->col[3]= 1.0f;
1800                         }
1801                         else {
1802                                 shi->r= pow(max_ff(shi->r, 0.0f), ma->sss_texfac);
1803                                 shi->g= pow(max_ff(shi->g, 0.0f), ma->sss_texfac);
1804                                 shi->b= pow(max_ff(shi->b, 0.0f), ma->sss_texfac);
1805                                 shi->alpha= pow(max_ff(shi->alpha, 0.0f), ma->sss_texfac);
1806
1807                                 shr->col[0]= pow(max_ff(shr->col[0], 0.0f), ma->sss_texfac);
1808                                 shr->col[1]= pow(max_ff(shr->col[1], 0.0f), ma->sss_texfac);
1809                                 shr->col[2]= pow(max_ff(shr->col[2], 0.0f), ma->sss_texfac);
1810                                 shr->col[3]= pow(max_ff(shr->col[3], 0.0f), ma->sss_texfac);
1811                         }
1812                 }
1813         }
1814
1815         if (ma->mode & MA_SHLESS) {
1816                 shr->combined[0]= shi->r;
1817                 shr->combined[1]= shi->g;
1818                 shr->combined[2]= shi->b;
1819                 shr->alpha= shi->alpha;
1820                 goto finally_shadeless;
1821         }
1822
1823         if ( (ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))== MA_VERTEXCOL ) {       /* vertexcolor light */
1824                 shr->emit[0]= shi->r*(shi->emit+shi->vcol[0]*shi->vcol[3]);
1825                 shr->emit[1]= shi->g*(shi->emit+shi->vcol[1]*shi->vcol[3]);
1826                 shr->emit[2]= shi->b*(shi->emit+shi->vcol[2]*shi->vcol[3]);
1827         }
1828         else {
1829                 shr->emit[0]= shi->r*shi->emit;
1830                 shr->emit[1]= shi->g*shi->emit;
1831                 shr->emit[2]= shi->b*shi->emit;
1832         }
1833
1834         /* AO pass */
1835         if (((passflag & SCE_PASS_COMBINED) && (shi->combinedflag & (SCE_PASS_AO|SCE_PASS_ENVIRONMENT|SCE_PASS_INDIRECT))) ||
1836             (passflag & (SCE_PASS_AO|SCE_PASS_ENVIRONMENT|SCE_PASS_INDIRECT))) {
1837                 if ((R.wrld.mode & (WO_AMB_OCC|WO_ENV_LIGHT|WO_INDIRECT_LIGHT)) && (R.r.mode & R_SHADOW)) {
1838                         /* AO was calculated for scanline already */
1839                         if (shi->depth || shi->volume_depth)
1840                                 ambient_occlusion(shi);
1841                         copy_v3_v3(shr->ao, shi->ao);
1842                         copy_v3_v3(shr->env, shi->env); /* XXX multiply */
1843                         copy_v3_v3(shr->indirect, shi->indirect); /* XXX multiply */
1844                 }
1845                 else {
1846                         shr->ao[0]= shr->ao[1]= shr->ao[2]= 1.0f;
1847                         zero_v3(shr->env);
1848                         zero_v3(shr->indirect);
1849                 }
1850         }
1851
1852         /* lighting pass */
1853         if (passflag & (SCE_PASS_COMBINED|SCE_PASS_DIFFUSE|SCE_PASS_SPEC|SCE_PASS_SHADOW)) {
1854                 GroupObject *go;
1855                 ListBase *lights;
1856                 LampRen *lar;
1857
1858                 lights= get_lights(shi);
1859                 for (go=lights->first; go; go= go->next) {
1860                         lar= go->lampren;
1861                         if (lar==NULL) continue;
1862
1863                         /* test for lamp layer */
1864                         if (lar->mode & LA_LAYER) if ((lar->lay & shi->obi->lay)==0) continue;
1865                         if ((lar->lay & shi->lay)==0) continue;
1866
1867                         /* accumulates in shr->diff and shr->spec and shr->shad (diffuse with shadow!) */
1868                         shade_one_light(lar, shi, shr, passflag);
1869                 }
1870
1871                 /* this check is to prevent only shadow lamps from producing negative
1872                  * colors.*/
1873                 if (shr->spec[0] < 0) shr->spec[0] = 0;
1874                 if (shr->spec[1] < 0) shr->spec[1] = 0;
1875                 if (shr->spec[2] < 0) shr->spec[2] = 0;
1876
1877                 if (shr->shad[0] < 0) shr->shad[0] = 0;
1878                 if (shr->shad[1] < 0) shr->shad[1] = 0;
1879                 if (shr->shad[2] < 0) shr->shad[2] = 0;
1880
1881                 if (ma->sss_flag & MA_DIFF_SSS) {
1882                         float sss[3], col[3], invalpha, texfac= ma->sss_texfac;
1883
1884                         /* this will return false in the preprocess stage */
1885                         if (sample_sss(&R, ma, shi->co, sss)) {
1886                                 invalpha= (shr->col[3] > FLT_EPSILON)? 1.0f/shr->col[3]: 1.0f;
1887
1888                                 if (texfac==0.0f) {
1889                                         copy_v3_v3(col, shr->col);
1890                                         mul_v3_fl(col, invalpha);
1891                                 }
1892                                 else if (texfac==1.0f) {
1893                                         col[0]= col[1]= col[2]= 1.0f;
1894                                         mul_v3_fl(col, invalpha);
1895                                 }
1896                                 else {
1897                                         copy_v3_v3(col, shr->col);
1898                                         mul_v3_fl(col, invalpha);
1899                                         col[0]= pow(max_ff(col[0], 0.0f), 1.0f-texfac);
1900                                         col[1]= pow(max_ff(col[1], 0.0f), 1.0f-texfac);
1901                                         col[2]= pow(max_ff(col[2], 0.0f), 1.0f-texfac);
1902                                 }
1903
1904                                 shr->diff[0]= sss[0]*col[0];
1905                                 shr->diff[1]= sss[1]*col[1];
1906                                 shr->diff[2]= sss[2]*col[2];
1907
1908                                 if (shi->combinedflag & SCE_PASS_SHADOW) {
1909                                         shr->shad[0]= shr->diff[0];
1910                                         shr->shad[1]= shr->diff[1];
1911                                         shr->shad[2]= shr->diff[2];
1912                                 }
1913                         }
1914                 }
1915
1916                 if (shi->combinedflag & SCE_PASS_SHADOW)
1917                         copy_v3_v3(shr->diffshad, shr->shad);
1918                 else
1919                         copy_v3_v3(shr->diffshad, shr->diff);
1920
1921                 copy_v3_v3(shr->combined, shr->diffshad);
1922
1923                 /* calculate shadow pass, we use a multiplication mask */
1924                 /* Even if diff = 0,0,0, it does matter what the shadow pass is, since we may want it 'for itself'! */
1925                 if (passflag & SCE_PASS_SHADOW) {
1926                         if (shr->diff[0]!=0.0f) shr->shad[0]= shr->shad[0]/shr->diff[0];
1927                         /* can't determine proper shadow from shad/diff (0/0), so use shadow intensity */
1928                         else if (shr->shad[0]==0.0f) shr->shad[0]= shr->shad[3];
1929
1930                         if (shr->diff[1]!=0.0f) shr->shad[1]= shr->shad[1]/shr->diff[1];
1931                         else if (shr->shad[1]==0.0f) shr->shad[1]= shr->shad[3];
1932
1933                         if (shr->diff[2]!=0.0f) shr->shad[2]= shr->shad[2]/shr->diff[2];
1934                         else if (shr->shad[2]==0.0f) shr->shad[2]= shr->shad[3];
1935                 }
1936
1937                 /* exposure correction */
1938                 if ((R.wrld.exp!=0.0f || R.wrld.range!=1.0f) && !R.sss_points) {
1939                         wrld_exposure_correct(shr->combined);   /* has no spec! */
1940                         wrld_exposure_correct(shr->spec);
1941                 }
1942         }
1943
1944         /* alpha in end, spec can influence it */
1945         if (passflag & (SCE_PASS_COMBINED)) {
1946                 if ((ma->fresnel_tra!=0.0f) && (shi->mode & MA_TRANSP))
1947                         shi->alpha*= fresnel_fac(shi->view, shi->vn, ma->fresnel_tra_i, ma->fresnel_tra);
1948
1949                 /* note: shi->mode! */
1950                 if (shi->mode & MA_TRANSP && (shi->mode & (MA_ZTRANSP|MA_RAYTRANSP))) {
1951                         if (shi->spectra!=0.0f) {
1952                                 float t = max_fff(shr->spec[0], shr->spec[1], shr->spec[2]);
1953                                 t *= shi->spectra;
1954                                 if (t>1.0f) t= 1.0f;
1955                                 shi->alpha= (1.0f-t)*shi->alpha+t;
1956                         }
1957                 }
1958         }
1959         shr->alpha= shi->alpha;
1960
1961         /* from now stuff everything in shr->combined: ambient, AO, ramps, exposure */
1962         if (!(ma->sss_flag & MA_DIFF_SSS) || !sss_pass_done(&R, ma)) {
1963                 if (R.r.mode & R_SHADOW) {
1964                         /* add AO in combined? */
1965                         if (R.wrld.mode & WO_AMB_OCC)
1966                                 if (shi->combinedflag & SCE_PASS_AO)
1967                                         ambient_occlusion_apply(shi, shr);
1968
1969                         if (R.wrld.mode & WO_ENV_LIGHT)
1970                                 if (shi->combinedflag & SCE_PASS_ENVIRONMENT)
1971                                         environment_lighting_apply(shi, shr);
1972
1973                         if (R.wrld.mode & WO_INDIRECT_LIGHT)
1974                                 if (shi->combinedflag & SCE_PASS_INDIRECT)
1975                                         indirect_lighting_apply(shi, shr);
1976                 }
1977
1978                 shr->combined[0]+= shi->ambr;
1979                 shr->combined[1]+= shi->ambg;
1980                 shr->combined[2]+= shi->ambb;
1981
1982                 if (ma->mode & MA_RAMP_COL) ramp_diffuse_result(shr->combined, shi);
1983         }
1984
1985         if (ma->mode & MA_RAMP_SPEC) ramp_spec_result(shr->spec, shi);
1986
1987         /* refcol is for envmap only */
1988         if (shi->refcol[0]!=0.0f) {
1989                 float result[3];
1990
1991                 result[0]= shi->mirr*shi->refcol[1] + (1.0f - shi->mirr*shi->refcol[0])*shr->combined[0];
1992                 result[1]= shi->mirg*shi->refcol[2] + (1.0f - shi->mirg*shi->refcol[0])*shr->combined[1];
1993                 result[2]= shi->mirb*shi->refcol[3] + (1.0f - shi->mirb*shi->refcol[0])*shr->combined[2];
1994
1995                 if (passflag & SCE_PASS_REFLECT)
1996                         sub_v3_v3v3(shr->refl, result, shr->combined);
1997
1998                 if (shi->combinedflag & SCE_PASS_REFLECT)
1999                         copy_v3_v3(shr->combined, result);
2000
2001         }
2002
2003         /* and add emit and spec */
2004         if (shi->combinedflag & SCE_PASS_EMIT)
2005                 add_v3_v3(shr->combined, shr->emit);
2006         if (shi->combinedflag & SCE_PASS_SPEC)
2007                 add_v3_v3(shr->combined, shr->spec);
2008
2009
2010         /* Last section of this function applies to shadeless colors too */
2011 finally_shadeless:
2012
2013         /* modulate by the object color */
2014         if ((ma->shade_flag & MA_OBCOLOR) && shi->obr->ob) {
2015                 if (!(ma->sss_flag & MA_DIFF_SSS) || !sss_pass_done(&R, ma)) {
2016                         float obcol[4];
2017
2018                         copy_v4_v4(obcol, shi->obr->ob->col);
2019                         CLAMP(obcol[3], 0.0f, 1.0f);
2020
2021                         shr->combined[0] *= obcol[0];
2022                         shr->combined[1] *= obcol[1];
2023                         shr->combined[2] *= obcol[2];
2024                         if (shi->mode & MA_TRANSP) shr->alpha *= obcol[3];
2025                 }
2026         }
2027
2028         shr->combined[3]= shr->alpha;
2029 }
2030
2031 /* used for "Lamp Data" shader node */
2032 static float lamp_get_data_internal(ShadeInput *shi, GroupObject *go, float col[4], float lv[3], float *dist, float shadow[4])
2033 {
2034         LampRen *lar = go->lampren;
2035         float visifac, inp;
2036
2037         if (!lar
2038             || ((lar->mode & LA_LAYER) && (lar->lay & shi->obi->lay) == 0)
2039             || (lar->lay & shi->lay) == 0)
2040                 return 0.0f;
2041
2042         if (lar->mode & LA_TEXTURE)
2043                 do_lamp_tex(lar, lv, shi, col, LA_TEXTURE);
2044
2045         visifac = lamp_get_visibility(lar, shi->co, lv, dist);
2046
2047         if (visifac == 0.0f
2048             || lar->type == LA_HEMI
2049             || (lar->type != LA_SPOT && !(lar->mode & LA_SHAD_RAY))
2050             || (R.r.scemode & R_BUTS_PREVIEW))
2051                 return visifac;
2052
2053         inp = dot_v3v3(shi->vn, lv);
2054
2055         if (inp > 0.0f) {
2056                 float shadfac[4];
2057
2058                 shadow[0] = lar->shdwr;
2059                 shadow[1] = lar->shdwg;
2060                 shadow[2] = lar->shdwb;
2061
2062                 if (lar->mode & LA_SHAD_TEX)
2063                         do_lamp_tex(lar, lv, shi, shadow, LA_SHAD_TEX);
2064
2065                 if (R.r.mode & R_SHADOW) {
2066                         lamp_get_shadow(lar, shi, inp, shadfac, shi->depth);
2067
2068                         shadow[0] = 1.0f - ((1.0f - shadfac[0] * shadfac[3]) * (1.0f - shadow[0]));
2069                         shadow[1] = 1.0f - ((1.0f - shadfac[1] * shadfac[3]) * (1.0f - shadow[1]));
2070                         shadow[2] = 1.0f - ((1.0f - shadfac[2] * shadfac[3]) * (1.0f - shadow[2]));
2071                 }
2072         }
2073
2074         return visifac;
2075 }
2076
2077 float RE_lamp_get_data(ShadeInput *shi, Object *lamp_obj, float col[4], float lv[3], float *dist, float shadow[4])
2078 {
2079         col[0] = col[1] = col[2] = 0.0f;
2080         col[3] = 1.0f;
2081         copy_v3_v3(lv, shi->vn);
2082         *dist = 1.0f;
2083         shadow[0] = shadow[1] = shadow[2] = shadow[3] = 1.0f;
2084
2085         if (lamp_obj->type == OB_LAMP) {
2086                 GroupObject *go;
2087                 Lamp *lamp = (Lamp *)lamp_obj->data;
2088
2089                 col[0] = lamp->r * lamp->energy;
2090                 col[1] = lamp->g * lamp->energy;
2091                 col[2] = lamp->b * lamp->energy;
2092
2093                 if (R.r.scemode & R_BUTS_PREVIEW) {
2094                         for (go = R.lights.first; go; go = go->next) {
2095                                 /* "Lamp.002" is main key light of material preview */
2096                                 if (STREQ(go->ob->id.name + 2, "Lamp.002"))
2097                                         return lamp_get_data_internal(shi, go, col, lv, dist, shadow);
2098                         }
2099                         return 0.0f;
2100                 }
2101
2102                 if (shi->light_override) {
2103                         for (go = shi->light_override->gobject.first; go; go = go->next) {
2104                                 if (go->ob == lamp_obj)
2105                                         return lamp_get_data_internal(shi, go, col, lv, dist, shadow);
2106                         }
2107                 }
2108
2109                 if (shi->mat && shi->mat->group) {
2110                         for (go = shi->mat->group->gobject.first; go; go = go->next) {
2111                                 if (go->ob == lamp_obj)
2112                                         return lamp_get_data_internal(shi, go, col, lv, dist, shadow);
2113                         }
2114                 }
2115
2116                 for (go = R.lights.first; go; go = go->next) {
2117                         if (go->ob == lamp_obj)
2118                                 return lamp_get_data_internal(shi, go, col, lv, dist, shadow);
2119                 }
2120         }
2121
2122         return 0.0f;
2123 }
2124
2125 const float (*RE_object_instance_get_matrix(struct ObjectInstanceRen *obi, int matrix_id))[4]
2126 {
2127         if (obi) {
2128                 switch (matrix_id) {
2129                         case RE_OBJECT_INSTANCE_MATRIX_OB:
2130                                 return (const float(*)[4])obi->obmat;
2131                         case RE_OBJECT_INSTANCE_MATRIX_OBINV:
2132                                 return (const float(*)[4])obi->obinvmat;
2133                         case RE_OBJECT_INSTANCE_MATRIX_LOCALTOVIEW:
2134                                 return (const float(*)[4])obi->localtoviewmat;
2135                         case RE_OBJECT_INSTANCE_MATRIX_LOCALTOVIEWINV:
2136                                 return (const float(*)[4])obi->localtoviewinvmat;
2137                 }
2138         }
2139         return NULL;
2140 }
2141
2142 float RE_object_instance_get_object_pass_index(struct ObjectInstanceRen *obi)
2143 {
2144         return obi->ob->index;
2145 }
2146
2147 float RE_object_instance_get_random_id(struct ObjectInstanceRen *obi)
2148 {
2149         return obi->random_id;
2150 }
2151
2152 const float (*RE_render_current_get_matrix(int matrix_id))[4]
2153 {
2154         switch (matrix_id) {
2155                 case RE_VIEW_MATRIX:
2156                         return (const float(*)[4])R.viewmat;
2157                 case RE_VIEWINV_MATRIX:
2158                         return (const float(*)[4])R.viewinv;
2159         }
2160         return NULL;
2161 }
2162
2163 float RE_fresnel_dielectric(float incoming[3], float normal[3], float eta)
2164 {
2165         /* compute fresnel reflectance without explicitly computing
2166          * the refracted direction */
2167         float c = fabs(dot_v3v3(incoming, normal));
2168         float g = eta * eta - 1.0 + c * c;
2169         float result;
2170
2171         if (g > 0.0) {
2172                 g = sqrtf(g);
2173                 float A = (g - c) / (g + c);
2174                 float B = (c * (g + c) - 1.0) / (c * (g - c) + 1.0);
2175                 result = 0.5 * A * A * (1.0 + B * B);
2176         }
2177         else {
2178                 result = 1.0;  /* TIR (no refracted component) */
2179         }
2180
2181         return result;
2182 }