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.4 by greg, Sat Feb 19 01:48:59 2011 UTC vs.
Revision 3.31 by greg, Thu Aug 8 05:26:56 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines