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