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