ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_t.c
(Generate patch)

Comparing ray/src/common/bsdf_t.c (file contents):
Revision 3.1 by greg, Fri Feb 18 00:40:25 2011 UTC vs.
Revision 3.8 by greg, Wed Apr 27 20:05:15 2011 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines