69e90a7537c30d91cf3228bef332cd2e9797931b
[blender.git] / source / blender / render / intern / source / rayshade.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 1990-1998 NeoGeo BV.
21  * All rights reserved.
22  *
23  * Contributors: 2004/2005 Blender Foundation, full recode
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <math.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <float.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_material_types.h"
36 #include "DNA_lamp_types.h"
37
38 #include "BKE_global.h"
39 #include "BKE_node.h"
40 #include "BKE_utildefines.h"
41
42 #include "BLI_arithb.h"
43 #include "BLI_rand.h"
44 #include "BLI_jitter.h"
45
46 #include "PIL_time.h"
47
48 #include "render_types.h"
49 #include "renderpipeline.h"
50 #include "rendercore.h"
51 #include "renderdatabase.h"
52 #include "pixelblending.h"
53 #include "pixelshading.h"
54 #include "shading.h"
55 #include "texture.h"
56
57 #include "RE_raytrace.h"
58
59 #define RAY_TRA         1
60 #define RAY_TRAFLIP     2
61
62 #define DEPTH_SHADOW_TRA  10
63
64 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
65 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
66 /* only to be used here in this file, it's for speed */
67 extern struct Render R;
68 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
69
70 static void vlr_face_coords(RayFace *face, float **v1, float **v2, float **v3, float **v4)
71 {
72         VlakRen *vlr= (VlakRen*)face;
73
74         *v1 = (vlr->v1)? vlr->v1->co: NULL;
75         *v2 = (vlr->v2)? vlr->v2->co: NULL;
76         *v3 = (vlr->v3)? vlr->v3->co: NULL;
77         *v4 = (vlr->v4)? vlr->v4->co: NULL;
78 }
79
80 static int vlr_check_intersect(Isect *is, RayFace *face)
81 {
82         VlakRen *vlr = (VlakRen*)face;
83
84         /* I know... cpu cycle waste, might do smarter once */
85         if(is->mode==RE_RAY_MIRROR)
86                 return !(vlr->mat->mode & MA_ONLYCAST);
87         else
88                 return (is->lay & vlr->lay);
89 }
90
91 static float *vlr_get_transform(void *userdata, int i)
92 {
93         ObjectInstanceRen *obi= RAY_OBJECT_GET((Render*)userdata, i);
94
95         return (obi->flag & R_TRANSFORMED)? (float*)obi->mat: NULL;
96 }
97
98 void freeraytree(Render *re)
99 {
100         if(re->raytree) {
101                 RE_ray_tree_free(re->raytree);
102                 re->raytree= NULL;
103         }
104 }
105
106 void makeraytree(Render *re)
107 {
108         ObjectInstanceRen *obi;
109         ObjectRen *obr;
110         VlakRen *vlr= NULL;
111         float min[3], max[3], co1[3], co2[3], co3[3], co4[3];
112         double lasttime= PIL_check_seconds_timer();
113         int v, totface = 0;
114
115         INIT_MINMAX(min, max);
116
117         /* first min max raytree space */
118         for(obi=re->instancetable.first; obi; obi=obi->next) {
119                 obr= obi->obr;
120
121                 if(re->excludeob && obr->ob == re->excludeob)
122                         continue;
123
124                 for(v=0;v<obr->totvlak;v++) {
125                         if((v & 255)==0) vlr= obr->vlaknodes[v>>8].vlak;
126                         else vlr++;
127                         if(vlr->mat->mode & MA_TRACEBLE) {      
128                                 if((vlr->mat->mode & MA_WIRE)==0) {     
129                                         VECCOPY(co1, vlr->v1->co);
130                                         VECCOPY(co2, vlr->v2->co);
131                                         VECCOPY(co3, vlr->v3->co);
132
133                                         if(obi->flag & R_TRANSFORMED) {
134                                                 Mat4MulVecfl(obi->mat, co1);
135                                                 Mat4MulVecfl(obi->mat, co2);
136                                                 Mat4MulVecfl(obi->mat, co3);
137                                         }
138
139                                         DO_MINMAX(co1, min, max);
140                                         DO_MINMAX(co2, min, max);
141                                         DO_MINMAX(co3, min, max);
142
143                                         if(vlr->v4) {
144                                                 VECCOPY(co4, vlr->v4->co);
145                                                 if(obi->flag & R_TRANSFORMED)
146                                                         Mat4MulVecfl(obi->mat, co4);
147                                                 DO_MINMAX(co4, min, max);
148                                         }
149
150                                         totface++;
151                                 }
152                         }
153                 }
154         }
155
156         re->raytree= RE_ray_tree_create(re->r.ocres, totface, min, max,
157                 vlr_face_coords, vlr_check_intersect, vlr_get_transform, re);
158
159         if(min[0] > max[0]) { /* empty raytree */
160                 RE_ray_tree_done(re->raytree);
161                 return; 
162         }
163
164         for(obi=re->instancetable.first; obi; obi=obi->next) {
165                 obr= obi->obr;
166
167                 if(re->excludeob && obr->ob == re->excludeob)
168                         continue;
169
170                 for(v=0; v<obr->totvlak; v++) {
171                         if((v & 255)==0) {
172                                 double time= PIL_check_seconds_timer();
173
174                                 vlr= obr->vlaknodes[v>>8].vlak;
175                                 if(re->test_break())
176                                         break;
177                                 if(time-lasttime>1.0f) {
178                                         char str[32];
179                                         sprintf(str, "Filling Octree: %d", v);
180                                         re->i.infostr= str;
181                                         re->stats_draw(&re->i);
182                                         re->i.infostr= NULL;
183                                         lasttime= time;
184                                 }
185                         }
186                         else vlr++;
187                         
188                         if(vlr->mat->mode & MA_TRACEBLE)
189                                 if((vlr->mat->mode & MA_WIRE)==0)
190                                         RE_ray_tree_add_face(re->raytree, RAY_OBJECT_SET(re, obi), vlr);
191                 }
192         }
193
194         RE_ray_tree_done(re->raytree);
195         
196         re->i.infostr= NULL;
197         re->stats_draw(&re->i);
198 }
199
200 static void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr)
201 {
202         VlakRen *vlr= (VlakRen*)is->face;
203         ObjectInstanceRen *obi= RAY_OBJECT_GET(&R, is->ob);
204         int osatex= 0;
205         
206         /* set up view vector */
207         VECCOPY(shi->view, is->vec);
208
209         /* render co */
210         shi->co[0]= is->start[0]+is->labda*(shi->view[0]);
211         shi->co[1]= is->start[1]+is->labda*(shi->view[1]);
212         shi->co[2]= is->start[2]+is->labda*(shi->view[2]);
213         
214         Normalize(shi->view);
215
216         shi->obi= obi;
217         shi->obr= obi->obr;
218         shi->vlr= vlr;
219         shi->mat= vlr->mat;
220         memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));        // note, keep this synced with render_types.h
221         shi->har= shi->mat->har;
222         
223         // Osa structs we leave unchanged now
224         SWAP(int, osatex, shi->osatex);
225         
226         shi->dxco[0]= shi->dxco[1]= shi->dxco[2]= 0.0f;
227         shi->dyco[0]= shi->dyco[1]= shi->dyco[2]= 0.0f;
228         
229         // but, set Osa stuff to zero where it can confuse texture code
230         if(shi->mat->texco & (TEXCO_NORM|TEXCO_REFL) ) {
231                 shi->dxno[0]= shi->dxno[1]= shi->dxno[2]= 0.0f;
232                 shi->dyno[0]= shi->dyno[1]= shi->dyno[2]= 0.0f;
233         }
234
235         if(vlr->v4) {
236                 if(is->isect==2) 
237                         shade_input_set_triangle_i(shi, obi, vlr, 2, 1, 3);
238                 else
239                         shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 3);
240         }
241         else {
242                 shade_input_set_triangle_i(shi, obi, vlr, 0, 1, 2);
243         }
244
245         shi->u= is->u;
246         shi->v= is->v;
247         shi->dx_u= shi->dx_v= shi->dy_u= shi->dy_v=  0.0f;
248
249         shade_input_set_normals(shi);
250
251         /* point normals to viewing direction */
252         if(INPR(shi->facenor, shi->view) < 0.0f)
253                 shade_input_flip_normals(shi);
254
255         shade_input_set_shade_texco(shi);
256         
257         if(is->mode==RE_RAY_SHADOW_TRA) 
258                 shade_color(shi, shr);
259         else {
260                 if(shi->mat->nodetree && shi->mat->use_nodes) {
261                         ntreeShaderExecTree(shi->mat->nodetree, shi, shr);
262                         shi->mat= vlr->mat;             /* shi->mat is being set in nodetree */
263                 }
264                 else
265                         shade_material_loop(shi, shr);
266                 
267                 /* raytrace likes to separate the spec color */
268                 VECSUB(shr->diff, shr->combined, shr->spec);
269         }       
270         
271         SWAP(int, osatex, shi->osatex);  // XXXXX!!!!
272
273 }
274
275 static int refraction(float *refract, float *n, float *view, float index)
276 {
277         float dot, fac;
278
279         VECCOPY(refract, view);
280         
281         dot= view[0]*n[0] + view[1]*n[1] + view[2]*n[2];
282
283         if(dot>0.0f) {
284                 index = 1.0f/index;
285                 fac= 1.0f - (1.0f - dot*dot)*index*index;
286                 if(fac<= 0.0f) return 0;
287                 fac= -dot*index + sqrt(fac);
288         }
289         else {
290                 fac= 1.0f - (1.0f - dot*dot)*index*index;
291                 if(fac<= 0.0f) return 0;
292                 fac= -dot*index - sqrt(fac);
293         }
294
295         refract[0]= index*view[0] + fac*n[0];
296         refract[1]= index*view[1] + fac*n[1];
297         refract[2]= index*view[2] + fac*n[2];
298
299         return 1;
300 }
301
302 /* orn = original face normal */
303 static void reflection(float *ref, float *n, float *view, float *orn)
304 {
305         float f1;
306         
307         f1= -2.0f*(n[0]*view[0]+ n[1]*view[1]+ n[2]*view[2]);
308         
309         ref[0]= (view[0]+f1*n[0]);
310         ref[1]= (view[1]+f1*n[1]);
311         ref[2]= (view[2]+f1*n[2]);
312
313         if(orn) {
314                 /* test phong normals, then we should prevent vector going to the back */
315                 f1= ref[0]*orn[0]+ ref[1]*orn[1]+ ref[2]*orn[2];
316                 if(f1>0.0f) {
317                         f1+= .01f;
318                         ref[0]-= f1*orn[0];
319                         ref[1]-= f1*orn[1];
320                         ref[2]-= f1*orn[2];
321                 }
322         }
323 }
324
325 #if 0
326 static void color_combine(float *result, float fac1, float fac2, float *col1, float *col2)
327 {
328         float col1t[3], col2t[3];
329         
330         col1t[0]= sqrt(col1[0]);
331         col1t[1]= sqrt(col1[1]);
332         col1t[2]= sqrt(col1[2]);
333         col2t[0]= sqrt(col2[0]);
334         col2t[1]= sqrt(col2[1]);
335         col2t[2]= sqrt(col2[2]);
336
337         result[0]= (fac1*col1t[0] + fac2*col2t[0]);
338         result[0]*= result[0];
339         result[1]= (fac1*col1t[1] + fac2*col2t[1]);
340         result[1]*= result[1];
341         result[2]= (fac1*col1t[2] + fac2*col2t[2]);
342         result[2]*= result[2];
343 }
344 #endif
345
346 static float shade_by_transmission(Isect *is, ShadeInput *shi, ShadeResult *shr)
347 {
348         float dx, dy, dz, d, p;
349
350         if (0 == (shi->mat->mode & (MA_RAYTRANSP|MA_ZTRA)))
351                 return -1;
352            
353         if (shi->mat->tx_limit <= 0.0f) {
354                 d= 1.0f;
355         } 
356         else {
357                 /* shi.co[] calculated by shade_ray() */
358                 dx= shi->co[0] - is->start[0];
359                 dy= shi->co[1] - is->start[1];
360                 dz= shi->co[2] - is->start[2];
361                 d= sqrt(dx*dx+dy*dy+dz*dz);
362                 if (d > shi->mat->tx_limit)
363                         d= shi->mat->tx_limit;
364
365                 p = shi->mat->tx_falloff;
366                 if(p < 0.0f) p= 0.0f;
367                 else if (p > 10.0f) p= 10.0f;
368
369                 shr->alpha *= pow(d, p);
370                 if (shr->alpha > 1.0f)
371                         shr->alpha= 1.0f;
372         }
373
374         return d;
375 }
376
377 static void ray_fadeout_endcolor(float *col, ShadeInput *origshi, ShadeInput *shi, ShadeResult *shr, Isect *isec, float *vec)
378 {
379         /* un-intersected rays get either rendered material colour or sky colour */
380         if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOMAT) {
381                 VECCOPY(col, shr->combined);
382         } else if (origshi->mat->fadeto_mir == MA_RAYMIR_FADETOSKY) {
383                 VECCOPY(shi->view, vec);
384                 Normalize(shi->view);
385                 
386                 shadeSkyView(col, isec->start, shi->view, NULL);
387         }
388 }
389
390 static void ray_fadeout(Isect *is, ShadeInput *shi, float *col, float *blendcol, float dist_mir)
391 {
392         /* if fading out, linear blend against fade colour */
393         float blendfac;
394
395         blendfac = 1.0 - VecLenf(shi->co, is->start)/dist_mir;
396         
397         col[0] = col[0]*blendfac + (1.0 - blendfac)*blendcol[0];
398         col[1] = col[1]*blendfac + (1.0 - blendfac)*blendcol[1];
399         col[2] = col[2]*blendfac + (1.0 - blendfac)*blendcol[2];
400 }
401
402 /* the main recursive tracer itself */
403 static void traceray(ShadeInput *origshi, ShadeResult *origshr, short depth, float *start, float *vec, float *col, ObjectInstanceRen *obi, VlakRen *vlr, int traflag)
404 {
405         ShadeInput shi;
406         ShadeResult shr;
407         Isect isec;
408         float f, f1, fr, fg, fb;
409         float ref[3], maxsize=RE_ray_tree_max_size(R.raytree);
410         float dist_mir = origshi->mat->dist_mir;
411
412         VECCOPY(isec.start, start);
413         if (dist_mir > 0.0) {
414                 isec.end[0]= start[0]+dist_mir*vec[0];
415                 isec.end[1]= start[1]+dist_mir*vec[1];
416                 isec.end[2]= start[2]+dist_mir*vec[2];
417         } else {
418                 isec.end[0]= start[0]+maxsize*vec[0];
419                 isec.end[1]= start[1]+maxsize*vec[1];
420                 isec.end[2]= start[2]+maxsize*vec[2];
421         }
422         isec.mode= RE_RAY_MIRROR;
423         isec.faceorig= (RayFace*)vlr;
424         isec.oborig= RAY_OBJECT_SET(&R, obi);
425
426         if(RE_ray_tree_intersect(R.raytree, &isec)) {
427                 float d= 1.0f;
428                 
429                 shi.mask= origshi->mask;
430                 shi.osatex= origshi->osatex;
431                 shi.depth= 1;                                   /* only used to indicate tracing */
432                 shi.thread= origshi->thread;
433                 shi.sample= 0;
434                 shi.xs= origshi->xs;
435                 shi.ys= origshi->ys;
436                 shi.lay= origshi->lay;
437                 shi.passflag= SCE_PASS_COMBINED; /* result of tracing needs no pass info */
438                 shi.combinedflag= 0xFFFFFF;              /* ray trace does all options */
439                 shi.do_preview= 0;
440                 shi.light_override= origshi->light_override;
441                 shi.mat_override= origshi->mat_override;
442                 
443                 memset(&shr, 0, sizeof(ShadeResult));
444                 
445                 shade_ray(&isec, &shi, &shr);
446                 if (traflag & RAY_TRA)
447                         d= shade_by_transmission(&isec, &shi, &shr);
448                 
449                 if(depth>0) {
450
451                         if(shi.mat->mode_l & (MA_RAYTRANSP|MA_ZTRA) && shr.alpha < 1.0f) {
452                                 float nf, f, f1, refract[3], tracol[4];
453                                 
454                                 tracol[0]= shi.r;
455                                 tracol[1]= shi.g;
456                                 tracol[2]= shi.b;
457                                 tracol[3]= col[3];      // we pass on and accumulate alpha
458                                 
459                                 if(shi.mat->mode & MA_RAYTRANSP) {
460                                         /* odd depths: use normal facing viewer, otherwise flip */
461                                         if(traflag & RAY_TRAFLIP) {
462                                                 float norm[3];
463                                                 norm[0]= - shi.vn[0];
464                                                 norm[1]= - shi.vn[1];
465                                                 norm[2]= - shi.vn[2];
466                                                 if (!refraction(refract, norm, shi.view, shi.ang))
467                                                         reflection(refract, norm, shi.view, shi.vn);
468                                         }
469                                         else {
470                                                 if (!refraction(refract, shi.vn, shi.view, shi.ang))
471                                                         reflection(refract, shi.vn, shi.view, shi.vn);
472                                         }
473                                         traflag |= RAY_TRA;
474                                         traceray(origshi, origshr, depth-1, shi.co, refract, tracol, shi.obi, shi.vlr, traflag ^ RAY_TRAFLIP);
475                                 }
476                                 else
477                                         traceray(origshi, origshr, depth-1, shi.co, shi.view, tracol, shi.obi, shi.vlr, 0);
478                                 
479                                 f= shr.alpha; f1= 1.0f-f;
480                                 nf= d * shi.mat->filter;
481                                 fr= 1.0f+ nf*(shi.r-1.0f);
482                                 fg= 1.0f+ nf*(shi.g-1.0f);
483                                 fb= 1.0f+ nf*(shi.b-1.0f);
484                                 shr.diff[0]= f*shr.diff[0] + f1*fr*tracol[0];
485                                 shr.diff[1]= f*shr.diff[1] + f1*fg*tracol[1];
486                                 shr.diff[2]= f*shr.diff[2] + f1*fb*tracol[2];
487                                 
488                                 shr.spec[0] *=f;
489                                 shr.spec[1] *=f;
490                                 shr.spec[2] *=f;
491
492                                 col[3]= f1*tracol[3] + f;
493                         }
494                         else 
495                                 col[3]= 1.0f;
496
497                         if(shi.mat->mode_l & MA_RAYMIRROR) {
498                                 f= shi.ray_mirror;
499                                 if(f!=0.0f) f*= fresnel_fac(shi.view, shi.vn, shi.mat->fresnel_mir_i, shi.mat->fresnel_mir);
500                         }
501                         else f= 0.0f;
502                         
503                         if(f!=0.0f) {
504                                 float mircol[4];
505                                 
506                                 reflection(ref, shi.vn, shi.view, NULL);                        
507                                 traceray(origshi, origshr, depth-1, shi.co, ref, mircol, shi.obi, shi.vlr, 0);
508                         
509                                 f1= 1.0f-f;
510
511                                 /* combine */
512                                 //color_combine(col, f*fr*(1.0f-shr.spec[0]), f1, col, shr.diff);
513                                 //col[0]+= shr.spec[0];
514                                 //col[1]+= shr.spec[1];
515                                 //col[2]+= shr.spec[2];
516                                 
517                                 fr= shi.mirr;
518                                 fg= shi.mirg;
519                                 fb= shi.mirb;
520                 
521                                 col[0]= f*fr*(1.0f-shr.spec[0])*mircol[0] + f1*shr.diff[0] + shr.spec[0];
522                                 col[1]= f*fg*(1.0f-shr.spec[1])*mircol[1] + f1*shr.diff[1] + shr.spec[1];
523                                 col[2]= f*fb*(1.0f-shr.spec[2])*mircol[2] + f1*shr.diff[2] + shr.spec[2];
524                         }
525                         else {
526                                 col[0]= shr.diff[0] + shr.spec[0];
527                                 col[1]= shr.diff[1] + shr.spec[1];
528                                 col[2]= shr.diff[2] + shr.spec[2];
529                         }
530                         
531                         if (dist_mir > 0.0) {
532                                 float blendcol[3];
533                                 
534                                 /* max ray distance set, but found an intersection, so fade this colour
535                                  * out towards the sky/material colour for a smooth transition */
536                                 ray_fadeout_endcolor(blendcol, origshi, &shi, origshr, &isec, vec);
537                                 ray_fadeout(&isec, &shi, col, blendcol, dist_mir);
538                         }
539                 }
540                 else {
541                         col[0]= shr.diff[0] + shr.spec[0];
542                         col[1]= shr.diff[1] + shr.spec[1];
543                         col[2]= shr.diff[2] + shr.spec[2];
544                 }
545                 
546         }
547         else {
548                 ray_fadeout_endcolor(col, origshi, &shi, origshr, &isec, vec);
549         }
550 }
551
552 /* **************** jitter blocks ********** */
553
554 /* calc distributed planar energy */
555
556 static void DP_energy(float *table, float *vec, int tot, float xsize, float ysize)
557 {
558         int x, y, a;
559         float *fp, force[3], result[3];
560         float dx, dy, dist, min;
561         
562         min= MIN2(xsize, ysize);
563         min*= min;
564         result[0]= result[1]= 0.0f;
565         
566         for(y= -1; y<2; y++) {
567                 dy= ysize*y;
568                 for(x= -1; x<2; x++) {
569                         dx= xsize*x;
570                         fp= table;
571                         for(a=0; a<tot; a++, fp+= 2) {
572                                 force[0]= vec[0] - fp[0]-dx;
573                                 force[1]= vec[1] - fp[1]-dy;
574                                 dist= force[0]*force[0] + force[1]*force[1];
575                                 if(dist < min && dist>0.0f) {
576                                         result[0]+= force[0]/dist;
577                                         result[1]+= force[1]/dist;
578                                 }
579                         }
580                 }
581         }
582         vec[0] += 0.1*min*result[0]/(float)tot;
583         vec[1] += 0.1*min*result[1]/(float)tot;
584         // cyclic clamping
585         vec[0]= vec[0] - xsize*floor(vec[0]/xsize + 0.5);
586         vec[1]= vec[1] - ysize*floor(vec[1]/ysize + 0.5);
587 }
588
589 // random offset of 1 in 2
590 static void jitter_plane_offset(float *jitter1, float *jitter2, int tot, float sizex, float sizey, float ofsx, float ofsy)
591 {
592         float dsizex= sizex*ofsx;
593         float dsizey= sizey*ofsy;
594         float hsizex= 0.5*sizex, hsizey= 0.5*sizey;
595         int x;
596         
597         for(x=tot; x>0; x--, jitter1+=2, jitter2+=2) {
598                 jitter2[0]= jitter1[0] + dsizex;
599                 jitter2[1]= jitter1[1] + dsizey;
600                 if(jitter2[0] > hsizex) jitter2[0]-= sizex;
601                 if(jitter2[1] > hsizey) jitter2[1]-= sizey;
602         }
603 }
604
605 /* called from convertBlenderScene.c */
606 /* we do this in advance to get consistant random, not alter the render seed, and be threadsafe */
607 void init_jitter_plane(LampRen *lar)
608 {
609         float *fp;
610         int x, iter=12, tot= lar->ray_totsamp;
611         
612         /* test if already initialized */
613         if(lar->jitter) return;
614         
615         /* at least 4, or max threads+1 tables */
616         if(BLENDER_MAX_THREADS < 4) x= 4;
617         else x= BLENDER_MAX_THREADS+1;
618         fp= lar->jitter= MEM_mallocN(x*tot*2*sizeof(float), "lamp jitter tab");
619         
620         /* set per-lamp fixed seed */
621         BLI_srandom(tot);
622         
623         /* fill table with random locations, area_size large */
624         for(x=0; x<tot; x++, fp+=2) {
625                 fp[0]= (BLI_frand()-0.5)*lar->area_size;
626                 fp[1]= (BLI_frand()-0.5)*lar->area_sizey;
627         }
628         
629         while(iter--) {
630                 fp= lar->jitter;
631                 for(x=tot; x>0; x--, fp+=2) {
632                         DP_energy(lar->jitter, fp, tot, lar->area_size, lar->area_sizey);
633                 }
634         }
635         
636         /* create the dithered tables (could just check lamp type!) */
637         jitter_plane_offset(lar->jitter, lar->jitter+2*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.0f);
638         jitter_plane_offset(lar->jitter, lar->jitter+4*tot, tot, lar->area_size, lar->area_sizey, 0.5f, 0.5f);
639         jitter_plane_offset(lar->jitter, lar->jitter+6*tot, tot, lar->area_size, lar->area_sizey, 0.0f, 0.5f);
640 }
641
642 /* table around origin, -0.5*size to 0.5*size */
643 static float *give_jitter_plane(LampRen *lar, int thread, int xs, int ys)
644 {
645         int tot;
646         
647         tot= lar->ray_totsamp;
648                         
649         if(lar->ray_samp_type & LA_SAMP_JITTER) {
650                 /* made it threadsafe */
651                 
652                 if(lar->xold[thread]!=xs || lar->yold[thread]!=ys) {
653                         jitter_plane_offset(lar->jitter, lar->jitter+2*(thread+1)*tot, tot, lar->area_size, lar->area_sizey, BLI_thread_frand(thread), BLI_thread_frand(thread));
654                         lar->xold[thread]= xs; 
655                         lar->yold[thread]= ys;
656                 }
657                 return lar->jitter+2*(thread+1)*tot;
658         }
659         if(lar->ray_samp_type & LA_SAMP_DITHER) {
660                 return lar->jitter + 2*tot*((xs & 1)+2*(ys & 1));
661         }
662         
663         return lar->jitter;
664 }
665
666
667 /* **************** QMC sampling *************** */
668
669 static void halton_sample(double *ht_invprimes, double *ht_nums, double *v)
670 {
671         // incremental halton sequence generator, from:
672         // "Instant Radiosity", Keller A.
673         unsigned int i;
674         
675         for (i = 0; i < 2; i++)
676         {
677                 double r = fabs((1.0 - ht_nums[i]) - 1e-10);
678                 
679                 if (ht_invprimes[i] >= r)
680                 {
681                         double lasth;
682                         double h = ht_invprimes[i];
683                         
684                         do {
685                                 lasth = h;
686                                 h *= ht_invprimes[i];
687                         } while (h >= r);
688                         
689                         ht_nums[i] += ((lasth + h) - 1.0);
690                 }
691                 else
692                         ht_nums[i] += ht_invprimes[i];
693                 
694                 v[i] = (float)ht_nums[i];
695         }
696 }
697
698 /* Generate Hammersley points in [0,1)^2
699  * From Lucille renderer */
700 static void hammersley_create(double *out, int n)
701 {
702         double p, t;
703         int k, kk;
704
705         for (k = 0; k < n; k++) {
706                 t = 0;
707                 for (p = 0.5, kk = k; kk; p *= 0.5, kk >>= 1) {
708                         if (kk & 1) {           /* kk mod 2 = 1         */
709                                 t += p;
710                         }
711                 }
712         
713                 out[2 * k + 0] = (double)k / (double)n;
714                 out[2 * k + 1] = t;
715         }
716 }
717
718 struct QMCSampler *QMC_initSampler(int type, int tot)
719 {       
720         QMCSampler *qsa = MEM_mallocN(sizeof(QMCSampler), "qmc sampler");
721         qsa->samp2d = MEM_mallocN(2*sizeof(double)*tot, "qmc sample table");
722
723         qsa->tot = tot;
724         qsa->type = type;
725         
726         if (qsa->type==SAMP_TYPE_HAMMERSLEY) 
727                 hammersley_create(qsa->samp2d, qsa->tot);
728                 
729         return qsa;
730 }
731
732 static void QMC_initPixel(QMCSampler *qsa, int thread)
733 {
734         if (qsa->type==SAMP_TYPE_HAMMERSLEY)
735         {
736                 /* hammersley sequence is fixed, already created in QMCSampler init.
737                  * per pixel, gets a random offset. We create separate offsets per thread, for write-safety */
738                 qsa->offs[thread][0] = 0.5 * BLI_thread_frand(thread);
739                 qsa->offs[thread][1] = 0.5 * BLI_thread_frand(thread);
740         }
741         else {  /* SAMP_TYPE_HALTON */
742                 
743                 /* generate a new randomised halton sequence per pixel
744                  * to alleviate qmc artifacts and make it reproducable 
745                  * between threads/frames */
746                 double ht_invprimes[2], ht_nums[2];
747                 double r[2];
748                 int i;
749         
750                 ht_nums[0] = BLI_thread_frand(thread);
751                 ht_nums[1] = BLI_thread_frand(thread);
752                 ht_invprimes[0] = 0.5;
753                 ht_invprimes[1] = 1.0/3.0;
754                 
755                 for (i=0; i< qsa->tot; i++) {
756                         halton_sample(ht_invprimes, ht_nums, r);
757                         qsa->samp2d[2*i+0] = r[0];
758                         qsa->samp2d[2*i+1] = r[1];
759                 }
760         }
761 }
762
763 static void QMC_freeSampler(QMCSampler *qsa)
764 {
765         MEM_freeN(qsa->samp2d);
766         MEM_freeN(qsa);
767 }
768
769 static void QMC_getSample(double *s, QMCSampler *qsa, int thread, int num)
770 {
771         if (qsa->type == SAMP_TYPE_HAMMERSLEY) {
772                 s[0] = fmod(qsa->samp2d[2*num+0] + qsa->offs[thread][0], 1.0f);
773                 s[1] = fmod(qsa->samp2d[2*num+1] + qsa->offs[thread][1], 1.0f);
774         }
775         else { /* SAMP_TYPE_HALTON */
776                 s[0] = qsa->samp2d[2*num+0];
777                 s[1] = qsa->samp2d[2*num+1];
778         }
779 }
780
781 /* phong weighted disc using 'blur' for exponent, centred on 0,0 */
782 static void QMC_samplePhong(float *vec, QMCSampler *qsa, int thread, int num, float blur)
783 {
784         double s[2];
785         float phi, pz, sqr;
786         
787         QMC_getSample(s, qsa, thread, num);
788
789         phi = s[0]*2*M_PI;
790         pz = pow(s[1], blur);
791         sqr = sqrt(1.0f-pz*pz);
792
793         vec[0] = cos(phi)*sqr;
794         vec[1] = sin(phi)*sqr;
795         vec[2] = 0.0f;
796 }
797
798 /* rect of edge lengths sizex, sizey, centred on 0.0,0.0 i.e. ranging from -sizex/2 to +sizey/2 */
799 static void QMC_sampleRect(float *vec, QMCSampler *qsa, int thread, int num, float sizex, float sizey)
800 {
801         double s[2];
802
803         QMC_getSample(s, qsa, thread, num);
804                 
805         vec[0] = (s[0] - 0.5) * sizex;
806         vec[1] = (s[1] - 0.5) * sizey;
807         vec[2] = 0.0f;
808 }
809
810 /* disc of radius 'radius', centred on 0,0 */
811 static void QMC_sampleDisc(float *vec, QMCSampler *qsa, int thread, int num, float radius)
812 {
813         double s[2];
814         float phi, sqr;
815         
816         QMC_getSample(s, qsa, thread, num);
817         
818         phi = s[0]*2*M_PI;
819         sqr = sqrt(s[1]);
820
821         vec[0] = cos(phi)*sqr* radius/2.0;
822         vec[1] = sin(phi)*sqr* radius/2.0;
823         vec[2] = 0.0f;
824 }
825
826 /* uniform hemisphere sampling */
827 static void QMC_sampleHemi(float *vec, QMCSampler *qsa, int thread, int num)
828 {
829         double s[2];
830         float phi, sqr;
831         
832         QMC_getSample(s, qsa, thread, num);
833         
834         phi = s[0]*2.f*M_PI;    
835         sqr = sqrt(s[1]);
836
837         vec[0] = cos(phi)*sqr;
838         vec[1] = sin(phi)*sqr;
839         vec[2] = 1.f - s[1]*s[1];
840 }
841
842 #if 0 /* currently not used */
843 /* cosine weighted hemisphere sampling */
844 static void QMC_sampleHemiCosine(float *vec, QMCSampler *qsa, int thread, int num)
845 {
846         double s[2];
847         float phi, sqr;
848         
849         QMC_getSample(s, qsa, thread, num);
850         
851         phi = s[0]*2.f*M_PI;    
852         sqr = s[1]*sqrt(2-s[1]*s[1]);
853
854         vec[0] = cos(phi)*sqr;
855         vec[1] = sin(phi)*sqr;
856         vec[2] = 1.f - s[1]*s[1];
857
858 }
859 #endif
860
861 /* called from convertBlenderScene.c */
862 /* samples don't change per pixel, so build the samples in advance for efficiency */
863 void init_lamp_hammersley(LampRen *lar)
864 {
865         lar->qsa = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, lar->ray_totsamp);
866 }
867
868 void init_render_hammersley(Render *re)
869 {
870         re->qsa = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, (re->wrld.aosamp * re->wrld.aosamp));
871 }
872
873 void free_lamp_qmcsampler(LampRen *lar)
874 {
875         QMC_freeSampler(lar->qsa);
876 }
877
878 void free_render_qmcsampler(Render *re)
879 {
880         QMC_freeSampler(re->qsa);
881 }
882
883 static int adaptive_sample_variance(int samples, float *col, float *colsq, float thresh)
884 {
885         float var[3], mean[3];
886
887         /* scale threshold just to give a bit more precision in input rather than dealing with 
888          * tiny tiny numbers in the UI */
889         thresh /= 2;
890         
891         mean[0] = col[0] / (float)samples;
892         mean[1] = col[1] / (float)samples;
893         mean[2] = col[2] / (float)samples;
894
895         var[0] = (colsq[0] / (float)samples) - (mean[0]*mean[0]);
896         var[1] = (colsq[1] / (float)samples) - (mean[1]*mean[1]);
897         var[2] = (colsq[2] / (float)samples) - (mean[2]*mean[2]);
898         
899         if ((var[0] * 0.4 < thresh) && (var[1] * 0.3 < thresh) && (var[2] * 0.6 < thresh))
900                 return 1;
901         else
902                 return 0;
903 }
904
905 static int adaptive_sample_contrast_val(int samples, float prev, float val, float thresh)
906 {
907         /* if the last sample's contribution to the total value was below a small threshold
908          * (i.e. the samples taken are very similar), then taking more samples that are probably 
909          * going to be the same is wasting effort */
910         if (fabs( prev/(float)(samples-1) - val/(float)samples ) < thresh) {
911                 return 1;
912         } else
913                 return 0;
914 }
915
916 static float get_avg_speed(ShadeInput *shi)
917 {
918         float pre_x, pre_y, post_x, post_y, speedavg;
919         
920         pre_x = (shi->winspeed[0] == PASS_VECTOR_MAX)?0.0:shi->winspeed[0];
921         pre_y = (shi->winspeed[1] == PASS_VECTOR_MAX)?0.0:shi->winspeed[1];
922         post_x = (shi->winspeed[2] == PASS_VECTOR_MAX)?0.0:shi->winspeed[2];
923         post_y = (shi->winspeed[3] == PASS_VECTOR_MAX)?0.0:shi->winspeed[3];
924         
925         speedavg = (sqrt(pre_x*pre_x + pre_y*pre_y) + sqrt(post_x*post_x + post_y*post_y)) / 2.0;
926         
927         return speedavg;
928 }
929
930 /* ***************** main calls ************** */
931
932
933 static void trace_refract(float *col, ShadeInput *shi, ShadeResult *shr)
934 {
935         QMCSampler *qsa=NULL;
936         int samp_type;
937         
938         float samp3d[3], orthx[3], orthy[3];
939         float v_refract[3], v_refract_new[3];
940         float sampcol[4], colsq[4];
941         
942         float blur = pow(1.0 - shi->mat->gloss_tra, 3);
943         short max_samples = shi->mat->samp_gloss_tra;
944         float adapt_thresh = shi->mat->adapt_thresh_tra;
945         
946         int samples=0;
947         
948         colsq[0] = colsq[1] = colsq[2] = 0.0;
949         col[0] = col[1] = col[2] = 0.0;
950         col[3]= shr->alpha;
951         
952         if (blur > 0.0) {
953                 if (adapt_thresh != 0.0) samp_type = SAMP_TYPE_HALTON;
954                 else samp_type = SAMP_TYPE_HAMMERSLEY;
955                         
956                 /* all samples are generated per pixel */
957                 qsa = QMC_initSampler(samp_type, max_samples);
958                 QMC_initPixel(qsa, shi->thread);
959         } else 
960                 max_samples = 1;
961         
962
963         while (samples < max_samples) {         
964                 refraction(v_refract, shi->vn, shi->view, shi->ang);
965                 
966                 if (max_samples > 1) {
967                         /* get a quasi-random vector from a phong-weighted disc */
968                         QMC_samplePhong(samp3d, qsa, shi->thread, samples, blur);
969                                                 
970                         VecOrthoBasisf(v_refract, orthx, orthy);
971                         VecMulf(orthx, samp3d[0]);
972                         VecMulf(orthy, samp3d[1]);
973                                 
974                         /* and perturb the refraction vector in it */
975                         VecAddf(v_refract_new, v_refract, orthx);
976                         VecAddf(v_refract_new, v_refract_new, orthy);
977                         
978                         Normalize(v_refract_new);
979                 } else {
980                         /* no blurriness, use the original normal */
981                         VECCOPY(v_refract_new, v_refract);
982                 }
983         
984                 traceray(shi, shr, shi->mat->ray_depth_tra, shi->co, v_refract_new, sampcol, shi->obi, shi->vlr, RAY_TRA|RAY_TRAFLIP);
985         
986                 col[0] += sampcol[0];
987                 col[1] += sampcol[1];
988                 col[2] += sampcol[2];
989                 col[3] += sampcol[3];
990                 
991                 /* for variance calc */
992                 colsq[0] += sampcol[0]*sampcol[0];
993                 colsq[1] += sampcol[1]*sampcol[1];
994                 colsq[2] += sampcol[2]*sampcol[2];
995                 
996                 samples++;
997                 
998                 /* adaptive sampling */
999                 if (adapt_thresh < 1.0 && samples > max_samples/2) 
1000                 {
1001                         if (adaptive_sample_variance(samples, col, colsq, adapt_thresh))
1002                                 break;
1003                         
1004                         /* if the pixel so far is very dark, we can get away with less samples */
1005                         if ( (col[0] + col[1] + col[2])/3.0/(float)samples < 0.01 )
1006                                 max_samples--;
1007                 }
1008         }
1009         
1010         col[0] /= (float)samples;
1011         col[1] /= (float)samples;
1012         col[2] /= (float)samples;
1013         col[3] /= (float)samples;
1014         
1015         if (qsa) QMC_freeSampler(qsa);
1016 }
1017
1018 static void trace_reflect(float *col, ShadeInput *shi, ShadeResult *shr, float fresnelfac)
1019 {
1020         QMCSampler *qsa=NULL;
1021         int samp_type;
1022         
1023         float samp3d[3], orthx[3], orthy[3];
1024         float v_nor_new[3], v_reflect[3];
1025         float sampcol[4], colsq[4];
1026                 
1027         float blur = pow(1.0 - shi->mat->gloss_mir, 3);
1028         short max_samples = shi->mat->samp_gloss_mir;
1029         float adapt_thresh = shi->mat->adapt_thresh_mir;
1030         float aniso = 1.0 - shi->mat->aniso_gloss_mir;
1031         
1032         int samples=0;
1033         
1034         col[0] = col[1] = col[2] = 0.0;
1035         colsq[0] = colsq[1] = colsq[2] = 0.0;
1036         
1037         if (blur > 0.0) {
1038                 if (adapt_thresh != 0.0) samp_type = SAMP_TYPE_HALTON;
1039                 else samp_type = SAMP_TYPE_HAMMERSLEY;
1040                         
1041                 /* all samples are generated per pixel */
1042                 qsa = QMC_initSampler(samp_type, max_samples);
1043                 QMC_initPixel(qsa, shi->thread);
1044         } else 
1045                 max_samples = 1;
1046         
1047         while (samples < max_samples) {
1048                                 
1049                 if (max_samples > 1) {
1050                         /* get a quasi-random vector from a phong-weighted disc */
1051                         QMC_samplePhong(samp3d, qsa, shi->thread, samples, blur);
1052
1053                         /* find the normal's perpendicular plane, blurring along tangents
1054                          * if tangent shading enabled */
1055                         if (shi->mat->mode & (MA_TANGENT_V)) {
1056                                 Crossf(orthx, shi->vn, shi->tang);      // bitangent
1057                                 VECCOPY(orthy, shi->tang);
1058                                 VecMulf(orthx, samp3d[0]);
1059                                 VecMulf(orthy, samp3d[1]*aniso);
1060                         } else {
1061                                 VecOrthoBasisf(shi->vn, orthx, orthy);
1062                                 VecMulf(orthx, samp3d[0]);
1063                                 VecMulf(orthy, samp3d[1]);
1064                         }
1065
1066                         /* and perturb the normal in it */
1067                         VecAddf(v_nor_new, shi->vn, orthx);
1068                         VecAddf(v_nor_new, v_nor_new, orthy);
1069                         Normalize(v_nor_new);
1070                 } else {
1071                         /* no blurriness, use the original normal */
1072                         VECCOPY(v_nor_new, shi->vn);
1073                 }
1074                 
1075                 if((shi->vlr->flag & R_SMOOTH)) 
1076                         reflection(v_reflect, v_nor_new, shi->view, shi->facenor);
1077                 else
1078                         reflection(v_reflect, v_nor_new, shi->view, NULL);
1079                 
1080                 traceray(shi, shr, shi->mat->ray_depth, shi->co, v_reflect, sampcol, shi->obi, shi->vlr, 0);
1081
1082                 
1083                 col[0] += sampcol[0];
1084                 col[1] += sampcol[1];
1085                 col[2] += sampcol[2];
1086         
1087                 /* for variance calc */
1088                 colsq[0] += sampcol[0]*sampcol[0];
1089                 colsq[1] += sampcol[1]*sampcol[1];
1090                 colsq[2] += sampcol[2]*sampcol[2];
1091                 
1092                 samples++;
1093
1094                 /* adaptive sampling */
1095                 if (adapt_thresh > 0.0 && samples > max_samples/3) 
1096                 {
1097                         if (adaptive_sample_variance(samples, col, colsq, adapt_thresh))
1098                                 break;
1099                         
1100                         /* if the pixel so far is very dark, we can get away with less samples */
1101                         if ( (col[0] + col[1] + col[2])/3.0/(float)samples < 0.01 )
1102                                 max_samples--;
1103                 
1104                         /* reduce samples when reflection is dim due to low ray mirror blend value or fresnel factor
1105                          * and when reflection is blurry */
1106                         if (fresnelfac < 0.1 * (blur+1)) {
1107                                 max_samples--;
1108                                 
1109                                 /* even more for very dim */
1110                                 if (fresnelfac < 0.05 * (blur+1)) 
1111                                         max_samples--;
1112                         }
1113                 }
1114         }
1115         
1116         col[0] /= (float)samples;
1117         col[1] /= (float)samples;
1118         col[2] /= (float)samples;
1119         
1120         if (qsa) QMC_freeSampler(qsa);
1121 }
1122
1123 /* extern call from render loop */
1124 void ray_trace(ShadeInput *shi, ShadeResult *shr)
1125 {
1126         VlakRen *vlr;
1127         float i, f, f1, fr, fg, fb;
1128         float mircol[4], tracol[4];
1129         float diff[3];
1130         int do_tra, do_mir;
1131         
1132         do_tra= ((shi->mat->mode & (MA_RAYTRANSP)) && shr->alpha!=1.0f);
1133         do_mir= ((shi->mat->mode & MA_RAYMIRROR) && shi->ray_mirror!=0.0f);
1134         vlr= shi->vlr;
1135         
1136         /* raytrace mirror amd refract like to separate the spec color */
1137         if(shi->combinedflag & SCE_PASS_SPEC)
1138                 VECSUB(diff, shr->combined, shr->spec) /* no ; */
1139         else
1140                 VECCOPY(diff, shr->combined);
1141         
1142         if(do_tra) {
1143                 float olddiff[3];
1144                 
1145                 trace_refract(tracol, shi, shr);
1146                 
1147                 f= shr->alpha; f1= 1.0f-f;
1148                 fr= 1.0f+ shi->mat->filter*(shi->r-1.0f);
1149                 fg= 1.0f+ shi->mat->filter*(shi->g-1.0f);
1150                 fb= 1.0f+ shi->mat->filter*(shi->b-1.0f);
1151                 
1152                 /* for refract pass */
1153                 VECCOPY(olddiff, diff);
1154                 
1155                 diff[0]= f*diff[0] + f1*fr*tracol[0];
1156                 diff[1]= f*diff[1] + f1*fg*tracol[1];
1157                 diff[2]= f*diff[2] + f1*fb*tracol[2];
1158                 
1159                 if(shi->passflag & SCE_PASS_REFRACT)
1160                         VECSUB(shr->refr, diff, olddiff);
1161                 
1162                 if(!(shi->combinedflag & SCE_PASS_REFRACT))
1163                         VECSUB(diff, diff, shr->refr);
1164                 
1165                 shr->alpha= tracol[3];
1166         }
1167         
1168         if(do_mir) {
1169         
1170                 i= shi->ray_mirror*fresnel_fac(shi->view, shi->vn, shi->mat->fresnel_mir_i, shi->mat->fresnel_mir);
1171                 if(i!=0.0f) {
1172                 
1173                         trace_reflect(mircol, shi, shr, i);
1174                         
1175                         fr= i*shi->mirr;
1176                         fg= i*shi->mirg;
1177                         fb= i*shi->mirb;
1178
1179                         if(shi->passflag & SCE_PASS_REFLECT) {
1180                                 /* mirror pass is not blocked out with spec */
1181                                 shr->refl[0]= fr*mircol[0] - fr*diff[0];
1182                                 shr->refl[1]= fg*mircol[1] - fg*diff[1];
1183                                 shr->refl[2]= fb*mircol[2] - fb*diff[2];
1184                         }
1185                         
1186                         if(shi->combinedflag & SCE_PASS_REFLECT) {
1187                                 
1188                                 f= fr*(1.0f-shr->spec[0]);      f1= 1.0f-i;
1189                                 diff[0]= f*mircol[0] + f1*diff[0];
1190                                 
1191                                 f= fg*(1.0f-shr->spec[1]);      f1= 1.0f-i;
1192                                 diff[1]= f*mircol[1] + f1*diff[1];
1193                                 
1194                                 f= fb*(1.0f-shr->spec[2]);      f1= 1.0f-i;
1195                                 diff[2]= f*mircol[2] + f1*diff[2];
1196                         }
1197                 }
1198         }
1199         /* put back together */
1200         if(shi->combinedflag & SCE_PASS_SPEC)
1201                 VECADD(shr->combined, diff, shr->spec) /* no ; */
1202         else
1203                 VECCOPY(shr->combined, diff);
1204 }
1205
1206 /* color 'shadfac' passes through 'col' with alpha and filter */
1207 /* filter is only applied on alpha defined transparent part */
1208 static void addAlphaLight(float *shadfac, float *col, float alpha, float filter)
1209 {
1210         float fr, fg, fb;
1211         
1212         fr= 1.0f+ filter*(col[0]-1.0f);
1213         fg= 1.0f+ filter*(col[1]-1.0f);
1214         fb= 1.0f+ filter*(col[2]-1.0f);
1215         
1216         shadfac[0]= alpha*col[0] + fr*(1.0f-alpha)*shadfac[0];
1217         shadfac[1]= alpha*col[1] + fg*(1.0f-alpha)*shadfac[1];
1218         shadfac[2]= alpha*col[2] + fb*(1.0f-alpha)*shadfac[2];
1219         
1220         shadfac[3]= (1.0f-alpha)*shadfac[3];
1221 }
1222
1223 static void ray_trace_shadow_tra(Isect *is, int depth, int traflag)
1224 {
1225         /* ray to lamp, find first face that intersects, check alpha properties,
1226            if it has col[3]>0.0f  continue. so exit when alpha is full */
1227         ShadeInput shi;
1228         ShadeResult shr;
1229
1230         if(RE_ray_tree_intersect(R.raytree, is)) {
1231                 float d= 1.0f;
1232                 /* we got a face */
1233                 
1234                 shi.depth= 1;                                   /* only used to indicate tracing */
1235                 shi.mask= 1;
1236                 shi.osatex= 0;
1237                 shi.thread= shi.sample= 0;
1238                 shi.lay= 0;
1239                 shi.passflag= 0;
1240                 shi.combinedflag= 0;
1241                 shi.do_preview= 0;
1242                 shi.light_override= NULL;
1243                 shi.mat_override= NULL;
1244                 
1245                 shade_ray(is, &shi, &shr);
1246                 if (traflag & RAY_TRA)
1247                         d= shade_by_transmission(is, &shi, &shr);
1248                 
1249                 /* mix colors based on shadfac (rgb + amount of light factor) */
1250                 addAlphaLight(is->col, shr.diff, shr.alpha, d*shi.mat->filter);
1251                 
1252                 if(depth>0 && is->col[3]>0.0f) {
1253                         
1254                         /* adapt isect struct */
1255                         VECCOPY(is->start, shi.co);
1256                         is->oborig= RAY_OBJECT_SET(&R, shi.obi);
1257                         is->faceorig= (RayFace*)shi.vlr;
1258
1259                         ray_trace_shadow_tra(is, depth-1, traflag | RAY_TRA);
1260                 }
1261         }
1262 }
1263
1264 /* not used, test function for ambient occlusion (yaf: pathlight) */
1265 /* main problem; has to be called within shading loop, giving unwanted recursion */
1266 int ray_trace_shadow_rad(ShadeInput *ship, ShadeResult *shr)
1267 {
1268         static int counter=0, only_one= 0;
1269         extern float hashvectf[];
1270         Isect isec;
1271         ShadeInput shi;
1272         ShadeResult shr_t;
1273         float vec[3], accum[3], div= 0.0f, maxsize= RE_ray_tree_max_size(R.raytree);
1274         int a;
1275         
1276         if(only_one) {
1277                 return 0;
1278         }
1279         only_one= 1;
1280         
1281         accum[0]= accum[1]= accum[2]= 0.0f;
1282         isec.mode= RE_RAY_MIRROR;
1283         isec.faceorig= (RayFace*)ship->vlr;
1284         isec.oborig= RAY_OBJECT_SET(&R, ship->obi);
1285         
1286         for(a=0; a<8*8; a++) {
1287                 
1288                 counter+=3;
1289                 counter %= 768;
1290                 VECCOPY(vec, hashvectf+counter);
1291                 if(ship->vn[0]*vec[0]+ship->vn[1]*vec[1]+ship->vn[2]*vec[2]>0.0f) {
1292                         vec[0]-= vec[0];
1293                         vec[1]-= vec[1];
1294                         vec[2]-= vec[2];
1295                 }
1296                 VECCOPY(isec.start, ship->co);
1297                 isec.end[0]= isec.start[0] + maxsize*vec[0];
1298                 isec.end[1]= isec.start[1] + maxsize*vec[1];
1299                 isec.end[2]= isec.start[2] + maxsize*vec[2];
1300                 
1301                 if(RE_ray_tree_intersect(R.raytree, &isec)) {
1302                         float fac;
1303                         shade_ray(&isec, &shi, &shr_t);
1304                         fac= isec.labda*isec.labda;
1305                         fac= 1.0f;
1306                         accum[0]+= fac*(shr_t.diff[0]+shr_t.spec[0]);
1307                         accum[1]+= fac*(shr_t.diff[1]+shr_t.spec[1]);
1308                         accum[2]+= fac*(shr_t.diff[2]+shr_t.spec[2]);
1309                         div+= fac;
1310                 }
1311                 else div+= 1.0f;
1312         }
1313         
1314         if(div!=0.0f) {
1315                 shr->diff[0]+= accum[0]/div;
1316                 shr->diff[1]+= accum[1]/div;
1317                 shr->diff[2]+= accum[2]/div;
1318         }
1319         shr->alpha= 1.0f;
1320         
1321         only_one= 0;
1322         return 1;
1323 }
1324
1325 /* aolight: function to create random unit sphere vectors for total random sampling */
1326 static void RandomSpherical(float *v)
1327 {
1328         float r;
1329         v[2] = 2.f*BLI_frand()-1.f;
1330         if ((r = 1.f - v[2]*v[2])>0.f) {
1331                 float a = 6.283185307f*BLI_frand();
1332                 r = sqrt(r);
1333                 v[0] = r * cos(a);
1334                 v[1] = r * sin(a);
1335         }
1336         else v[2] = 1.f;
1337 }
1338
1339 /* calc distributed spherical energy */
1340 static void DS_energy(float *sphere, int tot, float *vec)
1341 {
1342         float *fp, fac, force[3], res[3];
1343         int a;
1344         
1345         res[0]= res[1]= res[2]= 0.0f;
1346         
1347         for(a=0, fp=sphere; a<tot; a++, fp+=3) {
1348                 VecSubf(force, vec, fp);
1349                 fac= force[0]*force[0] + force[1]*force[1] + force[2]*force[2];
1350                 if(fac!=0.0f) {
1351                         fac= 1.0f/fac;
1352                         res[0]+= fac*force[0];
1353                         res[1]+= fac*force[1];
1354                         res[2]+= fac*force[2];
1355                 }
1356         }
1357
1358         VecMulf(res, 0.5);
1359         VecAddf(vec, vec, res);
1360         Normalize(vec);
1361         
1362 }
1363
1364 /* called from convertBlenderScene.c */
1365 /* creates an equally distributed spherical sample pattern */
1366 /* and allocates threadsafe memory */
1367 void init_ao_sphere(World *wrld)
1368 {
1369         float *fp;
1370         int a, tot, iter= 16;
1371
1372         /* we make twice the amount of samples, because only a hemisphere is used */
1373         tot= 2*wrld->aosamp*wrld->aosamp;
1374         
1375         wrld->aosphere= MEM_mallocN(3*tot*sizeof(float), "AO sphere");
1376         
1377         /* fixed random */
1378         BLI_srandom(tot);
1379         
1380         /* init */
1381         fp= wrld->aosphere;
1382         for(a=0; a<tot; a++, fp+= 3) {
1383                 RandomSpherical(fp);
1384         }
1385         
1386         while(iter--) {
1387                 for(a=0, fp= wrld->aosphere; a<tot; a++, fp+= 3) {
1388                         DS_energy(wrld->aosphere, tot, fp);
1389                 }
1390         }
1391         
1392         /* tables */
1393         wrld->aotables= MEM_mallocN(BLENDER_MAX_THREADS*3*tot*sizeof(float), "AO tables");
1394 }
1395
1396 /* give per thread a table, we have to compare xs ys because of way OSA works... */
1397 static float *threadsafe_table_sphere(int test, int thread, int xs, int ys, int tot)
1398 {
1399         static int xso[BLENDER_MAX_THREADS], yso[BLENDER_MAX_THREADS];
1400         static int firsttime= 1;
1401         
1402         if(firsttime) {
1403                 memset(xso, 255, sizeof(xso));
1404                 memset(yso, 255, sizeof(yso));
1405                 firsttime= 0;
1406         }
1407         
1408         if(xs==xso[thread] && ys==yso[thread]) return R.wrld.aotables+ thread*tot*3;
1409         if(test) return NULL;
1410         xso[thread]= xs; yso[thread]= ys;
1411         return R.wrld.aotables+ thread*tot*3;
1412 }
1413
1414 static float *sphere_sampler(int type, int resol, int thread, int xs, int ys)
1415 {
1416         int tot;
1417         float *vec;
1418         
1419         if(resol>16) resol= 16;
1420         
1421         tot= 2*resol*resol;
1422
1423         if (type & WO_AORNDSMP) {
1424                 static float sphere[2*3*256];
1425                 int a;
1426                 
1427                 /* total random sampling. NOT THREADSAFE! (should be removed, is not useful) */
1428                 vec= sphere;
1429                 for (a=0; a<tot; a++, vec+=3) {
1430                         RandomSpherical(vec);
1431                 }
1432                 
1433                 return sphere;
1434         } 
1435         else {
1436                 float *sphere;
1437                 float cosfi, sinfi, cost, sint;
1438                 float ang, *vec1;
1439                 int a;
1440                 
1441                 sphere= threadsafe_table_sphere(1, thread, xs, ys, tot);        // returns table if xs and ys were equal to last call
1442                 if(sphere==NULL) {
1443                         sphere= threadsafe_table_sphere(0, thread, xs, ys, tot);
1444                         
1445                         // random rotation
1446                         ang= BLI_thread_frand(thread);
1447                         sinfi= sin(ang); cosfi= cos(ang);
1448                         ang= BLI_thread_frand(thread);
1449                         sint= sin(ang); cost= cos(ang);
1450                         
1451                         vec= R.wrld.aosphere;
1452                         vec1= sphere;
1453                         for (a=0; a<tot; a++, vec+=3, vec1+=3) {
1454                                 vec1[0]= cost*cosfi*vec[0] - sinfi*vec[1] + sint*cosfi*vec[2];
1455                                 vec1[1]= cost*sinfi*vec[0] + cosfi*vec[1] + sint*sinfi*vec[2];
1456                                 vec1[2]= -sint*vec[0] + cost*vec[2];                    
1457                         }
1458                 }
1459                 return sphere;
1460         }
1461 }
1462
1463 void ray_ao_qmc(ShadeInput *shi, float *shadfac)
1464 {
1465         Isect isec;
1466         QMCSampler *qsa=NULL;
1467         float samp3d[3];
1468         float up[3], side[3], dir[3], nrm[3];
1469         
1470         float maxdist = R.wrld.aodist;
1471         float fac=0.0f, prev=0.0f;
1472         float adapt_thresh = G.scene->world->ao_adapt_thresh;
1473         float adapt_speed_fac = G.scene->world->ao_adapt_speed_fac;
1474         float bias = G.scene->world->aobias;
1475         
1476         int samples=0;
1477         int max_samples = R.wrld.aosamp*R.wrld.aosamp;
1478         
1479         float dxyview[3], skyadded=0, div;
1480         int aocolor;
1481         
1482         isec.faceorig= (RayFace*)shi->vlr;
1483         isec.oborig= RAY_OBJECT_SET(&R, shi->obi);
1484         isec.face_last= NULL;
1485         isec.ob_last= 0;
1486         isec.mode= (R.wrld.aomode & WO_AODIST)?RE_RAY_SHADOW_TRA:RE_RAY_SHADOW;
1487         isec.lay= -1;
1488         VECCOPY(isec.start, shi->co);
1489         
1490         shadfac[0]= shadfac[1]= shadfac[2]= 0.0f;
1491         
1492         /* prevent sky colors to be added for only shadow (shadow becomes alpha) */
1493         aocolor= R.wrld.aocolor;
1494         if(shi->mat->mode & MA_ONLYSHADOW)
1495                 aocolor= WO_AOPLAIN;
1496         
1497         if(aocolor == WO_AOSKYTEX) {
1498                 dxyview[0]= 1.0f/(float)R.wrld.aosamp;
1499                 dxyview[1]= 1.0f/(float)R.wrld.aosamp;
1500                 dxyview[2]= 0.0f;
1501         }
1502         
1503         /* bias prevents smoothed faces to appear flat */
1504         if(shi->vlr->flag & R_SMOOTH) {
1505                 bias= G.scene->world->aobias;
1506                 VECCOPY(nrm, shi->vn);
1507         }
1508         else {
1509                 bias= 0.0f;
1510                 VECCOPY(nrm, shi->facenor);
1511         }
1512         
1513         VecOrthoBasisf(nrm, up, side);
1514         
1515         /* sampling init */
1516         if (R.wrld.ao_samp_method==WO_AOSAMP_HALTON) {
1517                 float speedfac;
1518                 
1519                 speedfac = get_avg_speed(shi) * adapt_speed_fac;
1520                 CLAMP(speedfac, 1.0, 1000.0);
1521                 max_samples /= speedfac;
1522                 if (max_samples < 5) max_samples = 5;
1523                 
1524                 qsa = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
1525         } else if (R.wrld.ao_samp_method==WO_AOSAMP_HAMMERSLEY)
1526                 qsa = R.qsa;
1527
1528         QMC_initPixel(qsa, shi->thread);
1529         
1530         while (samples < max_samples) {
1531
1532                 /* sampling, returns quasi-random vector in unit hemisphere */
1533                 QMC_sampleHemi(samp3d, qsa, shi->thread, samples);
1534
1535                 dir[0] = (samp3d[0]*up[0] + samp3d[1]*side[0] + samp3d[2]*nrm[0]);
1536                 dir[1] = (samp3d[0]*up[1] + samp3d[1]*side[1] + samp3d[2]*nrm[1]);
1537                 dir[2] = (samp3d[0]*up[2] + samp3d[1]*side[2] + samp3d[2]*nrm[2]);
1538                 
1539                 Normalize(dir);
1540                         
1541                 isec.end[0] = shi->co[0] - maxdist*dir[0];
1542                 isec.end[1] = shi->co[1] - maxdist*dir[1];
1543                 isec.end[2] = shi->co[2] - maxdist*dir[2];
1544                 
1545                 prev = fac;
1546                 
1547                 if(RE_ray_tree_intersect(R.raytree, &isec)) {
1548                         if (R.wrld.aomode & WO_AODIST) fac+= exp(-isec.labda*R.wrld.aodistfac); 
1549                         else fac+= 1.0f;
1550                 }
1551                 else if(aocolor!=WO_AOPLAIN) {
1552                         float skycol[4];
1553                         float skyfac, view[3];
1554                         
1555                         view[0]= -dir[0];
1556                         view[1]= -dir[1];
1557                         view[2]= -dir[2];
1558                         Normalize(view);
1559                         
1560                         if(aocolor==WO_AOSKYCOL) {
1561                                 skyfac= 0.5*(1.0f+view[0]*R.grvec[0]+ view[1]*R.grvec[1]+ view[2]*R.grvec[2]);
1562                                 shadfac[0]+= (1.0f-skyfac)*R.wrld.horr + skyfac*R.wrld.zenr;
1563                                 shadfac[1]+= (1.0f-skyfac)*R.wrld.horg + skyfac*R.wrld.zeng;
1564                                 shadfac[2]+= (1.0f-skyfac)*R.wrld.horb + skyfac*R.wrld.zenb;
1565                         }
1566                         else {  /* WO_AOSKYTEX */
1567                                 shadeSkyView(skycol, isec.start, view, dxyview);
1568                                 shadfac[0]+= skycol[0];
1569                                 shadfac[1]+= skycol[1];
1570                                 shadfac[2]+= skycol[2];
1571                         }
1572                         skyadded++;
1573                 }
1574                 
1575                 samples++;
1576                 
1577                 if (qsa->type == SAMP_TYPE_HALTON) {
1578                         /* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */          
1579                         if (adapt_thresh > 0.0 && (samples > max_samples/2) ) {
1580                                 
1581                                 if (adaptive_sample_contrast_val(samples, prev, fac, adapt_thresh)) {
1582                                         break;
1583                                 }
1584                         }
1585                 }
1586         }
1587         
1588         if(aocolor!=WO_AOPLAIN && skyadded) {
1589                 div= (1.0f - fac/(float)samples)/((float)skyadded);
1590                 
1591                 shadfac[0]*= div;       // average color times distances/hits formula
1592                 shadfac[1]*= div;       // average color times distances/hits formula
1593                 shadfac[2]*= div;       // average color times distances/hits formula
1594         } else {
1595                 shadfac[0]= shadfac[1]= shadfac[2]= 1.0f - fac/(float)samples;
1596         }
1597         
1598         if ((qsa) && (qsa->type == SAMP_TYPE_HALTON)) QMC_freeSampler(qsa);
1599 }
1600
1601 /* extern call from shade_lamp_loop, ambient occlusion calculus */
1602 void ray_ao_spheresamp(ShadeInput *shi, float *shadfac)
1603 {
1604         Isect isec;
1605         float *vec, *nrm, div, bias, sh=0.0f;
1606         float maxdist = R.wrld.aodist;
1607         float dxyview[3];
1608         int j= -1, tot, actual=0, skyadded=0, aocolor;
1609         
1610         isec.faceorig= (RayFace*)shi->vlr;
1611         isec.oborig= RAY_OBJECT_SET(&R, shi->obi);
1612         isec.face_last= NULL;
1613         isec.ob_last= 0;
1614         isec.mode= (R.wrld.aomode & WO_AODIST)?RE_RAY_SHADOW_TRA:RE_RAY_SHADOW;
1615         isec.lay= -1;
1616
1617
1618         shadfac[0]= shadfac[1]= shadfac[2]= 0.0f;
1619
1620         /* bias prevents smoothed faces to appear flat */
1621         if(shi->vlr->flag & R_SMOOTH) {
1622                 bias= G.scene->world->aobias;
1623                 nrm= shi->vn;
1624         }
1625         else {
1626                 bias= 0.0f;
1627                 nrm= shi->facenor;
1628         }
1629
1630         /* prevent sky colors to be added for only shadow (shadow becomes alpha) */
1631         aocolor= R.wrld.aocolor;
1632         if(shi->mat->mode & MA_ONLYSHADOW)
1633                 aocolor= WO_AOPLAIN;
1634         
1635         vec= sphere_sampler(R.wrld.aomode, R.wrld.aosamp, shi->thread, shi->xs, shi->ys);
1636         
1637         // warning: since we use full sphere now, and dotproduct is below, we do twice as much
1638         tot= 2*R.wrld.aosamp*R.wrld.aosamp;
1639
1640         if(aocolor == WO_AOSKYTEX) {
1641                 dxyview[0]= 1.0f/(float)R.wrld.aosamp;
1642                 dxyview[1]= 1.0f/(float)R.wrld.aosamp;
1643                 dxyview[2]= 0.0f;
1644         }
1645         
1646         while(tot--) {
1647                 
1648                 if ((vec[0]*nrm[0] + vec[1]*nrm[1] + vec[2]*nrm[2]) > bias) {
1649                         /* only ao samples for mask */
1650                         if(R.r.mode & R_OSA) {
1651                                 j++;
1652                                 if(j==R.osa) j= 0;
1653                                 if(!(shi->mask & (1<<j))) {
1654                                         vec+=3;
1655                                         continue;
1656                                 }
1657                         }
1658                         
1659                         actual++;
1660                         
1661                         /* always set start/end, RE_ray_tree_intersect clips it */
1662                         VECCOPY(isec.start, shi->co);
1663                         isec.end[0] = shi->co[0] - maxdist*vec[0];
1664                         isec.end[1] = shi->co[1] - maxdist*vec[1];
1665                         isec.end[2] = shi->co[2] - maxdist*vec[2];
1666                         
1667                         /* do the trace */
1668                         if(RE_ray_tree_intersect(R.raytree, &isec)) {
1669                                 if (R.wrld.aomode & WO_AODIST) sh+= exp(-isec.labda*R.wrld.aodistfac); 
1670                                 else sh+= 1.0f;
1671                         }
1672                         else if(aocolor!=WO_AOPLAIN) {
1673                                 float skycol[4];
1674                                 float fac, view[3];
1675                                 
1676                                 view[0]= -vec[0];
1677                                 view[1]= -vec[1];
1678                                 view[2]= -vec[2];
1679                                 Normalize(view);
1680                                 
1681                                 if(aocolor==WO_AOSKYCOL) {
1682                                         fac= 0.5*(1.0f+view[0]*R.grvec[0]+ view[1]*R.grvec[1]+ view[2]*R.grvec[2]);
1683                                         shadfac[0]+= (1.0f-fac)*R.wrld.horr + fac*R.wrld.zenr;
1684                                         shadfac[1]+= (1.0f-fac)*R.wrld.horg + fac*R.wrld.zeng;
1685                                         shadfac[2]+= (1.0f-fac)*R.wrld.horb + fac*R.wrld.zenb;
1686                                 }
1687                                 else {  /* WO_AOSKYTEX */
1688                                         shadeSkyView(skycol, isec.start, view, dxyview);
1689                                         shadfac[0]+= skycol[0];
1690                                         shadfac[1]+= skycol[1];
1691                                         shadfac[2]+= skycol[2];
1692                                 }
1693                                 skyadded++;
1694                         }
1695                 }
1696                 // samples
1697                 vec+= 3;
1698         }
1699         
1700         if(actual==0) sh= 1.0f;
1701         else sh = 1.0f - sh/((float)actual);
1702         
1703         if(aocolor!=WO_AOPLAIN && skyadded) {
1704                 div= sh/((float)skyadded);
1705                 
1706                 shadfac[0]*= div;       // average color times distances/hits formula
1707                 shadfac[1]*= div;       // average color times distances/hits formula
1708                 shadfac[2]*= div;       // average color times distances/hits formula
1709         }
1710         else {
1711                 shadfac[0]= shadfac[1]= shadfac[2]= sh;
1712         }
1713 }
1714
1715 void ray_ao(ShadeInput *shi, float *shadfac)
1716 {
1717         /* Unfortunately, the unusual way that the sphere sampler calculates roughly twice as many
1718          * samples as are actually traced, and skips them based on bias and OSA settings makes it very difficult
1719          * to reuse code between these two functions. This is the easiest way I can think of to do it
1720          * --broken */
1721         if (ELEM(R.wrld.ao_samp_method, WO_AOSAMP_HAMMERSLEY, WO_AOSAMP_HALTON))
1722                 ray_ao_qmc(shi, shadfac);
1723         else if (R.wrld.ao_samp_method == WO_AOSAMP_CONSTANT)
1724                 ray_ao_spheresamp(shi, shadfac);
1725 }
1726
1727
1728 static void ray_shadow_qmc(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
1729 {
1730         QMCSampler *qsa=NULL;
1731         QMCSampler *qsa_jit=NULL;
1732         int samples=0;
1733         float samp3d[3], jit[3];
1734
1735         float fac=0.0f, vec[3];
1736         float colsq[4];
1737         float adapt_thresh = lar->adapt_thresh;
1738         int max_samples = lar->ray_totsamp;
1739         float pos[3];
1740         int do_soft=1, full_osa=0;
1741
1742         colsq[0] = colsq[1] = colsq[2] = 0.0;
1743         if(isec->mode==RE_RAY_SHADOW_TRA) {
1744                 shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 0.0f;
1745         } else
1746                 shadfac[3]= 1.0f;
1747         
1748         if (lar->ray_totsamp < 2) do_soft = 0;
1749         if ((R.r.mode & R_OSA) && (R.osa > 0) && (shi->vlr->flag & R_FULL_OSA)) full_osa = 1;
1750         
1751         if (full_osa) {
1752                 if (do_soft) max_samples  = max_samples/R.osa + 1;
1753                 else max_samples = 1;
1754         } else {
1755                 if (do_soft) max_samples = lar->ray_totsamp;
1756                 else max_samples = (R.osa > 4)?R.osa:5;
1757         }
1758         
1759         /* sampling init */
1760         if (lar->ray_samp_method==LA_SAMP_HALTON) {
1761                 qsa = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
1762                 qsa_jit = QMC_initSampler(SAMP_TYPE_HALTON, max_samples);
1763         } else if (lar->ray_samp_method==LA_SAMP_HAMMERSLEY) {
1764                 qsa = lar->qsa;
1765                 qsa_jit = QMC_initSampler(SAMP_TYPE_HAMMERSLEY, max_samples);
1766         }
1767         
1768         QMC_initPixel(qsa, shi->thread);
1769         QMC_initPixel(qsa_jit, shi->thread);
1770         
1771         VECCOPY(vec, lampco);
1772         
1773         
1774         while (samples < max_samples) {
1775                 isec->faceorig= (RayFace*)shi->vlr;
1776                 isec->oborig= RAY_OBJECT_SET(&R, shi->obi);
1777                 
1778                 /* manually jitter the start shading co-ord per sample
1779                  * based on the pre-generated OSA texture sampling offsets, 
1780                  * for anti-aliasing sharp shadow edges. */
1781                 VECCOPY(pos, shi->co);
1782                 if (shi->vlr && !full_osa) {
1783                         QMC_sampleRect(jit, qsa_jit, shi->thread, samples, 1.0, 1.0);
1784                         
1785                         pos[0] += shi->dxco[0]*jit[0] + shi->dyco[0]*jit[1];
1786                         pos[1] += shi->dxco[1]*jit[0] + shi->dyco[1]*jit[1];
1787                         pos[2] += shi->dxco[2]*jit[0] + shi->dyco[2]*jit[1];
1788                 }
1789
1790                 if (do_soft) {
1791                         /* sphere shadow source */
1792                         if (lar->type == LA_LOCAL) {
1793                                 float ru[3], rv[3], v[3], s[3];
1794                                 
1795                                 /* calc tangent plane vectors */
1796                                 v[0] = pos[0] - lampco[0];
1797                                 v[1] = pos[1] - lampco[1];
1798                                 v[2] = pos[2] - lampco[2];
1799                                 Normalize(v);
1800                                 VecOrthoBasisf(v, ru, rv);
1801                                 
1802                                 /* sampling, returns quasi-random vector in area_size disc */
1803                                 QMC_sampleDisc(samp3d, qsa, shi->thread, samples,lar->area_size);
1804
1805                                 /* distribute disc samples across the tangent plane */
1806                                 s[0] = samp3d[0]*ru[0] + samp3d[1]*rv[0];
1807                                 s[1] = samp3d[0]*ru[1] + samp3d[1]*rv[1];
1808                                 s[2] = samp3d[0]*ru[2] + samp3d[1]*rv[2];
1809                                 
1810                                 VECCOPY(samp3d, s);
1811                         }
1812                         else {
1813                                 /* sampling, returns quasi-random vector in [sizex,sizey]^2 plane */
1814                                 QMC_sampleRect(samp3d, qsa, shi->thread, samples, lar->area_size, lar->area_sizey);
1815                                                                 
1816                                 /* align samples to lamp vector */
1817                                 Mat3MulVecfl(lar->mat, samp3d);
1818                         }
1819                         isec->end[0]= vec[0]+samp3d[0];
1820                         isec->end[1]= vec[1]+samp3d[1];
1821                         isec->end[2]= vec[2]+samp3d[2];
1822                 } else {
1823                         VECCOPY(isec->end, vec);
1824                 }
1825                 VECCOPY(isec->start, pos);
1826                 
1827                 
1828                 /* trace the ray */
1829                 if(isec->mode==RE_RAY_SHADOW_TRA) {
1830                         isec->col[0]= isec->col[1]= isec->col[2]=  1.0f;
1831                         isec->col[3]= 1.0f;
1832                         
1833                         ray_trace_shadow_tra(isec, DEPTH_SHADOW_TRA, 0);
1834                         shadfac[0] += isec->col[0];
1835                         shadfac[1] += isec->col[1];
1836                         shadfac[2] += isec->col[2];
1837                         shadfac[3] += isec->col[3];
1838                         
1839                         /* for variance calc */
1840                         colsq[0] += isec->col[0]*isec->col[0];
1841                         colsq[1] += isec->col[1]*isec->col[1];
1842                         colsq[2] += isec->col[2]*isec->col[2];
1843                 }
1844                 else {
1845                         if( RE_ray_tree_intersect(R.raytree, isec) ) fac+= 1.0f;
1846                 }
1847                 
1848                 samples++;
1849                 
1850                 if ((lar->ray_samp_method == LA_SAMP_HALTON)) {
1851                 
1852                         /* adaptive sampling - consider samples below threshold as in shadow (or vice versa) and exit early */
1853                         if ((max_samples > 4) && (adapt_thresh > 0.0) && (samples > max_samples / 3)) {
1854                                 if (isec->mode==RE_RAY_SHADOW_TRA) {
1855                                         if ((shadfac[3] / samples > (1.0-adapt_thresh)) || (shadfac[3] / samples < adapt_thresh))
1856                                                 break;
1857                                         else if (adaptive_sample_variance(samples, shadfac, colsq, adapt_thresh))
1858                                                 break;
1859                                 } else {
1860                                         if ((fac / samples > (1.0-adapt_thresh)) || (fac / samples < adapt_thresh))
1861                                                 break;
1862                                 }
1863                         }
1864                 }
1865         }
1866         
1867         if(isec->mode==RE_RAY_SHADOW_TRA) {
1868                 shadfac[0] /= samples;
1869                 shadfac[1] /= samples;
1870                 shadfac[2] /= samples;
1871                 shadfac[3] /= samples;
1872         } else
1873                 shadfac[3]= 1.0f-fac/samples;
1874
1875         if (qsa_jit) QMC_freeSampler(qsa_jit);
1876         if ((qsa) && (qsa->type == SAMP_TYPE_HALTON)) QMC_freeSampler(qsa);
1877 }
1878
1879 static void ray_shadow_jitter(ShadeInput *shi, LampRen *lar, float *lampco, float *shadfac, Isect *isec)
1880 {
1881         /* area soft shadow */
1882         float *jitlamp;
1883         float fac=0.0f, div=0.0f, vec[3];
1884         int a, j= -1, mask;
1885         
1886         if(isec->mode==RE_RAY_SHADOW_TRA) {
1887                 shadfac[0]= shadfac[1]= shadfac[2]= shadfac[3]= 0.0f;
1888         }
1889         else shadfac[3]= 1.0f;
1890         
1891         fac= 0.0f;
1892         jitlamp= give_jitter_plane(lar, shi->thread, shi->xs, shi->ys);
1893
1894         a= lar->ray_totsamp;
1895         
1896         /* this correction to make sure we always take at least 1 sample */
1897         mask= shi->mask;
1898         if(a==4) mask |= (mask>>4)|(mask>>8);
1899         else if(a==9) mask |= (mask>>9);
1900         
1901         while(a--) {
1902                 
1903                 if(R.r.mode & R_OSA) {
1904                         j++;
1905                         if(j>=R.osa) j= 0;
1906                         if(!(mask & (1<<j))) {
1907                                 jitlamp+= 2;
1908                                 continue;
1909                         }
1910                 }
1911                 
1912                 isec->faceorig= (RayFace*)shi->vlr;
1913                 isec->oborig= RAY_OBJECT_SET(&R, shi->obi);
1914                 
1915                 vec[0]= jitlamp[0];
1916                 vec[1]= jitlamp[1];
1917                 vec[2]= 0.0f;
1918                 Mat3MulVecfl(lar->mat, vec);
1919                 
1920                 /* set start and end, RE_ray_tree_intersect clips it */
1921                 VECCOPY(isec->start, shi->co);
1922                 isec->end[0]= lampco[0]+vec[0];
1923                 isec->end[1]= lampco[1]+vec[1];
1924                 isec->end[2]= lampco[2]+vec[2];
1925                 
1926                 if(isec->mode==RE_RAY_SHADOW_TRA) {
1927                         /* isec.col is like shadfac, so defines amount of light (0.0 is full shadow) */
1928                         isec->col[0]= isec->col[1]= isec->col[2]=  1.0f;
1929                         isec->col[3]= 1.0f;
1930                         
1931                         ray_trace_shadow_tra(isec, DEPTH_SHADOW_TRA, 0);
1932                         shadfac[0] += isec->col[0];
1933                         shadfac[1] += isec->col[1];
1934                         shadfac[2] += isec->col[2];
1935                         shadfac[3] += isec->col[3];
1936                 }
1937                 else if( RE_ray_tree_intersect(R.raytree, isec) ) fac+= 1.0f;
1938                 
1939                 div+= 1.0f;
1940                 jitlamp+= 2;
1941         }
1942         
1943         if(isec->mode==RE_RAY_SHADOW_TRA) {
1944                 shadfac[0] /= div;
1945                 shadfac[1] /= div;
1946                 shadfac[2] /= div;
1947                 shadfac[3] /= div;
1948         }
1949         else {
1950                 // sqrt makes nice umbra effect
1951                 if(lar->ray_samp_type & LA_SAMP_UMBRA)
1952                         shadfac[3]= sqrt(1.0f-fac/div);
1953                 else
1954                         shadfac[3]= 1.0f-fac/div;
1955         }
1956 }
1957 /* extern call from shade_lamp_loop */
1958 void ray_shadow(ShadeInput *shi, LampRen *lar, float *shadfac)
1959 {
1960         Isect isec;
1961         float lampco[3], maxsize;
1962
1963         /* setup isec */
1964         if(shi->mat->mode & MA_SHADOW_TRA) isec.mode= RE_RAY_SHADOW_TRA;
1965         else isec.mode= RE_RAY_SHADOW;
1966         
1967         if(lar->mode & LA_LAYER) isec.lay= lar->lay; else isec.lay= -1;
1968
1969         /* only when not mir tracing, first hit optimm */
1970         if(shi->depth==0) {
1971                 isec.face_last= (RayFace*)lar->vlr_last[shi->thread];
1972                 isec.ob_last= RAY_OBJECT_SET(&R, lar->obi_last[shi->thread]);
1973         }
1974         else {
1975                 isec.face_last= NULL;
1976                 isec.ob_last= 0;
1977         }
1978         
1979         if(lar->type==LA_SUN || lar->type==LA_HEMI) {
1980                 maxsize= RE_ray_tree_max_size(R.raytree);
1981                 lampco[0]= shi->co[0] - maxsize*lar->vec[0];
1982                 lampco[1]= shi->co[1] - maxsize*lar->vec[1];
1983                 lampco[2]= shi->co[2] - maxsize*lar->vec[2];
1984         }
1985         else {
1986                 VECCOPY(lampco, lar->co);
1987         }
1988         
1989         if (ELEM(lar->ray_samp_method, LA_SAMP_HALTON, LA_SAMP_HAMMERSLEY)) {
1990                 
1991                 ray_shadow_qmc(shi, lar, lampco, shadfac, &isec);
1992                 
1993         } else {
1994                 if(lar->ray_totsamp<2) {
1995                         
1996                         isec.faceorig= (RayFace*)shi->vlr;
1997                         isec.oborig= RAY_OBJECT_SET(&R, shi->obi);
1998                         shadfac[3]= 1.0f; // 1.0=full light
1999                         
2000                         /* set up isec vec */
2001                         VECCOPY(isec.start, shi->co);
2002                         VECCOPY(isec.end, lampco);
2003
2004                         if(isec.mode==RE_RAY_SHADOW_TRA) {
2005                                 /* isec.col is like shadfac, so defines amount of light (0.0 is full shadow) */
2006                                 isec.col[0]= isec.col[1]= isec.col[2]=  1.0f;
2007                                 isec.col[3]= 1.0f;
2008
2009                                 ray_trace_shadow_tra(&isec, DEPTH_SHADOW_TRA, 0);
2010                                 QUATCOPY(shadfac, isec.col);
2011                         }
2012                         else if(RE_ray_tree_intersect(R.raytree, &isec)) shadfac[3]= 0.0f;
2013                 }
2014                 else {
2015                         ray_shadow_jitter(shi, lar, lampco, shadfac, &isec);
2016                 }
2017         }
2018                 
2019         /* for first hit optim, set last interesected shadow face */
2020         if(shi->depth==0) {
2021                 lar->vlr_last[shi->thread]= (VlakRen*)isec.face_last;
2022                 lar->obi_last[shi->thread]= RAY_OBJECT_GET(&R, isec.ob_last);
2023         }
2024
2025 }
2026
2027 /* only when face points away from lamp, in direction of lamp, trace ray and find first exit point */
2028 void ray_translucent(ShadeInput *shi, LampRen *lar, float *distfac, float *co)
2029 {
2030         Isect isec;
2031         float lampco[3], maxsize;
2032         
2033         /* setup isec */
2034         isec.mode= RE_RAY_SHADOW_TRA;
2035         
2036         if(lar->mode & LA_LAYER) isec.lay= lar->lay; else isec.lay= -1;
2037         
2038         if(lar->type==LA_SUN || lar->type==LA_HEMI) {
2039                 maxsize= RE_ray_tree_max_size(R.raytree);
2040                 lampco[0]= shi->co[0] - maxsize*lar->vec[0];
2041                 lampco[1]= shi->co[1] - maxsize*lar->vec[1];
2042                 lampco[2]= shi->co[2] - maxsize*lar->vec[2];
2043         }
2044         else {
2045                 VECCOPY(lampco, lar->co);
2046         }
2047         
2048         isec.faceorig= (RayFace*)shi->vlr;
2049         isec.oborig= RAY_OBJECT_SET(&R, shi->obi);
2050         
2051         /* set up isec vec */
2052         VECCOPY(isec.start, shi->co);
2053         VECCOPY(isec.end, lampco);
2054         
2055         if(RE_ray_tree_intersect(R.raytree, &isec)) {
2056                 /* we got a face */
2057                 
2058                 /* render co */
2059                 co[0]= isec.start[0]+isec.labda*(isec.vec[0]);
2060                 co[1]= isec.start[1]+isec.labda*(isec.vec[1]);
2061                 co[2]= isec.start[2]+isec.labda*(isec.vec[2]);
2062                 
2063                 *distfac= VecLength(isec.vec);
2064         }
2065         else
2066                 *distfac= 0.0f;
2067 }
2068
2069