ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_t.c
Revision: 3.10
Committed: Thu Apr 28 04:05:11 2011 UTC (13 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 3.9: +32 -17 lines
Log Message:
First tested version

File Contents

# User Rev Content
1 greg 3.2 #ifndef lint
2 greg 3.10 static const char RCSid[] = "$Id: bsdf_t.c,v 3.9 2011/04/27 23:05:51 greg Exp $";
3 greg 3.2 #endif
4 greg 3.1 /*
5     * bsdf_t.c
6     *
7     * Definitions for variable-resolution BSDF trees
8     *
9     * Created by Greg Ward on 2/2/11.
10     *
11     */
12    
13 greg 3.3 #include "rtio.h"
14 greg 3.1 #include <stdlib.h>
15 greg 3.3 #include <math.h>
16     #include <ctype.h>
17 greg 3.1 #include "ezxml.h"
18     #include "bsdf.h"
19     #include "bsdf_t.h"
20 greg 3.6 #include "hilbert.h"
21    
22     /* Callback function type for SDtraverseTre() */
23     typedef int SDtreCallback(float val, const double *cmin,
24     double csiz, void *cptr);
25    
26     /* reference width maximum (1.0) */
27 greg 3.7 static const unsigned iwbits = sizeof(unsigned)*4;
28 greg 3.6 static const unsigned iwmax = (1<<(sizeof(unsigned)*4))-1;
29 greg 3.7 /* maximum cumulative value */
30     static const unsigned cumlmax = ~0;
31 greg 3.6
32     /* Struct used for our distribution-building callback */
33     typedef struct {
34     int nic; /* number of input coordinates */
35 greg 3.7 unsigned alen; /* current array length */
36     unsigned nall; /* number of allocated entries */
37     unsigned wmin; /* minimum square size so far */
38     unsigned wmax; /* maximum square size */
39 greg 3.6 struct outdir_s {
40     unsigned hent; /* entering Hilbert index */
41     int wid; /* this square size */
42     float bsdf; /* BSDF for this square */
43     } *darr; /* output direction array */
44     } SDdistScaffold;
45 greg 3.1
46     /* Allocate a new scattering distribution node */
47     static SDNode *
48     SDnewNode(int nd, int lg)
49     {
50     SDNode *st;
51    
52     if (nd <= 0) {
53     strcpy(SDerrorDetail, "Zero dimension BSDF node request");
54     return NULL;
55     }
56     if (nd > SD_MAXDIM) {
57     sprintf(SDerrorDetail, "Illegal BSDF dimension (%d > %d)",
58     nd, SD_MAXDIM);
59     return NULL;
60     }
61     if (lg < 0) {
62     st = (SDNode *)malloc(sizeof(SDNode) +
63 greg 3.7 sizeof(st->u.t[0])*((1<<nd) - 1));
64 greg 3.1 if (st != NULL)
65 greg 3.5 memset(st->u.t, 0, sizeof(st->u.t[0])<<nd);
66 greg 3.1 } else
67     st = (SDNode *)malloc(sizeof(SDNode) +
68 greg 3.7 sizeof(st->u.v[0])*((1 << nd*lg) - 1));
69 greg 3.1
70     if (st == NULL) {
71     if (lg < 0)
72     sprintf(SDerrorDetail,
73 greg 3.6 "Cannot allocate %d branch BSDF tree", 1<<nd);
74 greg 3.1 else
75     sprintf(SDerrorDetail,
76     "Cannot allocate %d BSDF leaves", 1 << nd*lg);
77     return NULL;
78     }
79     st->ndim = nd;
80     st->log2GR = lg;
81     return st;
82     }
83    
84     /* Free an SD tree */
85     static void
86 greg 3.6 SDfreeTre(SDNode *st)
87 greg 3.1 {
88     int i;
89    
90     if (st == NULL)
91     return;
92     for (i = (st->log2GR < 0) << st->ndim; i--; )
93 greg 3.5 SDfreeTre(st->u.t[i]);
94 greg 3.1 free((void *)st);
95     }
96    
97 greg 3.6 /* Free a variable-resolution BSDF */
98     static void
99     SDFreeBTre(void *p)
100     {
101     SDTre *sdt = (SDTre *)p;
102    
103     if (sdt == NULL)
104     return;
105     SDfreeTre(sdt->st);
106     free(sdt);
107     }
108 greg 3.5
109 greg 3.7 /* Fill branch's worth of grid values from subtree */
110     static void
111     fill_grid_branch(float *dptr, const float *sptr, int nd, int shft)
112     {
113     unsigned n = 1 << (shft-1);
114    
115     if (!--nd) { /* end on the line */
116     memcpy(dptr, sptr, sizeof(*dptr)*n);
117     return;
118     }
119     while (n--) /* recurse on each slice */
120     fill_grid_branch(dptr + (n << shft*nd),
121     sptr + (n << (shft-1)*nd), nd, shft);
122     }
123    
124     /* Get pointer at appropriate offset for the given branch */
125     static float *
126     grid_branch_start(SDNode *st, int n)
127     {
128     unsigned skipsiz = 1 << st->log2GR;
129     float *vptr = st->u.v;
130     int i;
131    
132 greg 3.10 for (i = 0; i < st->ndim; skipsiz <<= st->log2GR)
133     if (1<<i++ & n)
134 greg 3.7 vptr += skipsiz >> 1;
135     return vptr;
136     }
137    
138     /* Simplify (consolidate) a tree by flattening uniform depth regions */
139     static SDNode *
140     SDsimplifyTre(SDNode *st)
141     {
142     int match, n;
143    
144     if (st == NULL) /* check for invalid tree */
145     return NULL;
146     if (st->log2GR >= 0) /* grid just returns unaltered */
147     return st;
148     match = 1; /* check if grids below match */
149     for (n = 0; n < 1<<st->ndim; n++) {
150     if ((st->u.t[n] = SDsimplifyTre(st->u.t[n])) == NULL)
151     return NULL; /* propogate error up call stack */
152     match &= (st->u.t[n]->log2GR == st->u.t[0]->log2GR);
153     }
154 greg 3.9 if (match && (match = st->u.t[0]->log2GR) >= 0) {
155     SDNode *stn = SDnewNode(st->ndim, match + 1);
156 greg 3.7 if (stn == NULL) /* out of memory? */
157     return st;
158     /* transfer values to new grid */
159     for (n = 1 << st->ndim; n--; )
160     fill_grid_branch(grid_branch_start(stn, n),
161 greg 3.9 st->u.t[n]->u.v, stn->ndim, stn->log2GR);
162 greg 3.7 SDfreeTre(st); /* free old tree */
163     st = stn; /* return new one */
164     }
165     return st;
166     }
167    
168     /* Find smallest leaf in tree */
169     static double
170     SDsmallestLeaf(const SDNode *st)
171     {
172     if (st->log2GR < 0) { /* tree branches */
173     double lmin = 1.;
174     int n;
175     for (n = 1<<st->ndim; n--; ) {
176     double lsiz = SDsmallestLeaf(st->u.t[n]);
177     if (lsiz < lmin)
178     lmin = lsiz;
179     }
180     return .5*lmin;
181     }
182     /* leaf grid width */
183     return 1. / (double)(1 << st->log2GR);
184     }
185    
186 greg 3.1 /* Add up N-dimensional hypercube array values over the given box */
187     static double
188 greg 3.7 SDiterSum(const float *va, int nd, int shft, const int *imin, const int *imax)
189 greg 3.1 {
190 greg 3.10 const unsigned skipsiz = 1 << --nd*shft;
191 greg 3.1 double sum = .0;
192     int i;
193    
194     if (skipsiz == 1)
195     for (i = *imin; i < *imax; i++)
196     sum += va[i];
197     else
198     for (i = *imin; i < *imax; i++)
199 greg 3.10 sum += SDiterSum(va + i*skipsiz, nd, shft, imin+1, imax+1);
200 greg 3.1 return sum;
201     }
202    
203     /* Average BSDF leaves over an orthotope defined by the unit hypercube */
204     static double
205 greg 3.6 SDavgTreBox(const SDNode *st, const double *bmin, const double *bmax)
206 greg 3.1 {
207     int imin[SD_MAXDIM], imax[SD_MAXDIM];
208     unsigned n;
209     int i;
210    
211     if (!st)
212     return .0;
213     /* check box limits */
214     for (i = st->ndim; i--; ) {
215     if (bmin[i] >= 1.)
216     return .0;
217     if (bmax[i] <= .0)
218     return .0;
219     if (bmin[i] >= bmax[i])
220     return .0;
221     }
222     if (st->log2GR < 0) { /* iterate on subtree */
223     double sum = .0, wsum = 1e-20;
224     double sbmin[SD_MAXDIM], sbmax[SD_MAXDIM], w;
225    
226     for (n = 1 << st->ndim; n--; ) {
227     w = 1.;
228     for (i = st->ndim; i--; ) {
229     sbmin[i] = 2.*bmin[i];
230     sbmax[i] = 2.*bmax[i];
231     if (n & 1<<i) {
232     sbmin[i] -= 1.;
233     sbmax[i] -= 1.;
234     }
235     if (sbmin[i] < .0) sbmin[i] = .0;
236     if (sbmax[i] > 1.) sbmax[i] = 1.;
237     w *= sbmax[i] - sbmin[i];
238     }
239     if (w > 1e-10) {
240 greg 3.6 sum += w * SDavgTreBox(st->u.t[n], sbmin, sbmax);
241 greg 3.1 wsum += w;
242     }
243     }
244     return sum / wsum;
245     }
246     n = 1; /* iterate over leaves */
247     for (i = st->ndim; i--; ) {
248 greg 3.7 imin[i] = (bmin[i] <= 0) ? 0
249 greg 3.1 : (int)((1 << st->log2GR)*bmin[i]);
250     imax[i] = (bmax[i] >= 1.) ? (1 << st->log2GR)
251     : (int)((1 << st->log2GR)*bmax[i] + .999999);
252     n *= imax[i] - imin[i];
253     }
254     if (!n)
255     return .0;
256    
257 greg 3.7 return SDiterSum(st->u.v, st->ndim, st->log2GR, imin, imax) / (double)n;
258 greg 3.1 }
259    
260 greg 3.6 /* Recursive call for SDtraverseTre() */
261     static int
262     SDdotravTre(const SDNode *st, const double *pos, int cmask,
263     SDtreCallback *cf, void *cptr,
264     const double *cmin, double csiz)
265     {
266     int rv, rval = 0;
267     double bmin[SD_MAXDIM];
268     int i, n;
269     /* in branches? */
270     if (st->log2GR < 0) {
271     unsigned skipmask = 0;
272    
273     csiz *= .5;
274     for (i = st->ndim; i--; )
275     if (1<<i & cmask)
276     if (pos[i] < cmin[i] + csiz)
277     for (n = 1 << st->ndim; n--; )
278     if (n & 1<<i)
279     skipmask |= 1<<n;
280     else
281     for (n = 1 << st->ndim; n--; )
282     if (!(n & 1<<i))
283     skipmask |= 1<<n;
284     for (n = 1 << st->ndim; n--; ) {
285     if (1<<n & skipmask)
286     continue;
287     for (i = st->ndim; i--; )
288     if (1<<i & n)
289     bmin[i] = cmin[i] + csiz;
290     else
291     bmin[i] = cmin[i];
292    
293     rval += rv = SDdotravTre(st->u.t[n], pos, cmask,
294     cf, cptr, bmin, csiz);
295     if (rv < 0)
296     return rv;
297     }
298     } else { /* else traverse leaves */
299     int clim[SD_MAXDIM][2];
300     int cpos[SD_MAXDIM];
301    
302     if (st->log2GR == 0) /* short cut */
303     return (*cf)(st->u.v[0], cmin, csiz, cptr);
304    
305     csiz /= (double)(1 << st->log2GR);
306     /* assign coord. ranges */
307     for (i = st->ndim; i--; )
308     if (1<<i & cmask) {
309     clim[i][0] = (pos[i] - cmin[i])/csiz;
310     /* check overflow from f.p. error */
311     clim[i][0] -= clim[i][0] >> st->log2GR;
312     clim[i][1] = clim[i][0] + 1;
313     } else {
314     clim[i][0] = 0;
315     clim[i][1] = 1 << st->log2GR;
316     }
317     /* fill in unused dimensions */
318     for (i = SD_MAXDIM; i-- > st->ndim; ) {
319     clim[i][0] = 0; clim[i][1] = 1;
320     }
321     #if (SD_MAXDIM == 4)
322     bmin[0] = cmin[0] + csiz*clim[0][0];
323     for (cpos[0] = clim[0][0]; cpos[0] < clim[0][1]; cpos[0]++) {
324     bmin[1] = cmin[1] + csiz*clim[1][0];
325     for (cpos[1] = clim[1][0]; cpos[1] < clim[1][1]; cpos[1]++) {
326     bmin[2] = cmin[2] + csiz*clim[2][0];
327     for (cpos[2] = clim[2][0]; cpos[2] < clim[2][1]; cpos[2]++) {
328     bmin[3] = cmin[3] + csiz*(cpos[3] = clim[3][0]);
329     n = cpos[0];
330     for (i = 1; i < st->ndim; i++)
331     n = (n << st->log2GR) + cpos[i];
332     for ( ; cpos[3] < clim[3][1]; cpos[3]++) {
333     rval += rv = (*cf)(st->u.v[n++], bmin, csiz, cptr);
334     if (rv < 0)
335     return rv;
336     bmin[3] += csiz;
337     }
338     bmin[2] += csiz;
339     }
340     bmin[1] += csiz;
341     }
342     bmin[0] += csiz;
343     }
344     #else
345     _!_ "broken code segment!"
346     #endif
347     }
348     return rval;
349     }
350    
351     /* Traverse a tree, visiting nodes in a slice that fits partial position */
352     static int
353     SDtraverseTre(const SDNode *st, const double *pos, int cmask,
354     SDtreCallback *cf, void *cptr)
355     {
356     static double czero[SD_MAXDIM];
357     int i;
358     /* check arguments */
359     if ((st == NULL) | (cf == NULL))
360     return -1;
361     for (i = st->ndim; i--; )
362     if (1<<i & cmask && (pos[i] < 0) | (pos[i] >= 1.))
363     return -1;
364    
365     return SDdotravTre(st, pos, cmask, cf, cptr, czero, 1.);
366     }
367 greg 3.5
368     /* Look up tree value at the given grid position */
369     static float
370 greg 3.6 SDlookupTre(const SDNode *st, const double *pos, double *hcube)
371 greg 3.5 {
372     double spos[SD_MAXDIM];
373     int i, n, t;
374 greg 3.6 /* initialize voxel return */
375     if (hcube) {
376     hcube[i = st->ndim] = 1.;
377     while (i--)
378     hcube[i] = .0;
379     }
380 greg 3.5 /* climb the tree */
381     while (st->log2GR < 0) {
382     n = 0; /* move to appropriate branch */
383 greg 3.6 if (hcube) hcube[st->ndim] *= .5;
384 greg 3.5 for (i = st->ndim; i--; ) {
385     spos[i] = 2.*pos[i];
386     t = (spos[i] >= 1.);
387     n |= t<<i;
388     spos[i] -= (double)t;
389 greg 3.6 if (hcube) hcube[i] += (double)t * hcube[st->ndim];
390 greg 3.5 }
391     st = st->u.t[n]; /* avoids tail recursion */
392     pos = spos;
393     }
394 greg 3.6 if (st->log2GR == 0) /* short cut */
395     return st->u.v[0];
396 greg 3.5 n = t = 0; /* find grid array index */
397     for (i = st->ndim; i--; ) {
398     n += (int)((1<<st->log2GR)*pos[i]) << t;
399     t += st->log2GR;
400     }
401 greg 3.6 if (hcube) { /* compute final hypercube */
402     hcube[st->ndim] /= (double)(1<<st->log2GR);
403     for (i = st->ndim; i--; )
404     hcube[i] += floor((1<<st->log2GR)*pos[i])*hcube[st->ndim];
405     }
406     return st->u.v[n]; /* no interpolation */
407     }
408    
409     /* Query BSDF value and sample hypercube for the given vectors */
410     static float
411     SDqueryTre(const SDTre *sdt, const FVECT outVec, const FVECT inVec, double *hc)
412     {
413     static const FVECT zvec = {.0, .0, 1.};
414     FVECT rOutVec;
415     double gridPos[4];
416 greg 3.7
417     switch (sdt->sidef) { /* whose side are you on? */
418     case SD_UFRONT:
419     if ((outVec[2] < 0) | (inVec[2] < 0))
420     return -1.;
421     break;
422     case SD_UBACK:
423     if ((outVec[2] > 0) | (inVec[2] > 0))
424     return -1.;
425     break;
426     case SD_XMIT:
427     if ((outVec[2] > 0) == (inVec[2] > 0))
428     return -1.;
429     break;
430     default:
431 greg 3.6 return -1.;
432 greg 3.7 }
433 greg 3.6 /* convert vector coordinates */
434     if (sdt->st->ndim == 3) {
435     spinvector(rOutVec, outVec, zvec, -atan2(inVec[1],inVec[0]));
436     gridPos[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
437     SDdisk2square(gridPos+1, rOutVec[0], rOutVec[1]);
438     } else if (sdt->st->ndim == 4) {
439     SDdisk2square(gridPos, -inVec[0], -inVec[1]);
440     SDdisk2square(gridPos+2, outVec[0], outVec[1]);
441     } else
442     return -1.; /* should be internal error */
443    
444     return SDlookupTre(sdt->st, gridPos, hc);
445 greg 3.5 }
446    
447     /* Compute non-diffuse component for variable-resolution BSDF */
448     static int
449     SDgetTreBSDF(float coef[SDmaxCh], const FVECT outVec,
450 greg 3.6 const FVECT inVec, SDComponent *sdc)
451 greg 3.5 {
452 greg 3.6 /* check arguments */
453     if ((coef == NULL) | (outVec == NULL) | (inVec == NULL) | (sdc == NULL)
454     || sdc->dist == NULL)
455     return 0;
456 greg 3.5 /* get nearest BSDF value */
457 greg 3.6 coef[0] = SDqueryTre((SDTre *)sdc->dist, outVec, inVec, NULL);
458     return (coef[0] >= 0); /* monochromatic for now */
459     }
460    
461     /* Callback to build cumulative distribution using SDtraverseTre() */
462     static int
463     build_scaffold(float val, const double *cmin, double csiz, void *cptr)
464     {
465     SDdistScaffold *sp = (SDdistScaffold *)cptr;
466     int wid = csiz*(double)iwmax + .5;
467     bitmask_t bmin[2], bmax[2];
468    
469     cmin += sp->nic; /* skip to output coords */
470     if (wid < sp->wmin) /* new minimum width? */
471     sp->wmin = wid;
472     if (wid > sp->wmax) /* new maximum? */
473     sp->wmax = wid;
474     if (sp->alen >= sp->nall) { /* need more space? */
475     struct outdir_s *ndarr;
476     sp->nall += 8192;
477     ndarr = (struct outdir_s *)realloc(sp->darr,
478     sizeof(struct outdir_s)*sp->nall);
479     if (ndarr == NULL)
480     return -1; /* abort build */
481     sp->darr = ndarr;
482     }
483     /* find Hilbert entry index */
484     bmin[0] = cmin[0]*(double)iwmax + .5;
485     bmin[1] = cmin[1]*(double)iwmax + .5;
486 greg 3.10 bmax[0] = bmin[0] + wid-1;
487     bmax[1] = bmin[1] + wid-1;
488 greg 3.7 hilbert_box_vtx(2, sizeof(bitmask_t), iwbits, 1, bmin, bmax);
489     sp->darr[sp->alen].hent = hilbert_c2i(2, iwbits, bmin);
490 greg 3.6 sp->darr[sp->alen].wid = wid;
491     sp->darr[sp->alen].bsdf = val;
492     sp->alen++; /* on to the next entry */
493     return 0;
494     }
495    
496     /* Scaffold comparison function for qsort -- ascending Hilbert index */
497     static int
498     sscmp(const void *p1, const void *p2)
499     {
500 greg 3.10 unsigned h1 = (*(const struct outdir_s *)p1).hent;
501     unsigned h2 = (*(const struct outdir_s *)p2).hent;
502    
503     if (h1 > h2)
504     return 1;
505     if (h1 < h2)
506     return -1;
507     return 0;
508     /*
509 greg 3.6 return (int)((*(const struct outdir_s *)p1).hent -
510     (*(const struct outdir_s *)p2).hent);
511 greg 3.10 */
512 greg 3.6 }
513    
514     /* Create a new cumulative distribution for the given input direction */
515     static SDTreCDst *
516     make_cdist(const SDTre *sdt, const double *pos)
517     {
518     SDdistScaffold myScaffold;
519     SDTreCDst *cd;
520     struct outdir_s *sp;
521     double scale, cursum;
522     int i;
523     /* initialize scaffold */
524     myScaffold.wmin = iwmax;
525     myScaffold.wmax = 0;
526     myScaffold.nic = sdt->st->ndim - 2;
527     myScaffold.alen = 0;
528     myScaffold.nall = 8192;
529     myScaffold.darr = (struct outdir_s *)malloc(sizeof(struct outdir_s) *
530     myScaffold.nall);
531     if (myScaffold.darr == NULL)
532     return NULL;
533     /* grow the distribution */
534     if (SDtraverseTre(sdt->st, pos, (1<<myScaffold.nic)-1,
535     &build_scaffold, &myScaffold) < 0) {
536     free(myScaffold.darr);
537     return NULL;
538     }
539     /* allocate result holder */
540     cd = (SDTreCDst *)malloc(sizeof(SDTreCDst) +
541     sizeof(cd->carr[0])*myScaffold.alen);
542     if (cd == NULL) {
543     free(myScaffold.darr);
544     return NULL;
545     }
546     /* sort the distribution */
547     qsort(myScaffold.darr, cd->calen = myScaffold.alen,
548     sizeof(struct outdir_s), &sscmp);
549    
550     /* record input range */
551 greg 3.7 scale = myScaffold.wmin / (double)iwmax;
552 greg 3.6 for (i = myScaffold.nic; i--; ) {
553 greg 3.7 cd->clim[i][0] = floor(pos[i]/scale) * scale;
554 greg 3.6 cd->clim[i][1] = cd->clim[i][0] + scale;
555     }
556     cd->max_psa = myScaffold.wmax / (double)iwmax;
557     cd->max_psa *= cd->max_psa * M_PI;
558 greg 3.7 cd->sidef = sdt->sidef;
559 greg 3.6 cd->cTotal = 1e-20; /* compute directional total */
560     sp = myScaffold.darr;
561     for (i = myScaffold.alen; i--; sp++)
562     cd->cTotal += sp->bsdf * (double)sp->wid * sp->wid;
563     cursum = .0; /* go back and get cumulative values */
564     scale = (double)cumlmax / cd->cTotal;
565     sp = myScaffold.darr;
566     for (i = 0; i < cd->calen; i++, sp++) {
567 greg 3.7 cd->carr[i].hndx = sp->hent;
568 greg 3.6 cd->carr[i].cuml = scale*cursum + .5;
569     cursum += sp->bsdf * (double)sp->wid * sp->wid;
570     }
571     cd->carr[i].hndx = ~0; /* make final entry */
572     cd->carr[i].cuml = cumlmax;
573     cd->cTotal *= M_PI/(double)iwmax/iwmax;
574     /* all done, clean up and return */
575     free(myScaffold.darr);
576     return cd;
577     }
578    
579     /* Find or allocate a cumulative distribution for the given incoming vector */
580     const SDCDst *
581     SDgetTreCDist(const FVECT inVec, SDComponent *sdc)
582     {
583     const SDTre *sdt;
584     double inCoord[2];
585     int vflags;
586     int i;
587     SDTreCDst *cd, *cdlast;
588     /* check arguments */
589     if ((inVec == NULL) | (sdc == NULL) ||
590     (sdt = (SDTre *)sdc->dist) == NULL)
591     return NULL;
592     if (sdt->st->ndim == 3) /* isotropic BSDF? */
593     inCoord[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
594     else if (sdt->st->ndim == 4)
595     SDdisk2square(inCoord, -inVec[0], -inVec[1]);
596     else
597     return NULL; /* should be internal error */
598     cdlast = NULL; /* check for direction in cache list */
599     for (cd = (SDTreCDst *)sdc->cdList; cd != NULL;
600     cdlast = cd, cd = (SDTreCDst *)cd->next) {
601     for (i = sdt->st->ndim - 2; i--; )
602     if ((cd->clim[i][0] > inCoord[i]) |
603     (inCoord[i] >= cd->clim[i][1]))
604     break;
605     if (i < 0)
606     break; /* means we have a match */
607     }
608     if (cd == NULL) /* need to create new entry? */
609     cdlast = cd = make_cdist(sdt, inCoord);
610     if (cdlast != NULL) { /* move entry to head of cache list */
611     cdlast->next = cd->next;
612     cd->next = sdc->cdList;
613     sdc->cdList = (SDCDst *)cd;
614     }
615     return (SDCDst *)cd; /* ready to go */
616     }
617    
618     /* Query solid angle for vector(s) */
619     static SDError
620     SDqueryTreProjSA(double *psa, const FVECT v1, const RREAL *v2,
621     int qflags, SDComponent *sdc)
622     {
623     double myPSA[2];
624     /* check arguments */
625     if ((psa == NULL) | (v1 == NULL) | (sdc == NULL) ||
626     sdc->dist == NULL)
627     return SDEargument;
628     /* get projected solid angle(s) */
629     if (v2 != NULL) {
630     const SDTre *sdt = (SDTre *)sdc->dist;
631     double hcube[SD_MAXDIM];
632     if (SDqueryTre(sdt, v1, v2, hcube) < 0) {
633 greg 3.7 strcpy(SDerrorDetail, "Bad call to SDqueryTreProjSA");
634     return SDEinternal;
635 greg 3.6 }
636     myPSA[0] = hcube[sdt->st->ndim];
637     myPSA[1] = myPSA[0] *= myPSA[0] * M_PI;
638     } else {
639     const SDTreCDst *cd = (const SDTreCDst *)SDgetTreCDist(v1, sdc);
640     if (cd == NULL)
641     return SDEmemory;
642     myPSA[0] = M_PI * (cd->clim[0][1] - cd->clim[0][0]) *
643     (cd->clim[1][1] - cd->clim[1][0]);
644     myPSA[1] = cd->max_psa;
645     }
646     switch (qflags) { /* record based on flag settings */
647     case SDqueryVal:
648     *psa = myPSA[0];
649     break;
650     case SDqueryMax:
651     if (myPSA[1] > *psa)
652     *psa = myPSA[1];
653     break;
654     case SDqueryMin+SDqueryMax:
655     if (myPSA[1] > psa[1])
656     psa[1] = myPSA[1];
657     /* fall through */
658     case SDqueryMin:
659     if (myPSA[0] < psa[0])
660     psa[0] = myPSA[0];
661     break;
662     }
663     return SDEnone;
664     }
665    
666     /* Sample cumulative distribution */
667     static SDError
668     SDsampTreCDist(FVECT ioVec, double randX, const SDCDst *cdp)
669     {
670     const unsigned nBitsC = 4*sizeof(bitmask_t);
671     const unsigned nExtraBits = 8*(sizeof(bitmask_t)-sizeof(unsigned));
672     const SDTreCDst *cd = (const SDTreCDst *)cdp;
673 greg 3.7 const unsigned target = randX*cumlmax;
674 greg 3.6 bitmask_t hndx, hcoord[2];
675     double gpos[3];
676     int i, iupper, ilower;
677     /* check arguments */
678     if ((ioVec == NULL) | (cd == NULL))
679     return SDEargument;
680 greg 3.7 if (ioVec[2] > 0) {
681     if (!(cd->sidef & SD_UFRONT))
682     return SDEargument;
683     } else if (!(cd->sidef & SD_UBACK))
684     return SDEargument;
685 greg 3.6 /* binary search to find position */
686     ilower = 0; iupper = cd->calen;
687     while ((i = (iupper + ilower) >> 1) != ilower)
688     if ((long)target >= (long)cd->carr[i].cuml)
689     ilower = i;
690     else
691     iupper = i;
692     /* localize random position */
693 greg 3.7 randX = (randX*cumlmax - cd->carr[ilower].cuml) /
694 greg 3.6 (double)(cd->carr[iupper].cuml - cd->carr[ilower].cuml);
695     /* index in longer Hilbert curve */
696     hndx = (randX*cd->carr[iupper].hndx + (1.-randX)*cd->carr[ilower].hndx)
697     * (double)((bitmask_t)1 << nExtraBits);
698     /* convert Hilbert index to vector */
699     hilbert_i2c(2, nBitsC, hndx, hcoord);
700     for (i = 2; i--; )
701     gpos[i] = ((double)hcoord[i] + rand()*(1./(RAND_MAX+.5))) /
702     (double)((bitmask_t)1 << nBitsC);
703     SDsquare2disk(gpos, gpos[0], gpos[1]);
704 greg 3.7 /* compute Z-coordinate */
705 greg 3.6 gpos[2] = 1. - gpos[0]*gpos[0] - gpos[1]*gpos[1];
706     if (gpos[2] > 0) /* paranoia, I hope */
707     gpos[2] = sqrt(gpos[2]);
708 greg 3.7 /* emit from back? */
709     if (ioVec[2] > 0 ^ cd->sidef != SD_XMIT)
710 greg 3.6 gpos[2] = -gpos[2];
711     VCOPY(ioVec, gpos);
712     return SDEnone;
713 greg 3.5 }
714    
715 greg 3.7 /* Advance pointer to the next non-white character in the string (or nul) */
716     static int
717     next_token(char **spp)
718     {
719     while (isspace(**spp))
720     ++*spp;
721     return **spp;
722     }
723    
724 greg 3.9 #define eat_token(spp,c) (next_token(spp)==(c) ? *(*(spp))++ : 0)
725    
726 greg 3.7 /* Count words from this point in string to '}' */
727     static int
728     count_values(char *cp)
729     {
730     int n = 0;
731    
732 greg 3.9 while (next_token(&cp) != '}' && *cp) {
733 greg 3.7 if (*cp == '{')
734     return -1;
735 greg 3.9 while (*cp && (*cp != ',') & (*cp != '}') & !isspace(*cp))
736 greg 3.7 ++cp;
737     ++n;
738 greg 3.9 eat_token(&cp, ',');
739 greg 3.7 }
740     return n;
741     }
742    
743     /* Load an array of real numbers, returning total */
744     static int
745     load_values(char **spp, float *va, int n)
746     {
747     float *v = va;
748     char *svnext;
749    
750     while (n-- > 0 && (svnext = fskip(*spp)) != NULL) {
751     *v++ = atof(*spp);
752     *spp = svnext;
753 greg 3.9 eat_token(spp, ',');
754 greg 3.7 }
755     return v - va;
756     }
757    
758     /* Load BSDF tree data */
759     static SDNode *
760     load_tree_data(char **spp, int nd)
761     {
762     SDNode *st;
763     int n;
764    
765 greg 3.9 if (!eat_token(spp, '{')) {
766 greg 3.7 strcpy(SDerrorDetail, "Missing '{' in tensor tree");
767     return NULL;
768     }
769     if (next_token(spp) == '{') { /* tree branches */
770     st = SDnewNode(nd, -1);
771     if (st == NULL)
772     return NULL;
773     for (n = 0; n < 1<<nd; n++)
774     if ((st->u.t[n] = load_tree_data(spp, nd)) == NULL) {
775     SDfreeTre(st);
776     return NULL;
777     }
778     } else { /* else load value grid */
779     int bsiz;
780     n = count_values(*spp); /* see how big the grid is */
781     if (n <= 0) {
782     strcpy(SDerrorDetail, "Bad tensor tree data");
783     return NULL;
784     }
785     for (bsiz = 0; bsiz < 8*sizeof(size_t)-1; bsiz += nd)
786     if (1<<bsiz == n)
787     break;
788     if (bsiz >= 8*sizeof(size_t)) {
789     strcpy(SDerrorDetail, "Illegal value count in tensor tree");
790     return NULL;
791     }
792     st = SDnewNode(nd, bsiz/nd);
793     if (st == NULL)
794     return NULL;
795     if (load_values(spp, st->u.v, n) != n) {
796     strcpy(SDerrorDetail, "Real format error in tensor tree");
797     SDfreeTre(st);
798     return NULL;
799     }
800     }
801 greg 3.9 if (!eat_token(spp, '}')) {
802 greg 3.7 strcpy(SDerrorDetail, "Missing '}' in tensor tree");
803     SDfreeTre(st);
804     return NULL;
805     }
806 greg 3.9 eat_token(spp, ',');
807 greg 3.7 return st;
808     }
809    
810     /* Compute min. proj. solid angle and max. direct hemispherical scattering */
811     static SDError
812     get_extrema(SDSpectralDF *df)
813     {
814     SDNode *st = (*(SDTre *)df->comp[0].dist).st;
815     double stepWidth, dhemi, bmin[4], bmax[4];
816    
817     stepWidth = SDsmallestLeaf(st);
818     df->minProjSA = M_PI*stepWidth*stepWidth;
819     if (stepWidth < .03125)
820     stepWidth = .03125; /* 1/32 resolution good enough */
821     df->maxHemi = .0;
822     if (st->ndim == 3) { /* isotropic BSDF */
823     bmin[1] = bmin[2] = .0;
824     bmax[1] = bmax[2] = 1.;
825     for (bmin[0] = .0; bmin[0] < .5-FTINY; bmin[0] += stepWidth) {
826     bmax[0] = bmin[0] + stepWidth;
827     dhemi = SDavgTreBox(st, bmin, bmax);
828     if (dhemi > df->maxHemi)
829     df->maxHemi = dhemi;
830     }
831     } else if (st->ndim == 4) { /* anisotropic BSDF */
832     bmin[2] = bmin[3] = .0;
833     bmax[2] = bmax[3] = 1.;
834     for (bmin[0] = .0; bmin[0] < 1.-FTINY; bmin[0] += stepWidth) {
835     bmax[0] = bmin[0] + stepWidth;
836     for (bmin[1] = .0; bmin[1] < 1.-FTINY; bmin[1] += stepWidth) {
837     bmax[1] = bmin[1] + stepWidth;
838     dhemi = SDavgTreBox(st, bmin, bmax);
839     if (dhemi > df->maxHemi)
840     df->maxHemi = dhemi;
841     }
842     }
843     } else
844     return SDEinternal;
845     /* correct hemispherical value */
846     df->maxHemi *= M_PI;
847     return SDEnone;
848     }
849    
850     /* Load BSDF distribution for this wavelength */
851     static SDError
852     load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
853     {
854     SDSpectralDF *df;
855     SDTre *sdt;
856     char *sdata;
857     int i;
858     /* allocate BSDF component */
859     sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
860     if (!sdata)
861     return SDEnone;
862     /*
863     * Remember that front and back are reversed from WINDOW 6 orientations
864     */
865     if (!strcasecmp(sdata, "Transmission")) {
866     if (sd->tf != NULL)
867     SDfreeSpectralDF(sd->tf);
868     if ((sd->tf = SDnewSpectralDF(1)) == NULL)
869     return SDEmemory;
870     df = sd->tf;
871     } else if (!strcasecmp(sdata, "Reflection Front")) {
872     if (sd->rb != NULL) /* note back-front reversal */
873     SDfreeSpectralDF(sd->rb);
874     if ((sd->rb = SDnewSpectralDF(1)) == NULL)
875     return SDEmemory;
876     df = sd->rb;
877     } else if (!strcasecmp(sdata, "Reflection Back")) {
878     if (sd->rf != NULL) /* note front-back reversal */
879     SDfreeSpectralDF(sd->rf);
880     if ((sd->rf = SDnewSpectralDF(1)) == NULL)
881     return SDEmemory;
882     df = sd->rf;
883     } else
884     return SDEnone;
885     /* XXX should also check "ScatteringDataType" for consistency? */
886     /* get angle bases */
887     sdata = ezxml_txt(ezxml_child(wdb,"AngleBasis"));
888     if (!sdata || strcasecmp(sdata, "LBNL/Shirley-Chiu")) {
889     sprintf(SDerrorDetail, "%s angle basis for BSDF '%s'",
890     !sdata ? "Missing" : "Unsupported", sd->name);
891     return !sdata ? SDEformat : SDEsupport;
892     }
893     /* allocate BSDF tree */
894     sdt = (SDTre *)malloc(sizeof(SDTre));
895     if (sdt == NULL)
896     return SDEmemory;
897     if (df == sd->rf)
898     sdt->sidef = SD_UFRONT;
899     else if (df == sd->rb)
900     sdt->sidef = SD_UBACK;
901     else
902     sdt->sidef = SD_XMIT;
903     sdt->st = NULL;
904     df->comp[0].cspec[0] = c_dfcolor; /* XXX monochrome for now */
905     df->comp[0].dist = sdt;
906     df->comp[0].func = &SDhandleTre;
907     /* read BSDF data */
908     sdata = ezxml_txt(ezxml_child(wdb, "ScatteringData"));
909     if (!sdata || !next_token(&sdata)) {
910     sprintf(SDerrorDetail, "Missing BSDF ScatteringData in '%s'",
911     sd->name);
912     return SDEformat;
913     }
914     sdt->st = load_tree_data(&sdata, ndim);
915     if (sdt->st == NULL)
916     return SDEformat;
917     if (next_token(&sdata)) { /* check for unconsumed characters */
918     sprintf(SDerrorDetail,
919     "Extra characters at end of ScatteringData in '%s'",
920     sd->name);
921     return SDEformat;
922     }
923     /* flatten branches where possible */
924     sdt->st = SDsimplifyTre(sdt->st);
925     if (sdt->st == NULL)
926     return SDEinternal;
927     return get_extrema(df); /* compute global quantities */
928     }
929    
930     /* Find minimum value in tree */
931     static float
932     SDgetTreMin(const SDNode *st)
933     {
934 greg 3.10 float vmin = FHUGE;
935 greg 3.7 int n;
936    
937     if (st->log2GR < 0) {
938     for (n = 1<<st->ndim; n--; ) {
939     float v = SDgetTreMin(st->u.t[n]);
940     if (v < vmin)
941     vmin = v;
942     }
943     } else {
944     for (n = 1<<(st->ndim*st->log2GR); n--; )
945     if (st->u.v[n] < vmin)
946     vmin = st->u.v[n];
947     }
948     return vmin;
949     }
950    
951     /* Subtract the given value from all tree nodes */
952     static void
953     SDsubtractTreVal(SDNode *st, float val)
954     {
955     int n;
956    
957     if (st->log2GR < 0) {
958     for (n = 1<<st->ndim; n--; )
959     SDsubtractTreVal(st->u.t[n], val);
960     } else {
961     for (n = 1<<(st->ndim*st->log2GR); n--; )
962     st->u.v[n] -= val;
963     }
964     }
965    
966     /* Subtract minimum value from BSDF */
967     static double
968     subtract_min(SDNode *st)
969     {
970     float vmin;
971     /* be sure to skip unused portion */
972 greg 3.10 if (st->ndim == 3) {
973     int n;
974 greg 3.7 vmin = 1./M_PI;
975 greg 3.10 if (st->log2GR < 0) {
976     for (n = 0; n < 4; n++) {
977     float v = SDgetTreMin(st->u.t[n]);
978     if (v < vmin)
979     vmin = v;
980     }
981     } else if (st->log2GR) {
982     for (n = 1 << (3*st->log2GR - 1); n--; )
983     if (st->u.v[n] < vmin)
984     vmin = st->u.v[n];
985     } else
986     vmin = st->u.v[0];
987 greg 3.7 } else /* anisotropic covers entire tree */
988     vmin = SDgetTreMin(st);
989    
990     if (vmin <= FTINY)
991     return .0;
992    
993 greg 3.8 SDsubtractTreVal(st, vmin);
994 greg 3.7
995     return M_PI * vmin; /* return hemispherical value */
996     }
997    
998     /* Extract and separate diffuse portion of BSDF */
999     static void
1000     extract_diffuse(SDValue *dv, SDSpectralDF *df)
1001     {
1002     int n;
1003    
1004     if (df == NULL || df->ncomp <= 0) {
1005     dv->spec = c_dfcolor;
1006     dv->cieY = .0;
1007     return;
1008     }
1009     dv->spec = df->comp[0].cspec[0];
1010 greg 3.9 dv->cieY = subtract_min((*(SDTre *)df->comp[0].dist).st);
1011 greg 3.7 /* in case of multiple components */
1012     for (n = df->ncomp; --n; ) {
1013     double ymin = subtract_min((*(SDTre *)df->comp[n].dist).st);
1014     c_cmix(&dv->spec, dv->cieY, &dv->spec, ymin, &df->comp[n].cspec[0]);
1015     dv->cieY += ymin;
1016     }
1017     df->maxHemi -= dv->cieY; /* adjust maximum hemispherical */
1018     /* make sure everything is set */
1019     c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
1020     }
1021    
1022 greg 3.1 /* Load a variable-resolution BSDF tree from an open XML file */
1023     SDError
1024 greg 3.4 SDloadTre(SDData *sd, ezxml_t wtl)
1025 greg 3.1 {
1026 greg 3.7 SDError ec;
1027     ezxml_t wld, wdb;
1028     int rank;
1029     char *txt;
1030     /* basic checks and tensor rank */
1031     txt = ezxml_txt(ezxml_child(ezxml_child(wtl,
1032     "DataDefinition"), "IncidentDataStructure"));
1033     if (txt == NULL || !*txt) {
1034     sprintf(SDerrorDetail,
1035     "BSDF \"%s\": missing IncidentDataStructure",
1036     sd->name);
1037     return SDEformat;
1038     }
1039     if (!strcasecmp(txt, "TensorTree3"))
1040     rank = 3;
1041     else if (!strcasecmp(txt, "TensorTree4"))
1042     rank = 4;
1043     else {
1044     sprintf(SDerrorDetail,
1045     "BSDF \"%s\": unsupported IncidentDataStructure",
1046     sd->name);
1047     return SDEsupport;
1048     }
1049     /* load BSDF components */
1050     for (wld = ezxml_child(wtl, "WavelengthData");
1051     wld != NULL; wld = wld->next) {
1052     if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1053     "Visible"))
1054     continue; /* just visible for now */
1055     for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1056     wdb != NULL; wdb = wdb->next)
1057     if ((ec = load_bsdf_data(sd, wdb, rank)) != SDEnone)
1058     return ec;
1059     }
1060     /* separate diffuse components */
1061     extract_diffuse(&sd->rLambFront, sd->rf);
1062     extract_diffuse(&sd->rLambBack, sd->rb);
1063     extract_diffuse(&sd->tLamb, sd->tf);
1064     /* return success */
1065     return SDEnone;
1066 greg 3.1 }
1067    
1068     /* Variable resolution BSDF methods */
1069 greg 3.5 SDFunc SDhandleTre = {
1070     &SDgetTreBSDF,
1071 greg 3.6 &SDqueryTreProjSA,
1072     &SDgetTreCDist,
1073     &SDsampTreCDist,
1074     &SDFreeBTre,
1075 greg 3.1 };