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.13 by greg, Wed Jun 1 00:29:40 2011 UTC vs.
Revision 3.48 by greg, Thu May 14 19:20:13 2020 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 20 | Line 21 | static const char RCSid[] = "$Id$";
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);
25 <
24 > typedef int     SDtreCallback(float val, const double *cmin, double csiz,
25 >                                                void *cptr);
26                                          /* reference width maximum (1.0) */
27   static const unsigned   iwbits = sizeof(unsigned)*4;
28 < static const unsigned   iwmax = (1<<(sizeof(unsigned)*4))-1;
28 > static const unsigned   iwmax = 1<<(sizeof(unsigned)*4);
29                                          /* maximum cumulative value */
30   static const unsigned   cumlmax = ~0;
31 +                                        /* constant z-vector */
32 + static const FVECT      zvec = {.0, .0, 1.};
33 +                                        /* quantization value */
34 + static double           quantum = 1./256.;
35 +                                        /* our RGB primaries */
36 + static C_COLOR          tt_RGB_prim[3];
37 + static float            tt_RGB_coef[3];
38  
39 + static const double     czero[SD_MAXDIM];
40 +
41 + enum {tt_Y, tt_u, tt_v};                /* tree components (tt_Y==0) */
42 +
43   /* Struct used for our distribution-building callback */
44   typedef struct {
45 <        int             nic;            /* number of input coordinates */
45 >        short           nic;            /* number of input coordinates */
46 >        short           rev;            /* reversing query */
47          unsigned        alen;           /* current array length */
48          unsigned        nall;           /* number of allocated entries */
49          unsigned        wmin;           /* minimum square size so far */
# Line 91 | Line 103 | SDfreeTre(SDNode *st)
103                  return;
104          for (n = (st->log2GR < 0) << st->ndim; n--; )
105                  SDfreeTre(st->u.t[n]);
106 <        free((void *)st);
106 >        free(st);
107   }
108  
109   /* Free a variable-resolution BSDF */
# Line 102 | Line 114 | SDFreeBTre(void *p)
114  
115          if (sdt == NULL)
116                  return;
117 <        SDfreeTre(sdt->st);
117 >        SDfreeTre(sdt->stc[tt_Y]);
118 >        SDfreeTre(sdt->stc[tt_u]);
119 >        SDfreeTre(sdt->stc[tt_v]);
120          free(sdt);
121   }
122  
# Line 125 | Line 139 | fill_grid_branch(float *dptr, const float *sptr, int n
139   static float *
140   grid_branch_start(SDNode *st, int n)
141   {
142 <        unsigned        skipsiz = 1 << st->log2GR;
142 >        unsigned        skipsiz = 1 << (st->log2GR - 1);
143          float           *vptr = st->u.v;
144          int             i;
145  
146 <        for (i = 0; i < st->ndim; skipsiz <<= st->log2GR)
147 <                if (1<<i++ & n)
148 <                        vptr += skipsiz >> 1;
146 >        for (i = st->ndim; i--; skipsiz <<= st->log2GR)
147 >                if (1<<i & n)
148 >                        vptr += skipsiz;
149          return vptr;
150   }
151  
# Line 165 | Line 179 | SDsimplifyTre(SDNode *st)
179          return st;
180   }
181  
182 + /* Assign the given voxel in tree (produces no grid nodes) */
183 + static SDNode *
184 + SDsetVoxel(SDNode *sroot, int nd, const double *tmin, const double tsiz, float val)
185 + {
186 +        double  ctrk[SD_MAXDIM];
187 +        double  csiz = 1.;
188 +        SDNode  *st;
189 +        int     i, n;
190 +                                        /* check arguments */
191 +        for (i = nd; i-- > 0; )
192 +                if ((tmin[i] < .0) | (tmin[i] >= 1.-FTINY))
193 +                        break;
194 +        if ((i >= 0) | (nd <= 0) | (tsiz <= FTINY) | (tsiz > 1.+FTINY) |
195 +                        (sroot != NULL && sroot->ndim != nd)) {
196 +                SDfreeTre(sroot);
197 +                return NULL;
198 +        }
199 +        if (tsiz >= 1.-FTINY) {         /* special case when tree is a leaf */
200 +                SDfreeTre(sroot);
201 +                if ((sroot = SDnewNode(nd, 0)) != NULL)
202 +                        sroot->u.v[0] = val;
203 +                return sroot;
204 +        }
205 +                                        /* make sure we have branching root */
206 +        if (sroot != NULL && sroot->log2GR >= 0) {
207 +                SDfreeTre(sroot); sroot = NULL;
208 +        }
209 +        if (sroot == NULL && (sroot = SDnewNode(nd, -1)) == NULL)
210 +                return NULL;
211 +        st = sroot;                     /* climb/grow tree */
212 +        memset(ctrk, 0, sizeof(ctrk));
213 +        for ( ; ; ) {
214 +                csiz *= .5;             /* find appropriate branch */
215 +                n = 0;
216 +                for (i = nd; i--; )
217 +                        if (ctrk[i]+csiz <= tmin[i]+FTINY) {
218 +                                ctrk[i] += csiz;
219 +                                n |= 1 << i;
220 +                        }
221 +                                        /* reached desired voxel? */
222 +                if (csiz <= tsiz+FTINY) {
223 +                        SDfreeTre(st->u.t[n]);
224 +                        st = st->u.t[n] = SDnewNode(nd, 0);
225 +                        break;
226 +                }
227 +                                        /* else grow tree as needed */
228 +                if (st->u.t[n] != NULL && st->u.t[n]->log2GR >= 0) {
229 +                        SDfreeTre(st->u.t[n]); st->u.t[n] = NULL;
230 +                }
231 +                if (st->u.t[n] == NULL)
232 +                        st->u.t[n] = SDnewNode(nd, -1);
233 +                if ((st = st->u.t[n]) == NULL)
234 +                        break;
235 +        }
236 +        if (st == NULL) {
237 +                SDfreeTre(sroot);
238 +                return NULL;
239 +        }
240 +        st->u.v[0] = val;               /* assign leaf and return root */
241 +        return sroot;
242 + }
243 +
244   /* Find smallest leaf in tree */
245   static double
246   SDsmallestLeaf(const SDNode *st)
# Line 190 | Line 266 | SDiterSum(const float *va, int nd, int shft, const int
266          const unsigned  skipsiz = 1 << --nd*shft;
267          double          sum = .0;
268          int             i;
269 <        
269 >
270 >        va += *imin * skipsiz;
271 >
272          if (skipsiz == 1)
273                  for (i = *imin; i < *imax; i++)
274 <                        sum += va[i];
274 >                        sum += *va++;
275          else
276 <                for (i = *imin; i < *imax; i++)
277 <                        sum += SDiterSum(va + i*skipsiz, nd, shft, imin+1, imax+1);
276 >                for (i = *imin; i < *imax; i++, va += skipsiz)
277 >                        sum += SDiterSum(va, nd, shft, imin+1, imax+1);
278          return sum;
279   }
280  
# Line 204 | Line 282 | SDiterSum(const float *va, int nd, int shft, const int
282   static double
283   SDavgTreBox(const SDNode *st, const double *bmin, const double *bmax)
284   {
207        int             imin[SD_MAXDIM], imax[SD_MAXDIM];
285          unsigned        n;
286          int             i;
287  
# Line 222 | Line 299 | SDavgTreBox(const SDNode *st, const double *bmin, cons
299          if (st->log2GR < 0) {           /* iterate on subtree */
300                  double          sum = .0, wsum = 1e-20;
301                  double          sbmin[SD_MAXDIM], sbmax[SD_MAXDIM], w;
225
302                  for (n = 1 << st->ndim; n--; ) {
303                          w = 1.;
304                          for (i = st->ndim; i--; ) {
# Line 246 | Line 322 | SDavgTreBox(const SDNode *st, const double *bmin, cons
322                          }
323                  }
324                  return sum / wsum;
325 +        } else {                        /* iterate over leaves */
326 +                int             imin[SD_MAXDIM], imax[SD_MAXDIM];
327 +
328 +                n = 1;
329 +                for (i = st->ndim; i--; ) {
330 +                        imin[i] = (bmin[i] <= 0) ? 0 :
331 +                                        (int)((1 << st->log2GR)*bmin[i]);
332 +                        imax[i] = (bmax[i] >= 1.) ? (1 << st->log2GR) :
333 +                                (int)((1 << st->log2GR)*bmax[i] + .999999);
334 +                        n *= imax[i] - imin[i];
335 +                }
336 +                if (n)
337 +                        return SDiterSum(st->u.v, st->ndim,
338 +                                        st->log2GR, imin, imax) / (double)n;
339          }
340 <        n = 1;                          /* iterate over leaves */
251 <        for (i = st->ndim; i--; ) {
252 <                imin[i] = (bmin[i] <= 0) ? 0
253 <                                : (int)((1 << st->log2GR)*bmin[i]);
254 <                imax[i] = (bmax[i] >= 1.) ? (1 << st->log2GR)
255 <                                : (int)((1 << st->log2GR)*bmax[i] + .999999);
256 <                n *= imax[i] - imin[i];
257 <        }
258 <        if (!n)
259 <                return .0;
260 <        
261 <        return SDiterSum(st->u.v, st->ndim, st->log2GR, imin, imax) / (double)n;
340 >        return .0;
341   }
342  
343   /* Recursive call for SDtraverseTre() */
# Line 270 | Line 349 | SDdotravTre(const SDNode *st, const double *pos, int c
349          int     rv, rval = 0;
350          double  bmin[SD_MAXDIM];
351          int     i, n;
352 +                                        /* paranoia */
353 +        if (st == NULL)
354 +                return 0;
355                                          /* in branches? */
356          if (st->log2GR < 0) {
357                  unsigned        skipmask = 0;
358                  csiz *= .5;
359                  for (i = st->ndim; i--; )
360 <                        if (1<<i & cmask)
360 >                        if (1<<i & cmask) {
361                                  if (pos[i] < cmin[i] + csiz)
362                                          for (n = 1 << st->ndim; n--; ) {
363                                                  if (n & 1<<i)
# Line 286 | Line 368 | SDdotravTre(const SDNode *st, const double *pos, int c
368                                                  if (!(n & 1<<i))
369                                                          skipmask |= 1<<n;
370                                          }
371 +                        }
372                  for (n = 1 << st->ndim; n--; ) {
373                          if (1<<n & skipmask)
374                                  continue;
# Line 319 | Line 402 | SDdotravTre(const SDNode *st, const double *pos, int c
402                                  clim[i][0] = 0;
403                                  clim[i][1] = 1 << st->log2GR;
404                          }
322                                        /* fill in unused dimensions */
323                for (i = SD_MAXDIM; i-- > st->ndim; ) {
324                        clim[i][0] = 0; clim[i][1] = 1;
325                }
405   #if (SD_MAXDIM == 4)
406                  bmin[0] = cmin[0] + csiz*clim[0][0];
407                  for (cpos[0] = clim[0][0]; cpos[0] < clim[0][1]; cpos[0]++) {
408                      bmin[1] = cmin[1] + csiz*clim[1][0];
409                      for (cpos[1] = clim[1][0]; cpos[1] < clim[1][1]; cpos[1]++) {
410                          bmin[2] = cmin[2] + csiz*clim[2][0];
411 <                        for (cpos[2] = clim[2][0]; cpos[2] < clim[2][1]; cpos[2]++) {
412 <                            bmin[3] = cmin[3] + csiz*(cpos[3] = clim[3][0]);
411 >                        if (st->ndim == 3) {
412 >                            cpos[2] = clim[2][0];
413                              n = cpos[0];
414 <                            for (i = 1; i < st->ndim; i++)
414 >                            for (i = 1; i < 3; i++)
415                                  n = (n << st->log2GR) + cpos[i];
416 <                            for ( ; cpos[3] < clim[3][1]; cpos[3]++) {
416 >                            for ( ; cpos[2] < clim[2][1]; cpos[2]++) {
417                                  rval += rv = (*cf)(st->u.v[n++], bmin, csiz, cptr);
418                                  if (rv < 0)
419                                      return rv;
420 <                                bmin[3] += csiz;
420 >                                bmin[2] += csiz;
421                              }
422 <                            bmin[2] += csiz;
422 >                        } else {
423 >                            for (cpos[2] = clim[2][0]; cpos[2] < clim[2][1]; cpos[2]++) {
424 >                                bmin[3] = cmin[3] + csiz*(cpos[3] = clim[3][0]);
425 >                                n = cpos[0];
426 >                                for (i = 1; i < 4; i++)
427 >                                    n = (n << st->log2GR) + cpos[i];
428 >                                for ( ; cpos[3] < clim[3][1]; cpos[3]++) {
429 >                                    rval += rv = (*cf)(st->u.v[n++], bmin, csiz, cptr);
430 >                                    if (rv < 0)
431 >                                        return rv;
432 >                                    bmin[3] += csiz;
433 >                                }
434 >                                bmin[2] += csiz;
435 >                            }
436                          }
437                          bmin[1] += csiz;
438                      }
# Line 358 | Line 450 | static int
450   SDtraverseTre(const SDNode *st, const double *pos, int cmask,
451                                  SDtreCallback *cf, void *cptr)
452   {
361        static double   czero[SD_MAXDIM];
453          int             i;
454                                          /* check arguments */
455          if ((st == NULL) | (cf == NULL))
# Line 383 | Line 474 | SDlookupTre(const SDNode *st, const double *pos, doubl
474                          hcube[i] = .0;
475          }
476                                          /* climb the tree */
477 <        while (st->log2GR < 0) {
477 >        while (st != NULL && st->log2GR < 0) {
478                  n = 0;                  /* move to appropriate branch */
479                  if (hcube) hcube[st->ndim] *= .5;
480                  for (i = st->ndim; i--; ) {
# Line 396 | Line 487 | SDlookupTre(const SDNode *st, const double *pos, doubl
487                  st = st->u.t[n];        /* avoids tail recursion */
488                  pos = spos;
489          }
490 +        if (st == NULL)                 /* should never happen? */
491 +                return .0;
492          if (st->log2GR == 0)            /* short cut */
493                  return st->u.v[0];
494          n = t = 0;                      /* find grid array index */
# Line 411 | Line 504 | SDlookupTre(const SDNode *st, const double *pos, doubl
504          return st->u.v[n];              /* no interpolation */
505   }
506  
507 + /* Convert CIE (Y,u',v') color to our RGB */
508 + static void
509 + SDyuv2rgb(double yval, double uprime, double vprime, float rgb[3])
510 + {
511 +        const double    dfact = 1./(6.*uprime - 16.*vprime + 12.);
512 +        C_COLOR         cxy;
513 +
514 +        c_cset(&cxy, 9.*uprime*dfact, 4.*vprime*dfact);
515 +        c_toSharpRGB(&cxy, yval, rgb);
516 + }
517 +
518   /* Query BSDF value and sample hypercube for the given vectors */
519 < static float
520 < SDqueryTre(const SDTre *sdt, const FVECT outVec, const FVECT inVec, double *hc)
519 > static int
520 > SDqueryTre(const SDTre *sdt, float *coef,
521 >                const FVECT outVec, const FVECT inVec, double *hc)
522   {
523 <        static const FVECT      zvec = {.0, .0, 1.};
524 <        FVECT                   rOutVec;
525 <        double                  gridPos[4];
523 >        const RREAL     *vtmp;
524 >        float           yval;
525 >        FVECT           rOutVec;
526 >        double          gridPos[4];
527  
528 +        if (sdt->stc[tt_Y] == NULL)     /* paranoia, I hope */
529 +                return 0;
530 +
531          switch (sdt->sidef) {           /* whose side are you on? */
532 <        case SD_UFRONT:
532 >        case SD_FREFL:
533                  if ((outVec[2] < 0) | (inVec[2] < 0))
534 <                        return -1.;
534 >                        return 0;
535                  break;
536 <        case SD_UBACK:
536 >        case SD_BREFL:
537                  if ((outVec[2] > 0) | (inVec[2] > 0))
538 <                        return -1.;
538 >                        return 0;
539                  break;
540 <        case SD_XMIT:
541 <                if ((outVec[2] > 0) == (inVec[2] > 0))
542 <                        return -1.;
540 >        case SD_FXMIT:
541 >                if (outVec[2] > 0) {
542 >                        if (inVec[2] > 0)
543 >                                return 0;
544 >                        vtmp = outVec; outVec = inVec; inVec = vtmp;
545 >                } else if (inVec[2] < 0)
546 >                        return 0;
547                  break;
548 +        case SD_BXMIT:
549 +                if (inVec[2] > 0) {
550 +                        if (outVec[2] > 0)
551 +                                return 0;
552 +                        vtmp = outVec; outVec = inVec; inVec = vtmp;
553 +                } else if (outVec[2] < 0)
554 +                        return 0;
555 +                break;
556          default:
557 <                return -1.;
557 >                return 0;
558          }
559                                          /* convert vector coordinates */
560 <        if (sdt->st->ndim == 3) {
561 <                spinvector(rOutVec, outVec, zvec, -atan2(inVec[1],inVec[0]));
562 <                gridPos[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
560 >        if (sdt->stc[tt_Y]->ndim == 3) {
561 >                spinvector(rOutVec, outVec, zvec, -atan2(-inVec[1],-inVec[0]));
562 >                gridPos[0] = (.5-FTINY) -
563 >                                .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
564                  SDdisk2square(gridPos+1, rOutVec[0], rOutVec[1]);
565 <        } else if (sdt->st->ndim == 4) {
565 >        } else if (sdt->stc[tt_Y]->ndim == 4) {
566                  SDdisk2square(gridPos, -inVec[0], -inVec[1]);
567                  SDdisk2square(gridPos+2, outVec[0], outVec[1]);
568          } else
569 <                return -1.;             /* should be internal error */
570 <
571 <        return SDlookupTre(sdt->st, gridPos, hc);
569 >                return 0;               /* should be internal error */
570 >                                        /* get BSDF value */
571 >        yval = SDlookupTre(sdt->stc[tt_Y], gridPos, hc);
572 >        if (coef == NULL)               /* just getting hypercube? */
573 >                return 1;
574 >        if (sdt->stc[tt_u] == NULL || sdt->stc[tt_v] == NULL) {
575 >                *coef = yval;
576 >                return 1;               /* no color */
577 >        }
578 >                                        /* else decode color */
579 >        SDyuv2rgb(yval, SDlookupTre(sdt->stc[tt_u], gridPos, NULL),
580 >                        SDlookupTre(sdt->stc[tt_v], gridPos, NULL), coef);
581 >        coef[0] *= tt_RGB_coef[0];
582 >        coef[1] *= tt_RGB_coef[1];
583 >        coef[2] *= tt_RGB_coef[2];
584 >        return 3;
585   }
586  
587   /* Compute non-diffuse component for variable-resolution BSDF */
# Line 459 | Line 594 | SDgetTreBSDF(float coef[SDmaxCh], const FVECT outVec,
594                                  || sdc->dist == NULL)
595                  return 0;
596                                          /* get nearest BSDF value */
597 <        coef[0] = SDqueryTre((SDTre *)sdc->dist, outVec, inVec, NULL);
463 <        return (coef[0] >= 0);          /* monochromatic for now */
597 >        return SDqueryTre((SDTre *)sdc->dist, coef, outVec, inVec, NULL);
598   }
599  
600   /* Callback to build cumulative distribution using SDtraverseTre() */
# Line 469 | Line 603 | build_scaffold(float val, const double *cmin, double c
603   {
604          SDdistScaffold  *sp = (SDdistScaffold *)cptr;
605          int             wid = csiz*(double)iwmax + .5;
606 +        double          revcmin[2];
607          bitmask_t       bmin[2], bmax[2];
608  
609 <        cmin += sp->nic;                /* skip to output coords */
609 >        if (sp->rev) {                  /* need to reverse sense? */
610 >                revcmin[0] = 1. - cmin[0] - csiz;
611 >                revcmin[1] = 1. - cmin[1] - csiz;
612 >                cmin = revcmin;
613 >        } else {
614 >                cmin += sp->nic;        /* else skip to output coords */
615 >        }
616          if (wid < sp->wmin)             /* new minimum width? */
617                  sp->wmin = wid;
618          if (wid > sp->wmax)             /* new maximum? */
619                  sp->wmax = wid;
620          if (sp->alen >= sp->nall) {     /* need more space? */
621                  struct outdir_s *ndarr;
622 <                sp->nall += 1024;
622 >                sp->nall = (int)(1.5*sp->nall) + 256;
623                  ndarr = (struct outdir_s *)realloc(sp->darr,
624                                          sizeof(struct outdir_s)*sp->nall);
625                  if (ndarr == NULL) {
# Line 517 | Line 658 | sscmp(const void *p1, const void *p2)
658  
659   /* Create a new cumulative distribution for the given input direction */
660   static SDTreCDst *
661 < make_cdist(const SDTre *sdt, const double *pos)
661 > make_cdist(const SDTre *sdt, const double *invec, int rev)
662   {
663          SDdistScaffold  myScaffold;
664 +        double          pos[4];
665 +        int             cmask;
666          SDTreCDst       *cd;
667          struct outdir_s *sp;
668          double          scale, cursum;
# Line 527 | Line 670 | make_cdist(const SDTre *sdt, const double *pos)
670                                          /* initialize scaffold */
671          myScaffold.wmin = iwmax;
672          myScaffold.wmax = 0;
673 <        myScaffold.nic = sdt->st->ndim - 2;
673 >        myScaffold.nic = sdt->stc[tt_Y]->ndim - 2;
674 >        myScaffold.rev = rev;
675          myScaffold.alen = 0;
676          myScaffold.nall = 512;
677          myScaffold.darr = (struct outdir_s *)malloc(sizeof(struct outdir_s) *
678                                                          myScaffold.nall);
679          if (myScaffold.darr == NULL)
680                  return NULL;
681 +                                        /* set up traversal */
682 +        cmask = (1<<myScaffold.nic) - 1;
683 +        for (i = myScaffold.nic; i--; )
684 +                        pos[i+2*rev] = invec[i];
685 +        cmask <<= 2*rev;
686                                          /* grow the distribution */
687 <        if (SDtraverseTre(sdt->st, pos, (1<<myScaffold.nic)-1,
688 <                                &build_scaffold, &myScaffold) < 0) {
687 >        if (SDtraverseTre(sdt->stc[tt_Y], pos, cmask,
688 >                                build_scaffold, &myScaffold) < 0) {
689                  free(myScaffold.darr);
690                  return NULL;
691          }
# Line 550 | Line 699 | make_cdist(const SDTre *sdt, const double *pos)
699                  free(myScaffold.darr);
700                  return NULL;
701          }
702 +        cd->isodist = (myScaffold.nic == 1);
703                                          /* sort the distribution */
704          qsort(myScaffold.darr, cd->calen = myScaffold.alen,
705 <                                sizeof(struct outdir_s), &sscmp);
705 >                                sizeof(struct outdir_s), sscmp);
706  
707                                          /* record input range */
708          scale = myScaffold.wmin / (double)iwmax;
709          for (i = myScaffold.nic; i--; ) {
710 <                cd->clim[i][0] = floor(pos[i]/scale) * scale;
710 >                cd->clim[i][0] = floor(pos[i+2*rev]/scale) * scale;
711                  cd->clim[i][1] = cd->clim[i][0] + scale;
712          }
713 +        if (cd->isodist) {              /* avoid issue in SDqueryTreProjSA() */
714 +                cd->clim[1][0] = cd->clim[0][0];
715 +                cd->clim[1][1] = cd->clim[0][1];
716 +        }
717          cd->max_psa = myScaffold.wmax / (double)iwmax;
718          cd->max_psa *= cd->max_psa * M_PI;
719 <        cd->sidef = sdt->sidef;
719 >        if (rev)
720 >                cd->sidef = (sdt->sidef==SD_BXMIT) ? SD_FXMIT : SD_BXMIT;
721 >        else
722 >                cd->sidef = sdt->sidef;
723          cd->cTotal = 1e-20;             /* compute directional total */
724          sp = myScaffold.darr;
725          for (i = myScaffold.alen; i--; sp++)
# Line 587 | Line 744 | make_cdist(const SDTre *sdt, const double *pos)
744   const SDCDst *
745   SDgetTreCDist(const FVECT inVec, SDComponent *sdc)
746   {
747 +        unsigned long   cacheLeft = SDmaxCache;
748          const SDTre     *sdt;
749          double          inCoord[2];
592        int             vflags;
750          int             i;
751 <        SDTreCDst       *cd, *cdlast;
751 >        int             mode;
752 >        SDTreCDst       *cd, *cdlast, *cdlimit;
753                                          /* check arguments */
754          if ((inVec == NULL) | (sdc == NULL) ||
755                          (sdt = (SDTre *)sdc->dist) == NULL)
756                  return NULL;
757 <        if (sdt->st->ndim == 3)         /* isotropic BSDF? */
758 <                inCoord[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
759 <        else if (sdt->st->ndim == 4)
760 <                SDdisk2square(inCoord, -inVec[0], -inVec[1]);
761 <        else
757 >        switch (mode = sdt->sidef) {    /* check direction */
758 >        case SD_FREFL:
759 >                if (inVec[2] < 0)
760 >                        return NULL;
761 >                break;
762 >        case SD_BREFL:
763 >                if (inVec[2] > 0)
764 >                        return NULL;
765 >                break;
766 >        case SD_FXMIT:
767 >                if (inVec[2] < 0)
768 >                        mode = SD_BXMIT;
769 >                break;
770 >        case SD_BXMIT:
771 >                if (inVec[2] > 0)
772 >                        mode = SD_FXMIT;
773 >                break;
774 >        default:
775 >                return NULL;
776 >        }
777 >        if (sdt->stc[tt_Y]->ndim == 3) {        /* isotropic BSDF? */
778 >                if (mode != sdt->sidef) /* XXX unhandled reciprocity */
779 >                        return &SDemptyCD;
780 >                inCoord[0] = (.5-FTINY) -
781 >                                .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
782 >        } else if (sdt->stc[tt_Y]->ndim == 4) {
783 >                if (mode != sdt->sidef) /* use reciprocity? */
784 >                        SDdisk2square(inCoord, inVec[0], inVec[1]);
785 >                else
786 >                        SDdisk2square(inCoord, -inVec[0], -inVec[1]);
787 >        } else
788                  return NULL;            /* should be internal error */
789 <        cdlast = NULL;                  /* check for direction in cache list */
789 >                                        /* quantize to avoid f.p. errors */
790 >        for (i = sdt->stc[tt_Y]->ndim - 2; i--; )
791 >                inCoord[i] = floor(inCoord[i]/quantum)*quantum + .5*quantum;
792 >        cdlast = cdlimit = NULL;        /* check for direction in cache list */
793 >        /* PLACE MUTEX LOCK HERE FOR THREAD-SAFE */
794          for (cd = (SDTreCDst *)sdc->cdList; cd != NULL;
795 <                                cdlast = cd, cd = (SDTreCDst *)cd->next) {
796 <                for (i = sdt->st->ndim - 2; i--; )
795 >                                        cdlast = cd, cd = cd->next) {
796 >                if (cacheLeft) {        /* check cache size limit */
797 >                        long    csiz = sizeof(SDTreCDst) +
798 >                                        sizeof(cd->carr[0])*cd->calen;
799 >                        if (cacheLeft > csiz)
800 >                                cacheLeft -= csiz;
801 >                        else {
802 >                                cdlimit = cdlast;
803 >                                cacheLeft = 0;
804 >                        }
805 >                }
806 >                if (cd->sidef != mode)
807 >                        continue;
808 >                for (i = sdt->stc[tt_Y]->ndim - 2; i--; )
809                          if ((cd->clim[i][0] > inCoord[i]) |
810                                          (inCoord[i] >= cd->clim[i][1]))
811                                  break;
812                  if (i < 0)
813                          break;          /* means we have a match */
814          }
815 <        if (cd == NULL)                 /* need to create new entry? */
816 <                cdlast = cd = make_cdist(sdt, inCoord);
815 >        if (cd == NULL) {               /* need to create new entry? */
816 >                if (cdlimit != NULL)    /* exceeded cache size limit? */
817 >                        while ((cd = cdlimit->next) != NULL) {
818 >                                cdlimit->next = cd->next;
819 >                                free(cd);
820 >                        }
821 >                cdlast = cd = make_cdist(sdt, inCoord, mode != sdt->sidef);
822 >        }
823          if (cdlast != NULL) {           /* move entry to head of cache list */
824                  cdlast->next = cd->next;
825 <                cd->next = sdc->cdList;
825 >                cd->next = (SDTreCDst *)sdc->cdList;
826                  sdc->cdList = (SDCDst *)cd;
827          }
828 +        /* END MUTEX LOCK */
829          return (SDCDst *)cd;            /* ready to go */
830   }
831  
# Line 635 | Line 842 | SDqueryTreProjSA(double *psa, const FVECT v1, const RR
842                                          /* get projected solid angle(s) */
843          if (v2 != NULL) {
844                  const SDTre     *sdt = (SDTre *)sdc->dist;
845 <                double          hcube[SD_MAXDIM];
846 <                if (SDqueryTre(sdt, v1, v2, hcube) < 0) {
845 >                double          hcube[SD_MAXDIM+1];
846 >                if (!SDqueryTre(sdt, NULL, v1, v2, hcube)) {
847                          strcpy(SDerrorDetail, "Bad call to SDqueryTreProjSA");
848                          return SDEinternal;
849                  }
850 <                myPSA[0] = hcube[sdt->st->ndim];
850 >                myPSA[0] = hcube[sdt->stc[tt_Y]->ndim];
851                  myPSA[1] = myPSA[0] *= myPSA[0] * M_PI;
852          } else {
853                  const SDTreCDst *cd = (const SDTreCDst *)SDgetTreCDist(v1, sdc);
854                  if (cd == NULL)
855 <                        return SDEmemory;
856 <                myPSA[0] = M_PI * (cd->clim[0][1] - cd->clim[0][0]) *
857 <                                (cd->clim[1][1] - cd->clim[1][0]);
858 <                myPSA[1] = cd->max_psa;
855 >                        myPSA[0] = myPSA[1] = 0;
856 >                else {
857 >                        myPSA[0] = M_PI * (cd->clim[0][1] - cd->clim[0][0]) *
858 >                                        (cd->clim[1][1] - cd->clim[1][0]);
859 >                        myPSA[1] = cd->max_psa;
860 >                }
861          }
862          switch (qflags) {               /* record based on flag settings */
863          case SDqueryVal:
# Line 663 | Line 872 | SDqueryTreProjSA(double *psa, const FVECT v1, const RR
872                          psa[1] = myPSA[1];
873                  /* fall through */
874          case SDqueryMin:
875 <                if (myPSA[0] < psa[0])
875 >                if ((myPSA[0] > 0) & (myPSA[0] < psa[0]))
876                          psa[0] = myPSA[0];
877                  break;
878          }
# Line 679 | Line 888 | SDsampTreCDist(FVECT ioVec, double randX, const SDCDst
888          const SDTreCDst *cd = (const SDTreCDst *)cdp;
889          const unsigned  target = randX*cumlmax;
890          bitmask_t       hndx, hcoord[2];
891 <        double          gpos[3];
891 >        double          gpos[3], rotangle;
892          int             i, iupper, ilower;
893                                          /* check arguments */
894          if ((ioVec == NULL) | (cd == NULL))
895                  return SDEargument;
896 +        if (!cd->sidef)
897 +                return SDEnone;         /* XXX should never happen */
898          if (ioVec[2] > 0) {
899 <                if (!(cd->sidef & SD_UFRONT))
899 >                if ((cd->sidef != SD_FREFL) & (cd->sidef != SD_FXMIT))
900                          return SDEargument;
901 <        } else if (!(cd->sidef & SD_UBACK))
901 >        } else if ((cd->sidef != SD_BREFL) & (cd->sidef != SD_BXMIT))
902                  return SDEargument;
903                                          /* binary search to find position */
904          ilower = 0; iupper = cd->calen;
905          while ((i = (iupper + ilower) >> 1) != ilower)
906 <                if ((long)target >= (long)cd->carr[i].cuml)
906 >                if (target >= cd->carr[i].cuml)
907                          ilower = i;
908                  else
909                          iupper = i;
# Line 710 | Line 921 | SDsampTreCDist(FVECT ioVec, double randX, const SDCDst
921          SDsquare2disk(gpos, gpos[0], gpos[1]);
922                                          /* compute Z-coordinate */
923          gpos[2] = 1. - gpos[0]*gpos[0] - gpos[1]*gpos[1];
924 <        if (gpos[2] > 0)                /* paranoia, I hope */
714 <                gpos[2] = sqrt(gpos[2]);
924 >        gpos[2] = sqrt(gpos[2]*(gpos[2]>0));
925                                          /* emit from back? */
926 <        if (ioVec[2] > 0 ^ cd->sidef != SD_XMIT)
926 >        if ((cd->sidef == SD_BREFL) | (cd->sidef == SD_FXMIT))
927                  gpos[2] = -gpos[2];
928 <        VCOPY(ioVec, gpos);
928 >        if (cd->isodist) {              /* rotate isotropic sample */
929 >                rotangle = atan2(-ioVec[1],-ioVec[0]);
930 >                spinvector(ioVec, gpos, zvec, rotangle);
931 >        } else
932 >                VCOPY(ioVec, gpos);
933          return SDEnone;
934   }
935  
# Line 729 | Line 943 | next_token(char **spp)
943   }
944  
945   /* Advance pointer past matching token (or any token if c==0) */
946 < #define eat_token(spp,c)        (next_token(spp)==(c) ^ !(c) ? *(*(spp))++ : 0)
946 > #define eat_token(spp,c)        ((next_token(spp)==(c)) ^ !(c) ? *(*(spp))++ : 0)
947  
948   /* Count words from this point in string to '}' */
949   static int
# Line 755 | Line 969 | load_values(char **spp, float *va, int n)
969          char    *svnext;
970  
971          while (n-- > 0 && (svnext = fskip(*spp)) != NULL) {
972 <                *v++ = atof(*spp);
972 >                if ((*v++ = atof(*spp)) < 0)
973 >                        v[-1] = 0;
974                  *spp = svnext;
975                  eat_token(spp, ',');
976          }
# Line 785 | Line 1000 | load_tree_data(char **spp, int nd)
1000          } else {                        /* else load value grid */
1001                  int     bsiz;
1002                  n = count_values(*spp); /* see how big the grid is */
1003 <                for (bsiz = 0; bsiz < 8*sizeof(size_t)-1; bsiz += nd)
1003 >                for (bsiz = 0; bsiz < 8*sizeof(size_t); bsiz += nd)
1004                          if (1<<bsiz == n)
1005                                  break;
1006                  if (bsiz >= 8*sizeof(size_t)) {
# Line 814 | Line 1029 | load_tree_data(char **spp, int nd)
1029   static SDError
1030   get_extrema(SDSpectralDF *df)
1031   {
1032 <        SDNode  *st = (*(SDTre *)df->comp[0].dist).st;
1032 >        SDNode  *st = (*(SDTre *)df->comp[0].dist).stc[tt_Y];
1033          double  stepWidth, dhemi, bmin[4], bmax[4];
1034  
1035          stepWidth = SDsmallestLeaf(st);
1036 +        if (quantum > stepWidth)        /* adjust quantization factor */
1037 +                quantum = stepWidth;
1038          df->minProjSA = M_PI*stepWidth*stepWidth;
1039          if (stepWidth < .03125)
1040                  stepWidth = .03125;     /* 1/32 resolution good enough */
# Line 852 | Line 1069 | get_extrema(SDSpectralDF *df)
1069  
1070   /* Load BSDF distribution for this wavelength */
1071   static SDError
1072 < load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
1072 > load_bsdf_data(SDData *sd, ezxml_t wdb, int ct, int ndim)
1073   {
1074          SDSpectralDF    *df;
1075          SDTre           *sdt;
1076          char            *sdata;
860        int             i;
1077                                          /* allocate BSDF component */
1078          sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
1079          if (!sdata)
# Line 865 | Line 1081 | load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
1081          /*
1082           * Remember that front and back are reversed from WINDOW 6 orientations
1083           */
1084 <        if (!strcasecmp(sdata, "Transmission")) {
1085 <                if (sd->tf != NULL)
870 <                        SDfreeSpectralDF(sd->tf);
871 <                if ((sd->tf = SDnewSpectralDF(1)) == NULL)
1084 >        if (!strcasecmp(sdata, "Transmission Front")) {
1085 >                if (sd->tb == NULL && (sd->tb = SDnewSpectralDF(1)) == NULL)
1086                          return SDEmemory;
1087 +                df = sd->tb;
1088 +        } else if (!strcasecmp(sdata, "Transmission Back")) {
1089 +                if (sd->tf == NULL && (sd->tf = SDnewSpectralDF(1)) == NULL)
1090 +                        return SDEmemory;
1091                  df = sd->tf;
1092          } else if (!strcasecmp(sdata, "Reflection Front")) {
1093 <                if (sd->rb != NULL)     /* note back-front reversal */
876 <                        SDfreeSpectralDF(sd->rb);
877 <                if ((sd->rb = SDnewSpectralDF(1)) == NULL)
1093 >                if (sd->rb == NULL && (sd->rb = SDnewSpectralDF(1)) == NULL)
1094                          return SDEmemory;
1095                  df = sd->rb;
1096          } else if (!strcasecmp(sdata, "Reflection Back")) {
1097 <                if (sd->rf != NULL)     /* note front-back reversal */
882 <                        SDfreeSpectralDF(sd->rf);
883 <                if ((sd->rf = SDnewSpectralDF(1)) == NULL)
1097 >                if (sd->rf == NULL && (sd->rf = SDnewSpectralDF(1)) == NULL)
1098                          return SDEmemory;
1099                  df = sd->rf;
1100          } else
1101                  return SDEnone;
888        /* XXX should also check "ScatteringDataType" for consistency? */
1102                                          /* get angle bases */
1103          sdata = ezxml_txt(ezxml_child(wdb,"AngleBasis"));
1104          if (!sdata || strcasecmp(sdata, "LBNL/Shirley-Chiu")) {
# Line 893 | Line 1106 | load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
1106                                  !sdata ? "Missing" : "Unsupported", sd->name);
1107                  return !sdata ? SDEformat : SDEsupport;
1108          }
1109 <                                        /* allocate BSDF tree */
1110 <        sdt = (SDTre *)malloc(sizeof(SDTre));
1111 <        if (sdt == NULL)
1112 <                return SDEmemory;
1113 <        if (df == sd->rf)
1114 <                sdt->sidef = SD_UFRONT;
1115 <        else if (df == sd->rb)
1116 <                sdt->sidef = SD_UBACK;
1117 <        else
1118 <                sdt->sidef = SD_XMIT;
1119 <        sdt->st = NULL;
1120 <        df->comp[0].cspec[0] = c_dfcolor; /* XXX monochrome for now */
1121 <        df->comp[0].dist = sdt;
1122 <        df->comp[0].func = &SDhandleTre;
1109 >        if (df->comp[0].dist == NULL) { /* need to allocate BSDF tree? */
1110 >                sdt = (SDTre *)malloc(sizeof(SDTre));
1111 >                if (sdt == NULL)
1112 >                        return SDEmemory;
1113 >                if (df == sd->rf)
1114 >                        sdt->sidef = SD_FREFL;
1115 >                else if (df == sd->rb)
1116 >                        sdt->sidef = SD_BREFL;
1117 >                else if (df == sd->tf)
1118 >                        sdt->sidef = SD_FXMIT;
1119 >                else /* df == sd->tb */
1120 >                        sdt->sidef = SD_BXMIT;
1121 >                sdt->stc[tt_Y] = sdt->stc[tt_u] = sdt->stc[tt_v] = NULL;
1122 >                df->comp[0].dist = sdt;
1123 >                df->comp[0].func = &SDhandleTre;
1124 >        } else {
1125 >                sdt = (SDTre *)df->comp[0].dist;
1126 >                if (sdt->stc[ct] != NULL) {
1127 >                        SDfreeTre(sdt->stc[ct]);
1128 >                        sdt->stc[ct] = NULL;
1129 >                }
1130 >        }
1131                                          /* read BSDF data */
1132          sdata = ezxml_txt(ezxml_child(wdb, "ScatteringData"));
1133          if (!sdata || !next_token(&sdata)) {
# Line 914 | Line 1135 | load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
1135                                  sd->name);
1136                  return SDEformat;
1137          }
1138 <        sdt->st = load_tree_data(&sdata, ndim);
1139 <        if (sdt->st == NULL)
1138 >        sdt->stc[ct] = load_tree_data(&sdata, ndim);
1139 >        if (sdt->stc[ct] == NULL)
1140                  return SDEformat;
1141          if (next_token(&sdata)) {       /* check for unconsumed characters */
1142                  sprintf(SDerrorDetail,
# Line 924 | Line 1145 | load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
1145                  return SDEformat;
1146          }
1147                                          /* flatten branches where possible */
1148 <        sdt->st = SDsimplifyTre(sdt->st);
1149 <        if (sdt->st == NULL)
1148 >        sdt->stc[ct] = SDsimplifyTre(sdt->stc[ct]);
1149 >        if (sdt->stc[ct] == NULL)
1150                  return SDEinternal;
1151 <        return get_extrema(df);         /* compute global quantities */
1151 >                                        /* compute global quantities for Y */
1152 >        return (ct == tt_Y) ? get_extrema(df) : SDEnone;
1153   }
1154  
1155   /* Find minimum value in tree */
# Line 962 | Line 1184 | SDsubtractTreVal(SDNode *st, float val)
1184                          SDsubtractTreVal(st->u.t[n], val);
1185          } else {
1186                  for (n = 1<<(st->ndim*st->log2GR); n--; )
1187 <                        st->u.v[n] -= val;
1187 >                        if ((st->u.v[n] -= val) < 0)
1188 >                                st->u.v[n] = .0f;
1189          }
1190   }
1191  
1192 < /* Subtract minimum value from BSDF */
1192 > /* Subtract minimum Y value from BSDF */
1193   static double
1194 < subtract_min(SDNode *st)
1194 > subtract_min_Y(SDNode *st)
1195   {
1196 <        float   vmin;
1196 >        const float     vmaxmin = 1.5/M_PI;
1197 >        float           vmin;
1198                                          /* be sure to skip unused portion */
1199          if (st->ndim == 3) {
1200                  int     n;
1201 <                vmin = 1./M_PI;
1201 >                vmin = vmaxmin;
1202                  if (st->log2GR < 0) {
1203 <                        for (n = 0; n < 4; n++) {
1203 >                        for (n = 0; n < 8; n += 2) {
1204                                  float   v = SDgetTreMin(st->u.t[n]);
1205                                  if (v < vmin)
1206                                          vmin = v;
# Line 990 | Line 1214 | subtract_min(SDNode *st)
1214          } else                          /* anisotropic covers entire tree */
1215                  vmin = SDgetTreMin(st);
1216  
1217 <        if (vmin <= FTINY)
1218 <                return .0;
1217 >        if ((vmin >= vmaxmin) | (vmin <= .01/M_PI))
1218 >                return .0;              /* not worth bothering about */
1219  
1220          SDsubtractTreVal(st, vmin);
1221  
1222          return M_PI * vmin;             /* return hemispherical value */
1223   }
1224  
1225 + /* Struct used in callback to find RGB extrema */
1226 + typedef struct {
1227 +        SDNode  **stc;                  /* original Y, u' & v' trees */
1228 +        float   rgb[3];                 /* RGB value */
1229 +        SDNode  *new_stu, *new_stv;     /* replacement u' & v' trees */
1230 + } SDextRGBs;
1231 +
1232 + /* Callback to find minimum RGB from Y value plus CIE (u',v') trees */
1233 + static int
1234 + get_min_RGB(float yval, const double *cmin, double csiz, void *cptr)
1235 + {
1236 +        SDextRGBs       *mp = (SDextRGBs *)cptr;
1237 +        double          cmax[SD_MAXDIM];
1238 +        float           rgb[3];
1239 +
1240 +        if (mp->stc[tt_Y]->ndim == 3) {
1241 +                if (cmin[0] + .5*csiz >= .5)
1242 +                        return 0;       /* ignore dead half of isotropic */
1243 +        } else
1244 +                cmax[3] = cmin[3] + csiz;
1245 +        cmax[0] = cmin[0] + csiz;
1246 +        cmax[1] = cmin[1] + csiz;
1247 +        cmax[2] = cmin[2] + csiz;
1248 +                                        /* average RGB color over voxel */
1249 +        SDyuv2rgb(yval, SDavgTreBox(mp->stc[tt_u], cmin, cmax),
1250 +                        SDavgTreBox(mp->stc[tt_v], cmin, cmax), rgb);
1251 +                                        /* track smallest components */
1252 +        if (rgb[0] < mp->rgb[0]) mp->rgb[0] = rgb[0];
1253 +        if (rgb[1] < mp->rgb[1]) mp->rgb[1] = rgb[1];
1254 +        if (rgb[2] < mp->rgb[2]) mp->rgb[2] = rgb[2];
1255 +        return 0;
1256 + }
1257 +
1258 + /* Callback to build adjusted u' tree */
1259 + static int
1260 + adjust_utree(float uprime, const double *cmin, double csiz, void *cptr)
1261 + {
1262 +        SDextRGBs       *mp = (SDextRGBs *)cptr;
1263 +        double          cmax[SD_MAXDIM];
1264 +        double          yval;
1265 +        float           rgb[3];
1266 +        C_COLOR         clr;
1267 +
1268 +        if (mp->stc[tt_Y]->ndim == 3) {
1269 +                if (cmin[0] + .5*csiz >= .5)
1270 +                        return 0;       /* ignore dead half of isotropic */
1271 +        } else
1272 +                cmax[3] = cmin[3] + csiz;
1273 +        cmax[0] = cmin[0] + csiz;
1274 +        cmax[1] = cmin[1] + csiz;
1275 +        cmax[2] = cmin[2] + csiz;
1276 +                                        /* average RGB color over voxel */
1277 +        SDyuv2rgb(yval=SDavgTreBox(mp->stc[tt_Y], cmin, cmax), uprime,
1278 +                        SDavgTreBox(mp->stc[tt_v], cmin, cmax), rgb);
1279 +                                        /* subtract minimum (& clamp) */
1280 +        if ((rgb[0] -= mp->rgb[0]) < 1e-5*yval) rgb[0] = 1e-5*yval;
1281 +        if ((rgb[1] -= mp->rgb[1]) < 1e-5*yval) rgb[1] = 1e-5*yval;
1282 +        if ((rgb[2] -= mp->rgb[2]) < 1e-5*yval) rgb[2] = 1e-5*yval;
1283 +        c_fromSharpRGB(rgb, &clr);      /* compute new u' for adj. RGB */
1284 +        uprime = 4.*clr.cx/(-2.*clr.cx + 12.*clr.cy + 3.);
1285 +                                        /* assign in new u' tree */
1286 +        mp->new_stu = SDsetVoxel(mp->new_stu, mp->stc[tt_Y]->ndim,
1287 +                                        cmin, csiz, uprime);
1288 +        return -(mp->new_stu == NULL);
1289 + }
1290 +
1291 + /* Callback to build adjusted v' tree */
1292 + static int
1293 + adjust_vtree(float vprime, const double *cmin, double csiz, void *cptr)
1294 + {
1295 +        SDextRGBs       *mp = (SDextRGBs *)cptr;
1296 +        double          cmax[SD_MAXDIM];
1297 +        double          yval;
1298 +        float           rgb[3];
1299 +        C_COLOR         clr;
1300 +
1301 +        if (mp->stc[tt_Y]->ndim == 3) {
1302 +                if (cmin[0] + .5*csiz >= .5)
1303 +                        return 0;       /* ignore dead half of isotropic */
1304 +        } else
1305 +                cmax[3] = cmin[3] + csiz;
1306 +        cmax[0] = cmin[0] + csiz;
1307 +        cmax[1] = cmin[1] + csiz;
1308 +        cmax[2] = cmin[2] + csiz;
1309 +                                        /* average RGB color over voxel */
1310 +        SDyuv2rgb(yval=SDavgTreBox(mp->stc[tt_Y], cmin, cmax),
1311 +                        SDavgTreBox(mp->stc[tt_u], cmin, cmax),
1312 +                        vprime, rgb);
1313 +                                        /* subtract minimum (& clamp) */
1314 +        if ((rgb[0] -= mp->rgb[0]) < 1e-5*yval) rgb[0] = 1e-5*yval;
1315 +        if ((rgb[1] -= mp->rgb[1]) < 1e-5*yval) rgb[1] = 1e-5*yval;
1316 +        if ((rgb[2] -= mp->rgb[2]) < 1e-5*yval) rgb[2] = 1e-5*yval;
1317 +        c_fromSharpRGB(rgb, &clr);      /* compute new v' for adj. RGB */
1318 +        vprime = 9.*clr.cy/(-2.*clr.cx + 12.*clr.cy + 3.);
1319 +                                        /* assign in new v' tree */
1320 +        mp->new_stv = SDsetVoxel(mp->new_stv, mp->stc[tt_Y]->ndim,
1321 +                                        cmin, csiz, vprime);
1322 +        return -(mp->new_stv == NULL);
1323 + }
1324 +
1325 + /* Subtract minimum (diffuse) color and return luminance & CIE (x,y) */
1326 + static double
1327 + subtract_min_RGB(C_COLOR *cs, SDNode *stc[])
1328 + {
1329 +        SDextRGBs       my_min;
1330 +        double          ymin;
1331 +
1332 +        my_min.stc = stc;
1333 +        my_min.rgb[0] = my_min.rgb[1] = my_min.rgb[2] = FHUGE;
1334 +        my_min.new_stu = my_min.new_stv = NULL;
1335 +                                        /* get minimum RGB value */
1336 +        SDtraverseTre(stc[tt_Y], NULL, 0, get_min_RGB, &my_min);
1337 +                                        /* convert to C_COLOR */
1338 +        ymin =  c_fromSharpRGB(my_min.rgb, cs);
1339 +        if ((ymin >= .5*FHUGE) | (ymin <= .01/M_PI))
1340 +                return .0;              /* close to zero or no tree */
1341 +                                        /* adjust u' & v' trees */
1342 +        SDtraverseTre(stc[tt_u], NULL, 0, adjust_utree, &my_min);
1343 +        SDtraverseTre(stc[tt_v], NULL, 0, adjust_vtree, &my_min);
1344 +        SDfreeTre(stc[tt_u]); SDfreeTre(stc[tt_v]);
1345 +        stc[tt_u] = SDsimplifyTre(my_min.new_stu);
1346 +        stc[tt_v] = SDsimplifyTre(my_min.new_stv);
1347 +                                        /* subtract Y & return hemispherical */
1348 +        SDsubtractTreVal(stc[tt_Y], ymin);
1349 +
1350 +        return M_PI * ymin;
1351 + }
1352 +
1353   /* Extract and separate diffuse portion of BSDF */
1354   static void
1355   extract_diffuse(SDValue *dv, SDSpectralDF *df)
1356   {
1357          int     n;
1358 +        SDTre   *sdt;
1359  
1360          if (df == NULL || df->ncomp <= 0) {
1361                  dv->spec = c_dfcolor;
1362                  dv->cieY = .0;
1363                  return;
1364          }
1365 <        dv->spec = df->comp[0].cspec[0];
1366 <        dv->cieY = subtract_min((*(SDTre *)df->comp[0].dist).st);
1367 <                                        /* in case of multiple components */
1368 <        for (n = df->ncomp; --n; ) {
1369 <                double  ymin = subtract_min((*(SDTre *)df->comp[n].dist).st);
1370 <                c_cmix(&dv->spec, dv->cieY, &dv->spec, ymin, &df->comp[n].cspec[0]);
1371 <                dv->cieY += ymin;
1365 >        sdt = (SDTre *)df->comp[0].dist;
1366 >                                        /* subtract minimum color/grayscale */
1367 >        if (sdt->stc[tt_u] != NULL && sdt->stc[tt_v] != NULL) {
1368 >                int     i = 3*(tt_RGB_coef[1] < .001);
1369 >                while (i--) {           /* initialize on first call */
1370 >                        float   rgb[3];
1371 >                        rgb[0] = rgb[1] = rgb[2] = .0f; rgb[i] = 1.f;
1372 >                        tt_RGB_coef[i] = c_fromSharpRGB(rgb, &tt_RGB_prim[i]);
1373 >                }
1374 >                memcpy(df->comp[0].cspec, tt_RGB_prim, sizeof(tt_RGB_prim));
1375 >                dv->cieY = subtract_min_RGB(&dv->spec, sdt->stc);
1376 >        } else {
1377 >                df->comp[0].cspec[0] = dv->spec = c_dfcolor;
1378 >                dv->cieY = subtract_min_Y(sdt->stc[tt_Y]);
1379          }
1380          df->maxHemi -= dv->cieY;        /* adjust maximum hemispherical */
1381 <                                        /* make sure everything is set */
1382 <        c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
1381 >                                
1382 >        c_ccvt(&dv->spec, C_CSXY);      /* make sure (x,y) is set */
1383   }
1384  
1385   /* Load a variable-resolution BSDF tree from an open XML file */
# Line 1052 | Line 1412 | SDloadTre(SDData *sd, ezxml_t wtl)
1412                                          /* load BSDF components */
1413          for (wld = ezxml_child(wtl, "WavelengthData");
1414                                  wld != NULL; wld = wld->next) {
1415 <                if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1416 <                                "Visible"))
1417 <                        continue;       /* just visible for now */
1415 >                const char      *cnm = ezxml_txt(ezxml_child(wld,"Wavelength"));
1416 >                int             ct = -1;
1417 >                if (!strcasecmp(cnm, "Visible"))
1418 >                        ct = tt_Y;
1419 >                else if (!strcasecmp(cnm, "CIE-u"))
1420 >                        ct = tt_u;
1421 >                else if (!strcasecmp(cnm, "CIE-v"))
1422 >                        ct = tt_v;
1423 >                else
1424 >                        continue;
1425                  for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1426                                          wdb != NULL; wdb = wdb->next)
1427 <                        if ((ec = load_bsdf_data(sd, wdb, rank)) != SDEnone)
1427 >                        if ((ec = load_bsdf_data(sd, wdb, ct, rank)) != SDEnone)
1428                                  return ec;
1429          }
1430                                          /* separate diffuse components */
1431          extract_diffuse(&sd->rLambFront, sd->rf);
1432          extract_diffuse(&sd->rLambBack, sd->rb);
1433 <        extract_diffuse(&sd->tLamb, sd->tf);
1433 >        if (sd->tf != NULL)
1434 >                extract_diffuse(&sd->tLamb, sd->tf);
1435 >        if (sd->tb != NULL)
1436 >                extract_diffuse(&sd->tLamb, sd->tb);
1437                                          /* return success */
1438          return SDEnone;
1439   }
1440  
1441   /* Variable resolution BSDF methods */
1442 < SDFunc SDhandleTre = {
1442 > const SDFunc SDhandleTre = {
1443          &SDgetTreBSDF,
1444          &SDqueryTreProjSA,
1445          &SDgetTreCDist,

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines