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