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