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.6 by greg, Sun Apr 24 19:39:21 2011 UTC vs.
Revision 3.21 by greg, Mon Aug 22 05:48:39 2011 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 24 | Line 25 | typedef int    SDtreCallback(float val, const double *cmi
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))-1;
30 +                                        /* maximum cumulative value */
31 + static const unsigned   cumlmax = ~0;
32 +                                        /* constant z-vector */
33 + static const FVECT      zvec = {.0, .0, 1.};
34  
35   /* Struct used for our distribution-building callback */
36   typedef struct {
31        int             wmin;           /* minimum square size so far */
32        int             wmax;           /* maximum square size */
37          int             nic;            /* number of input coordinates */
38 <        int             alen;           /* current array length */
39 <        int             nall;           /* number of allocated entries */
38 >        unsigned        alen;           /* current array length */
39 >        unsigned        nall;           /* number of allocated entries */
40 >        unsigned        wmin;           /* minimum square size so far */
41 >        unsigned        wmax;           /* maximum square size */
42          struct outdir_s {
43                  unsigned        hent;           /* entering Hilbert index */
44                  int             wid;            /* this square size */
# Line 57 | Line 63 | SDnewNode(int nd, int lg)
63          }
64          if (lg < 0) {
65                  st = (SDNode *)malloc(sizeof(SDNode) +
66 <                                ((1<<nd) - 1)*sizeof(st->u.t[0]));
67 <                if (st != NULL)
62 <                        memset(st->u.t, 0, sizeof(st->u.t[0])<<nd);
63 <        } else
64 <                st = (SDNode *)malloc(sizeof(SDNode) +
65 <                                ((1 << nd*lg) - 1)*sizeof(st->u.v[0]));
66 <                
67 <        if (st == NULL) {
68 <                if (lg < 0)
66 >                                sizeof(st->u.t[0])*((1<<nd) - 1));
67 >                if (st == NULL) {
68                          sprintf(SDerrorDetail,
69                                  "Cannot allocate %d branch BSDF tree", 1<<nd);
70 <                else
70 >                        return NULL;
71 >                }
72 >                memset(st->u.t, 0, sizeof(st->u.t[0])<<nd);
73 >        } else {
74 >                st = (SDNode *)malloc(sizeof(SDNode) +
75 >                                sizeof(st->u.v[0])*((1 << nd*lg) - 1));        
76 >                if (st == NULL) {
77                          sprintf(SDerrorDetail,
78                                  "Cannot allocate %d BSDF leaves", 1 << nd*lg);
79 <                return NULL;
79 >                        return NULL;
80 >                }
81          }
82          st->ndim = nd;
83          st->log2GR = lg;
# Line 82 | Line 88 | SDnewNode(int nd, int lg)
88   static void
89   SDfreeTre(SDNode *st)
90   {
91 <        int     i;
91 >        int     n;
92  
93          if (st == NULL)
94                  return;
95 <        for (i = (st->log2GR < 0) << st->ndim; i--; )
96 <                SDfreeTre(st->u.t[i]);
97 <        free((void *)st);
95 >        for (n = (st->log2GR < 0) << st->ndim; n--; )
96 >                SDfreeTre(st->u.t[n]);
97 >        free(st);
98   }
99  
100   /* Free a variable-resolution BSDF */
# Line 103 | Line 109 | SDFreeBTre(void *p)
109          free(sdt);
110   }
111  
112 + /* Fill branch's worth of grid values from subtree */
113 + static void
114 + fill_grid_branch(float *dptr, const float *sptr, int nd, int shft)
115 + {
116 +        unsigned        n = 1 << (shft-1);
117 +
118 +        if (!--nd) {                    /* end on the line */
119 +                memcpy(dptr, sptr, sizeof(*dptr)*n);
120 +                return;
121 +        }
122 +        while (n--)                     /* recurse on each slice */
123 +                fill_grid_branch(dptr + (n << shft*nd),
124 +                                sptr + (n << (shft-1)*nd), nd, shft);
125 + }
126 +
127 + /* Get pointer at appropriate offset for the given branch */
128 + static float *
129 + grid_branch_start(SDNode *st, int n)
130 + {
131 +        unsigned        skipsiz = 1 << (st->log2GR - 1);
132 +        float           *vptr = st->u.v;
133 +        int             i;
134 +
135 +        for (i = st->ndim; i--; skipsiz <<= st->log2GR)
136 +                if (1<<i & n)
137 +                        vptr += skipsiz;
138 +        return vptr;
139 + }
140 +
141 + /* Simplify (consolidate) a tree by flattening uniform depth regions */
142 + static SDNode *
143 + SDsimplifyTre(SDNode *st)
144 + {
145 +        int             match, n;
146 +
147 +        if (st == NULL)                 /* check for invalid tree */
148 +                return NULL;
149 +        if (st->log2GR >= 0)            /* grid just returns unaltered */
150 +                return st;
151 +        match = 1;                      /* check if grids below match */
152 +        for (n = 0; n < 1<<st->ndim; n++) {
153 +                if ((st->u.t[n] = SDsimplifyTre(st->u.t[n])) == NULL)
154 +                        return NULL;    /* propogate error up call stack */
155 +                match &= (st->u.t[n]->log2GR == st->u.t[0]->log2GR);
156 +        }
157 +        if (match && (match = st->u.t[0]->log2GR) >= 0) {
158 +                SDNode  *stn = SDnewNode(st->ndim, match + 1);
159 +                if (stn == NULL)        /* out of memory? */
160 +                        return st;
161 +                                        /* transfer values to new grid */
162 +                for (n = 1 << st->ndim; n--; )
163 +                        fill_grid_branch(grid_branch_start(stn, n),
164 +                                        st->u.t[n]->u.v, stn->ndim, stn->log2GR);
165 +                SDfreeTre(st);          /* free old tree */
166 +                st = stn;               /* return new one */
167 +        }
168 +        return st;
169 + }
170 +
171 + /* Find smallest leaf in tree */
172 + static double
173 + SDsmallestLeaf(const SDNode *st)
174 + {
175 +        if (st->log2GR < 0) {           /* tree branches */
176 +                double  lmin = 1.;
177 +                int     n;
178 +                for (n = 1<<st->ndim; n--; ) {
179 +                        double  lsiz = SDsmallestLeaf(st->u.t[n]);
180 +                        if (lsiz < lmin)
181 +                                lmin = lsiz;
182 +                }
183 +                return .5*lmin;
184 +        }
185 +                                        /* leaf grid width */
186 +        return 1. / (double)(1 << st->log2GR);
187 + }
188 +
189   /* Add up N-dimensional hypercube array values over the given box */
190   static double
191 < SDiterSum(const float *va, int nd, int siz, const int *imin, const int *imax)
191 > SDiterSum(const float *va, int nd, int shft, const int *imin, const int *imax)
192   {
193 +        const unsigned  skipsiz = 1 << --nd*shft;
194          double          sum = .0;
111        unsigned        skipsiz = 1;
195          int             i;
196 <        
197 <        for (i = nd; --i > 0; )
198 <                skipsiz *= siz;
196 >
197 >        va += *imin * skipsiz;
198 >
199          if (skipsiz == 1)
200                  for (i = *imin; i < *imax; i++)
201 <                        sum += va[i];
201 >                        sum += *va++;
202          else
203 <                for (i = *imin; i < *imax; i++)
204 <                        sum += SDiterSum(va + i*skipsiz,
122 <                                        nd-1, siz, imin+1, imax+1);
203 >                for (i = *imin; i < *imax; i++, va += skipsiz)
204 >                        sum += SDiterSum(va, nd, shft, imin+1, imax+1);
205          return sum;
206   }
207  
# Line 127 | Line 209 | SDiterSum(const float *va, int nd, int siz, const int
209   static double
210   SDavgTreBox(const SDNode *st, const double *bmin, const double *bmax)
211   {
130        int             imin[SD_MAXDIM], imax[SD_MAXDIM];
212          unsigned        n;
213          int             i;
214  
# Line 137 | Line 218 | SDavgTreBox(const SDNode *st, const double *bmin, cons
218          for (i = st->ndim; i--; ) {
219                  if (bmin[i] >= 1.)
220                          return .0;
221 <                if (bmax[i] <= .0)
221 >                if (bmax[i] <= 0)
222                          return .0;
223                  if (bmin[i] >= bmax[i])
224                          return .0;
# Line 145 | Line 226 | SDavgTreBox(const SDNode *st, const double *bmin, cons
226          if (st->log2GR < 0) {           /* iterate on subtree */
227                  double          sum = .0, wsum = 1e-20;
228                  double          sbmin[SD_MAXDIM], sbmax[SD_MAXDIM], w;
148
229                  for (n = 1 << st->ndim; n--; ) {
230                          w = 1.;
231                          for (i = st->ndim; i--; ) {
# Line 157 | Line 237 | SDavgTreBox(const SDNode *st, const double *bmin, cons
237                                  }
238                                  if (sbmin[i] < .0) sbmin[i] = .0;
239                                  if (sbmax[i] > 1.) sbmax[i] = 1.;
240 +                                if (sbmin[i] >= sbmax[i]) {
241 +                                        w = .0;
242 +                                        break;
243 +                                }
244                                  w *= sbmax[i] - sbmin[i];
245                          }
246                          if (w > 1e-10) {
# Line 165 | Line 249 | SDavgTreBox(const SDNode *st, const double *bmin, cons
249                          }
250                  }
251                  return sum / wsum;
252 +        } else {                        /* iterate over leaves */
253 +                int             imin[SD_MAXDIM], imax[SD_MAXDIM];
254 +
255 +                n = 1;
256 +                for (i = st->ndim; i--; ) {
257 +                        imin[i] = (bmin[i] <= 0) ? 0 :
258 +                                        (int)((1 << st->log2GR)*bmin[i]);
259 +                        imax[i] = (bmax[i] >= 1.) ? (1 << st->log2GR) :
260 +                                (int)((1 << st->log2GR)*bmax[i] + .999999);
261 +                        n *= imax[i] - imin[i];
262 +                }
263 +                if (n)
264 +                        return SDiterSum(st->u.v, st->ndim,
265 +                                        st->log2GR, imin, imax) / (double)n;
266          }
267 <        n = 1;                          /* iterate over leaves */
170 <        for (i = st->ndim; i--; ) {
171 <                imin[i] = (bmin[i] <= .0) ? 0
172 <                                : (int)((1 << st->log2GR)*bmin[i]);
173 <                imax[i] = (bmax[i] >= 1.) ? (1 << st->log2GR)
174 <                                : (int)((1 << st->log2GR)*bmax[i] + .999999);
175 <                n *= imax[i] - imin[i];
176 <        }
177 <        if (!n)
178 <                return .0;
179 <        
180 <        return SDiterSum(st->u.v, st->ndim, 1 << st->log2GR, imin, imax) /
181 <                        (double)n;
267 >        return .0;
268   }
269  
270   /* Recursive call for SDtraverseTre() */
# Line 193 | Line 279 | SDdotravTre(const SDNode *st, const double *pos, int c
279                                          /* in branches? */
280          if (st->log2GR < 0) {
281                  unsigned        skipmask = 0;
196
282                  csiz *= .5;
283                  for (i = st->ndim; i--; )
284                          if (1<<i & cmask)
285                                  if (pos[i] < cmin[i] + csiz)
286 <                                        for (n = 1 << st->ndim; n--; )
286 >                                        for (n = 1 << st->ndim; n--; ) {
287                                                  if (n & 1<<i)
288                                                          skipmask |= 1<<n;
289 +                                        }
290                                  else
291 <                                        for (n = 1 << st->ndim; n--; )
291 >                                        for (n = 1 << st->ndim; n--; ) {
292                                                  if (!(n & 1<<i))
293                                                          skipmask |= 1<<n;
294 +                                        }
295                  for (n = 1 << st->ndim; n--; ) {
296                          if (1<<n & skipmask)
297                                  continue;
# Line 238 | Line 325 | SDdotravTre(const SDNode *st, const double *pos, int c
325                                  clim[i][0] = 0;
326                                  clim[i][1] = 1 << st->log2GR;
327                          }
241                                        /* fill in unused dimensions */
242                for (i = SD_MAXDIM; i-- > st->ndim; ) {
243                        clim[i][0] = 0; clim[i][1] = 1;
244                }
328   #if (SD_MAXDIM == 4)
329                  bmin[0] = cmin[0] + csiz*clim[0][0];
330                  for (cpos[0] = clim[0][0]; cpos[0] < clim[0][1]; cpos[0]++) {
331                      bmin[1] = cmin[1] + csiz*clim[1][0];
332                      for (cpos[1] = clim[1][0]; cpos[1] < clim[1][1]; cpos[1]++) {
333                          bmin[2] = cmin[2] + csiz*clim[2][0];
334 <                        for (cpos[2] = clim[2][0]; cpos[2] < clim[2][1]; cpos[2]++) {
335 <                            bmin[3] = cmin[3] + csiz*(cpos[3] = clim[3][0]);
334 >                        if (st->ndim == 3) {
335 >                            cpos[2] = clim[2][0];
336                              n = cpos[0];
337 <                            for (i = 1; i < st->ndim; i++)
337 >                            for (i = 1; i < 3; i++)
338                                  n = (n << st->log2GR) + cpos[i];
339 <                            for ( ; cpos[3] < clim[3][1]; cpos[3]++) {
339 >                            for ( ; cpos[2] < clim[2][1]; cpos[2]++) {
340                                  rval += rv = (*cf)(st->u.v[n++], bmin, csiz, cptr);
341                                  if (rv < 0)
342                                      return rv;
343 <                                bmin[3] += csiz;
343 >                                bmin[2] += csiz;
344                              }
345 <                            bmin[2] += csiz;
345 >                        } else {
346 >                            for (cpos[2] = clim[2][0]; cpos[2] < clim[2][1]; cpos[2]++) {
347 >                                bmin[3] = cmin[3] + csiz*(cpos[3] = clim[3][0]);
348 >                                n = cpos[0];
349 >                                for (i = 1; i < 4; i++)
350 >                                    n = (n << st->log2GR) + cpos[i];
351 >                                for ( ; cpos[3] < clim[3][1]; cpos[3]++) {
352 >                                    rval += rv = (*cf)(st->u.v[n++], bmin, csiz, cptr);
353 >                                    if (rv < 0)
354 >                                        return rv;
355 >                                    bmin[3] += csiz;
356 >                                }
357 >                                bmin[2] += csiz;
358 >                            }
359                          }
360                          bmin[1] += csiz;
361                      }
# Line 334 | Line 430 | SDlookupTre(const SDNode *st, const double *pos, doubl
430   static float
431   SDqueryTre(const SDTre *sdt, const FVECT outVec, const FVECT inVec, double *hc)
432   {
337        static const FVECT      zvec = {.0, .0, 1.};
433          FVECT                   rOutVec;
434          double                  gridPos[4];
435 <                                        /* check transmission */
436 <        if (!sdt->isxmit ^ outVec[2] > 0 ^ inVec[2] > 0)
435 >
436 >        switch (sdt->sidef) {           /* whose side are you on? */
437 >        case SD_UFRONT:
438 >                if ((outVec[2] < 0) | (inVec[2] < 0))
439 >                        return -1.;
440 >                break;
441 >        case SD_UBACK:
442 >                if ((outVec[2] > 0) | (inVec[2] > 0))
443 >                        return -1.;
444 >                break;
445 >        case SD_XMIT:
446 >                if ((outVec[2] > 0) == (inVec[2] > 0))
447 >                        return -1.;
448 >                break;
449 >        default:
450                  return -1.;
451 +        }
452                                          /* convert vector coordinates */
453          if (sdt->st->ndim == 3) {
454 <                spinvector(rOutVec, outVec, zvec, -atan2(inVec[1],inVec[0]));
454 >                spinvector(rOutVec, outVec, zvec, -atan2(-inVec[1],-inVec[0]));
455                  gridPos[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
456                  SDdisk2square(gridPos+1, rOutVec[0], rOutVec[1]);
457          } else if (sdt->st->ndim == 4) {
# Line 383 | Line 492 | build_scaffold(float val, const double *cmin, double c
492                  sp->wmax = wid;
493          if (sp->alen >= sp->nall) {     /* need more space? */
494                  struct outdir_s *ndarr;
495 <                sp->nall += 8192;
495 >                sp->nall += 1024;
496                  ndarr = (struct outdir_s *)realloc(sp->darr,
497                                          sizeof(struct outdir_s)*sp->nall);
498 <                if (ndarr == NULL)
498 >                if (ndarr == NULL) {
499 >                        sprintf(SDerrorDetail,
500 >                                "Cannot grow scaffold to %u entries", sp->nall);
501                          return -1;      /* abort build */
502 +                }
503                  sp->darr = ndarr;
504          }
505                                          /* find Hilbert entry index */
506          bmin[0] = cmin[0]*(double)iwmax + .5;
507          bmin[1] = cmin[1]*(double)iwmax + .5;
508 <        bmax[0] = bmin[0] + wid;
509 <        bmax[1] = bmin[1] + wid;
510 <        hilbert_box_vtx(2, sizeof(bitmask_t), sizeof(unsigned)*4,
511 <                                                        1, bmin, bmax);
400 <        sp->darr[sp->alen].hent = hilbert_c2i(2, sizeof(unsigned)*4, bmin);
508 >        bmax[0] = bmin[0] + wid-1;
509 >        bmax[1] = bmin[1] + wid-1;
510 >        hilbert_box_vtx(2, sizeof(bitmask_t), iwbits, 1, bmin, bmax);
511 >        sp->darr[sp->alen].hent = hilbert_c2i(2, iwbits, bmin);
512          sp->darr[sp->alen].wid = wid;
513          sp->darr[sp->alen].bsdf = val;
514          sp->alen++;                     /* on to the next entry */
# Line 408 | Line 519 | build_scaffold(float val, const double *cmin, double c
519   static int
520   sscmp(const void *p1, const void *p2)
521   {
522 <        return (int)((*(const struct outdir_s *)p1).hent -
523 <                        (*(const struct outdir_s *)p2).hent);
522 >        unsigned        h1 = (*(const struct outdir_s *)p1).hent;
523 >        unsigned        h2 = (*(const struct outdir_s *)p2).hent;
524 >
525 >        if (h1 > h2)
526 >                return 1;
527 >        if (h1 < h2)
528 >                return -1;
529 >        return 0;
530   }
531  
532   /* Create a new cumulative distribution for the given input direction */
533   static SDTreCDst *
534   make_cdist(const SDTre *sdt, const double *pos)
535   {
419        const unsigned  cumlmax = ~0;
536          SDdistScaffold  myScaffold;
537          SDTreCDst       *cd;
538          struct outdir_s *sp;
# Line 427 | Line 543 | make_cdist(const SDTre *sdt, const double *pos)
543          myScaffold.wmax = 0;
544          myScaffold.nic = sdt->st->ndim - 2;
545          myScaffold.alen = 0;
546 <        myScaffold.nall = 8192;
546 >        myScaffold.nall = 512;
547          myScaffold.darr = (struct outdir_s *)malloc(sizeof(struct outdir_s) *
548                                                          myScaffold.nall);
549          if (myScaffold.darr == NULL)
# Line 442 | Line 558 | make_cdist(const SDTre *sdt, const double *pos)
558          cd = (SDTreCDst *)malloc(sizeof(SDTreCDst) +
559                                  sizeof(cd->carr[0])*myScaffold.alen);
560          if (cd == NULL) {
561 +                sprintf(SDerrorDetail,
562 +                        "Cannot allocate %u entry cumulative distribution",
563 +                                myScaffold.alen);
564                  free(myScaffold.darr);
565                  return NULL;
566          }
567 +        cd->isodist = (myScaffold.nic == 1);
568                                          /* sort the distribution */
569          qsort(myScaffold.darr, cd->calen = myScaffold.alen,
570                                  sizeof(struct outdir_s), &sscmp);
571  
572                                          /* record input range */
573 <        scale = (double)myScaffold.wmin / iwmax;
573 >        scale = myScaffold.wmin / (double)iwmax;
574          for (i = myScaffold.nic; i--; ) {
575 <                cd->clim[i][0] = floor(pos[i]/scale + .5) * scale;
575 >                cd->clim[i][0] = floor(pos[i]/scale) * scale;
576                  cd->clim[i][1] = cd->clim[i][0] + scale;
577          }
578 +        if (cd->isodist) {              /* avoid issue in SDqueryTreProjSA() */
579 +                cd->clim[1][0] = cd->clim[0][0];
580 +                cd->clim[1][1] = cd->clim[0][1];
581 +        }
582          cd->max_psa = myScaffold.wmax / (double)iwmax;
583          cd->max_psa *= cd->max_psa * M_PI;
584 <        cd->isxmit = sdt->isxmit;
584 >        cd->sidef = sdt->sidef;
585          cd->cTotal = 1e-20;             /* compute directional total */
586          sp = myScaffold.darr;
587          for (i = myScaffold.alen; i--; sp++)
# Line 466 | Line 590 | make_cdist(const SDTre *sdt, const double *pos)
590          scale = (double)cumlmax / cd->cTotal;
591          sp = myScaffold.darr;
592          for (i = 0; i < cd->calen; i++, sp++) {
593 +                cd->carr[i].hndx = sp->hent;
594                  cd->carr[i].cuml = scale*cursum + .5;
595                  cursum += sp->bsdf * (double)sp->wid * sp->wid;
596          }
# Line 482 | Line 607 | const SDCDst *
607   SDgetTreCDist(const FVECT inVec, SDComponent *sdc)
608   {
609          const SDTre     *sdt;
610 <        double          inCoord[2];
486 <        int             vflags;
610 >        double          inCoord[2], quantum;
611          int             i;
612          SDTreCDst       *cd, *cdlast;
613                                          /* check arguments */
614          if ((inVec == NULL) | (sdc == NULL) ||
615                          (sdt = (SDTre *)sdc->dist) == NULL)
616                  return NULL;
617 <        if (sdt->st->ndim == 3)         /* isotropic BSDF? */
617 >        if (sdt->st->ndim == 3) {       /* isotropic BSDF? */
618                  inCoord[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
619 <        else if (sdt->st->ndim == 4)
619 >        } else if (sdt->st->ndim == 4) {
620                  SDdisk2square(inCoord, -inVec[0], -inVec[1]);
621 <        else
621 >        } else
622                  return NULL;            /* should be internal error */
623 +                                        /* quantize to avoid f.p. errors */
624 +        quantum = SDsmallestLeaf(sdt->st);
625 +        for (i = sdt->st->ndim - 2; i--; )
626 +                inCoord[i] = floor(inCoord[i]/quantum)*quantum + .5*quantum;
627          cdlast = NULL;                  /* check for direction in cache list */
628          for (cd = (SDTreCDst *)sdc->cdList; cd != NULL;
629 <                                cdlast = cd, cd = (SDTreCDst *)cd->next) {
629 >                                        cdlast = cd, cd = cd->next) {
630                  for (i = sdt->st->ndim - 2; i--; )
631                          if ((cd->clim[i][0] > inCoord[i]) |
632                                          (inCoord[i] >= cd->clim[i][1]))
# Line 510 | Line 638 | SDgetTreCDist(const FVECT inVec, SDComponent *sdc)
638                  cdlast = cd = make_cdist(sdt, inCoord);
639          if (cdlast != NULL) {           /* move entry to head of cache list */
640                  cdlast->next = cd->next;
641 <                cd->next = sdc->cdList;
641 >                cd->next = (SDTreCDst *)sdc->cdList;
642                  sdc->cdList = (SDCDst *)cd;
643          }
644          return (SDCDst *)cd;            /* ready to go */
# Line 531 | Line 659 | SDqueryTreProjSA(double *psa, const FVECT v1, const RR
659                  const SDTre     *sdt = (SDTre *)sdc->dist;
660                  double          hcube[SD_MAXDIM];
661                  if (SDqueryTre(sdt, v1, v2, hcube) < 0) {
662 <                        if (qflags == SDqueryVal)
663 <                                *psa = M_PI;
536 <                        return SDEnone;
662 >                        strcpy(SDerrorDetail, "Bad call to SDqueryTreProjSA");
663 >                        return SDEinternal;
664                  }
665                  myPSA[0] = hcube[sdt->st->ndim];
666                  myPSA[1] = myPSA[0] *= myPSA[0] * M_PI;
# Line 571 | Line 698 | SDsampTreCDist(FVECT ioVec, double randX, const SDCDst
698   {
699          const unsigned  nBitsC = 4*sizeof(bitmask_t);
700          const unsigned  nExtraBits = 8*(sizeof(bitmask_t)-sizeof(unsigned));
574        const unsigned  maxval = ~0;
701          const SDTreCDst *cd = (const SDTreCDst *)cdp;
702 <        const unsigned  target = randX*maxval;
702 >        const unsigned  target = randX*cumlmax;
703          bitmask_t       hndx, hcoord[2];
704 <        double          gpos[3];
704 >        double          gpos[3], rotangle;
705          int             i, iupper, ilower;
706                                          /* check arguments */
707          if ((ioVec == NULL) | (cd == NULL))
708                  return SDEargument;
709 +        if (ioVec[2] > 0) {
710 +                if (!(cd->sidef & SD_UFRONT))
711 +                        return SDEargument;
712 +        } else if (!(cd->sidef & SD_UBACK))
713 +                return SDEargument;
714                                          /* binary search to find position */
715          ilower = 0; iupper = cd->calen;
716          while ((i = (iupper + ilower) >> 1) != ilower)
717 <                if ((long)target >= (long)cd->carr[i].cuml)
717 >                if (target >= cd->carr[i].cuml)
718                          ilower = i;
719                  else
720                          iupper = i;
721                                          /* localize random position */
722 <        randX = (randX*maxval - cd->carr[ilower].cuml) /
722 >        randX = (randX*cumlmax - cd->carr[ilower].cuml) /
723                      (double)(cd->carr[iupper].cuml - cd->carr[ilower].cuml);
724                                          /* index in longer Hilbert curve */
725          hndx = (randX*cd->carr[iupper].hndx + (1.-randX)*cd->carr[ilower].hndx)
# Line 599 | Line 730 | SDsampTreCDist(FVECT ioVec, double randX, const SDCDst
730                  gpos[i] = ((double)hcoord[i] + rand()*(1./(RAND_MAX+.5))) /
731                                  (double)((bitmask_t)1 << nBitsC);
732          SDsquare2disk(gpos, gpos[0], gpos[1]);
733 +                                        /* compute Z-coordinate */
734          gpos[2] = 1. - gpos[0]*gpos[0] - gpos[1]*gpos[1];
735          if (gpos[2] > 0)                /* paranoia, I hope */
736                  gpos[2] = sqrt(gpos[2]);
737 <        if (ioVec[2] > 0 ^ !cd->isxmit)
737 >                                        /* emit from back? */
738 >        if (ioVec[2] > 0 ^ cd->sidef != SD_XMIT)
739                  gpos[2] = -gpos[2];
740 <        VCOPY(ioVec, gpos);
740 >        if (cd->isodist) {              /* rotate isotropic result */
741 >                rotangle = atan2(-ioVec[1],-ioVec[0]);
742 >                VCOPY(ioVec, gpos);
743 >                spinvector(ioVec, ioVec, zvec, rotangle);
744 >        } else
745 >                VCOPY(ioVec, gpos);
746          return SDEnone;
747   }
748  
749 + /* Advance pointer to the next non-white character in the string (or nul) */
750 + static int
751 + next_token(char **spp)
752 + {
753 +        while (isspace(**spp))
754 +                ++*spp;
755 +        return **spp;
756 + }
757 +
758 + /* Advance pointer past matching token (or any token if c==0) */
759 + #define eat_token(spp,c)        (next_token(spp)==(c) ^ !(c) ? *(*(spp))++ : 0)
760 +
761 + /* Count words from this point in string to '}' */
762 + static int
763 + count_values(char *cp)
764 + {
765 +        int     n = 0;
766 +
767 +        while (next_token(&cp) != '}' && *cp) {
768 +                while (!isspace(*cp) & (*cp != ',') & (*cp != '}'))
769 +                        if (!*++cp)
770 +                                break;
771 +                ++n;
772 +                eat_token(&cp, ',');
773 +        }
774 +        return n;
775 + }
776 +
777 + /* Load an array of real numbers, returning total */
778 + static int
779 + load_values(char **spp, float *va, int n)
780 + {
781 +        float   *v = va;
782 +        char    *svnext;
783 +
784 +        while (n-- > 0 && (svnext = fskip(*spp)) != NULL) {
785 +                *v++ = atof(*spp);
786 +                *spp = svnext;
787 +                eat_token(spp, ',');
788 +        }
789 +        return v - va;
790 + }
791 +
792 + /* Load BSDF tree data */
793 + static SDNode *
794 + load_tree_data(char **spp, int nd)
795 + {
796 +        SDNode  *st;
797 +        int     n;
798 +
799 +        if (!eat_token(spp, '{')) {
800 +                strcpy(SDerrorDetail, "Missing '{' in tensor tree");
801 +                return NULL;
802 +        }
803 +        if (next_token(spp) == '{') {   /* tree branches */
804 +                st = SDnewNode(nd, -1);
805 +                if (st == NULL)
806 +                        return NULL;
807 +                for (n = 0; n < 1<<nd; n++)
808 +                        if ((st->u.t[n] = load_tree_data(spp, nd)) == NULL) {
809 +                                SDfreeTre(st);
810 +                                return NULL;
811 +                        }
812 +        } else {                        /* else load value grid */
813 +                int     bsiz;
814 +                n = count_values(*spp); /* see how big the grid is */
815 +                for (bsiz = 0; bsiz < 8*sizeof(size_t); bsiz += nd)
816 +                        if (1<<bsiz == n)
817 +                                break;
818 +                if (bsiz >= 8*sizeof(size_t)) {
819 +                        strcpy(SDerrorDetail, "Illegal value count in tensor tree");
820 +                        return NULL;
821 +                }
822 +                st = SDnewNode(nd, bsiz/nd);
823 +                if (st == NULL)
824 +                        return NULL;
825 +                if (load_values(spp, st->u.v, n) != n) {
826 +                        strcpy(SDerrorDetail, "Real format error in tensor tree");
827 +                        SDfreeTre(st);
828 +                        return NULL;
829 +                }
830 +        }
831 +        if (!eat_token(spp, '}')) {
832 +                strcpy(SDerrorDetail, "Missing '}' in tensor tree");
833 +                SDfreeTre(st);
834 +                return NULL;
835 +        }
836 +        eat_token(spp, ',');
837 +        return st;
838 + }
839 +
840 + /* Compute min. proj. solid angle and max. direct hemispherical scattering */
841 + static SDError
842 + get_extrema(SDSpectralDF *df)
843 + {
844 +        SDNode  *st = (*(SDTre *)df->comp[0].dist).st;
845 +        double  stepWidth, dhemi, bmin[4], bmax[4];
846 +
847 +        stepWidth = SDsmallestLeaf(st);
848 +        df->minProjSA = M_PI*stepWidth*stepWidth;
849 +        if (stepWidth < .03125)
850 +                stepWidth = .03125;     /* 1/32 resolution good enough */
851 +        df->maxHemi = .0;
852 +        if (st->ndim == 3) {            /* isotropic BSDF */
853 +                bmin[1] = bmin[2] = .0;
854 +                bmax[1] = bmax[2] = 1.;
855 +                for (bmin[0] = .0; bmin[0] < .5-FTINY; bmin[0] += stepWidth) {
856 +                        bmax[0] = bmin[0] + stepWidth;
857 +                        dhemi = SDavgTreBox(st, bmin, bmax);
858 +                        if (dhemi > df->maxHemi)
859 +                                df->maxHemi = dhemi;
860 +                }
861 +        } else if (st->ndim == 4) {     /* anisotropic BSDF */
862 +                bmin[2] = bmin[3] = .0;
863 +                bmax[2] = bmax[3] = 1.;
864 +                for (bmin[0] = .0; bmin[0] < 1.-FTINY; bmin[0] += stepWidth) {
865 +                        bmax[0] = bmin[0] + stepWidth;
866 +                        for (bmin[1] = .0; bmin[1] < 1.-FTINY; bmin[1] += stepWidth) {
867 +                                bmax[1] = bmin[1] + stepWidth;
868 +                                dhemi = SDavgTreBox(st, bmin, bmax);
869 +                                if (dhemi > df->maxHemi)
870 +                                        df->maxHemi = dhemi;
871 +                        }
872 +                }
873 +        } else
874 +                return SDEinternal;
875 +                                        /* correct hemispherical value */
876 +        df->maxHemi *= M_PI;
877 +        return SDEnone;
878 + }
879 +
880 + /* Load BSDF distribution for this wavelength */
881 + static SDError
882 + load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
883 + {
884 +        SDSpectralDF    *df;
885 +        SDTre           *sdt;
886 +        char            *sdata;
887 +                                        /* allocate BSDF component */
888 +        sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
889 +        if (!sdata)
890 +                return SDEnone;
891 +        /*
892 +         * Remember that front and back are reversed from WINDOW 6 orientations
893 +         */
894 +        if (!strcasecmp(sdata, "Transmission")) {
895 +                if (sd->tf != NULL)
896 +                        SDfreeSpectralDF(sd->tf);
897 +                if ((sd->tf = SDnewSpectralDF(1)) == NULL)
898 +                        return SDEmemory;
899 +                df = sd->tf;
900 +        } else if (!strcasecmp(sdata, "Reflection Front")) {
901 +                if (sd->rb != NULL)     /* note back-front reversal */
902 +                        SDfreeSpectralDF(sd->rb);
903 +                if ((sd->rb = SDnewSpectralDF(1)) == NULL)
904 +                        return SDEmemory;
905 +                df = sd->rb;
906 +        } else if (!strcasecmp(sdata, "Reflection Back")) {
907 +                if (sd->rf != NULL)     /* note front-back reversal */
908 +                        SDfreeSpectralDF(sd->rf);
909 +                if ((sd->rf = SDnewSpectralDF(1)) == NULL)
910 +                        return SDEmemory;
911 +                df = sd->rf;
912 +        } else
913 +                return SDEnone;
914 +        /* XXX should also check "ScatteringDataType" for consistency? */
915 +                                        /* get angle bases */
916 +        sdata = ezxml_txt(ezxml_child(wdb,"AngleBasis"));
917 +        if (!sdata || strcasecmp(sdata, "LBNL/Shirley-Chiu")) {
918 +                sprintf(SDerrorDetail, "%s angle basis for BSDF '%s'",
919 +                                !sdata ? "Missing" : "Unsupported", sd->name);
920 +                return !sdata ? SDEformat : SDEsupport;
921 +        }
922 +                                        /* allocate BSDF tree */
923 +        sdt = (SDTre *)malloc(sizeof(SDTre));
924 +        if (sdt == NULL)
925 +                return SDEmemory;
926 +        if (df == sd->rf)
927 +                sdt->sidef = SD_UFRONT;
928 +        else if (df == sd->rb)
929 +                sdt->sidef = SD_UBACK;
930 +        else
931 +                sdt->sidef = SD_XMIT;
932 +        sdt->st = NULL;
933 +        df->comp[0].cspec[0] = c_dfcolor; /* XXX monochrome for now */
934 +        df->comp[0].dist = sdt;
935 +        df->comp[0].func = &SDhandleTre;
936 +                                        /* read BSDF data */
937 +        sdata = ezxml_txt(ezxml_child(wdb, "ScatteringData"));
938 +        if (!sdata || !next_token(&sdata)) {
939 +                sprintf(SDerrorDetail, "Missing BSDF ScatteringData in '%s'",
940 +                                sd->name);
941 +                return SDEformat;
942 +        }
943 +        sdt->st = load_tree_data(&sdata, ndim);
944 +        if (sdt->st == NULL)
945 +                return SDEformat;
946 +        if (next_token(&sdata)) {       /* check for unconsumed characters */
947 +                sprintf(SDerrorDetail,
948 +                        "Extra characters at end of ScatteringData in '%s'",
949 +                                sd->name);
950 +                return SDEformat;
951 +        }
952 +                                        /* flatten branches where possible */
953 +        sdt->st = SDsimplifyTre(sdt->st);
954 +        if (sdt->st == NULL)
955 +                return SDEinternal;
956 +        return get_extrema(df);         /* compute global quantities */
957 + }
958 +
959 + /* Find minimum value in tree */
960 + static float
961 + SDgetTreMin(const SDNode *st)
962 + {
963 +        float   vmin = FHUGE;
964 +        int     n;
965 +
966 +        if (st->log2GR < 0) {
967 +                for (n = 1<<st->ndim; n--; ) {
968 +                        float   v = SDgetTreMin(st->u.t[n]);
969 +                        if (v < vmin)
970 +                                vmin = v;
971 +                }
972 +        } else {
973 +                for (n = 1<<(st->ndim*st->log2GR); n--; )
974 +                        if (st->u.v[n] < vmin)
975 +                                vmin = st->u.v[n];
976 +        }
977 +        return vmin;
978 + }
979 +
980 + /* Subtract the given value from all tree nodes */
981 + static void
982 + SDsubtractTreVal(SDNode *st, float val)
983 + {
984 +        int     n;
985 +
986 +        if (st->log2GR < 0) {
987 +                for (n = 1<<st->ndim; n--; )
988 +                        SDsubtractTreVal(st->u.t[n], val);
989 +        } else {
990 +                for (n = 1<<(st->ndim*st->log2GR); n--; )
991 +                        if ((st->u.v[n] -= val) < 0)
992 +                                st->u.v[n] = .0f;
993 +        }
994 + }
995 +
996 + /* Subtract minimum value from BSDF */
997 + static double
998 + subtract_min(SDNode *st)
999 + {
1000 +        float   vmin;
1001 +                                        /* be sure to skip unused portion */
1002 +        if (st->ndim == 3) {
1003 +                int     n;
1004 +                vmin = 1./M_PI;
1005 +                if (st->log2GR < 0) {
1006 +                        for (n = 0; n < 8; n += 2) {
1007 +                                float   v = SDgetTreMin(st->u.t[n]);
1008 +                                if (v < vmin)
1009 +                                        vmin = v;
1010 +                        }
1011 +                } else if (st->log2GR) {
1012 +                        for (n = 1 << (3*st->log2GR - 1); n--; )
1013 +                                if (st->u.v[n] < vmin)
1014 +                                        vmin = st->u.v[n];
1015 +                } else
1016 +                        vmin = st->u.v[0];
1017 +        } else                          /* anisotropic covers entire tree */
1018 +                vmin = SDgetTreMin(st);
1019 +
1020 +        if (vmin <= FTINY)
1021 +                return .0;
1022 +
1023 +        SDsubtractTreVal(st, vmin);
1024 +
1025 +        return M_PI * vmin;             /* return hemispherical value */
1026 + }
1027 +
1028 + /* Extract and separate diffuse portion of BSDF */
1029 + static void
1030 + extract_diffuse(SDValue *dv, SDSpectralDF *df)
1031 + {
1032 +        int     n;
1033 +
1034 +        if (df == NULL || df->ncomp <= 0) {
1035 +                dv->spec = c_dfcolor;
1036 +                dv->cieY = .0;
1037 +                return;
1038 +        }
1039 +        dv->spec = df->comp[0].cspec[0];
1040 +        dv->cieY = subtract_min((*(SDTre *)df->comp[0].dist).st);
1041 +                                        /* in case of multiple components */
1042 +        for (n = df->ncomp; --n; ) {
1043 +                double  ymin = subtract_min((*(SDTre *)df->comp[n].dist).st);
1044 +                c_cmix(&dv->spec, dv->cieY, &dv->spec, ymin, &df->comp[n].cspec[0]);
1045 +                dv->cieY += ymin;
1046 +        }
1047 +        df->maxHemi -= dv->cieY;        /* adjust maximum hemispherical */
1048 +                                        /* make sure everything is set */
1049 +        c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
1050 + }
1051 +
1052   /* Load a variable-resolution BSDF tree from an open XML file */
1053   SDError
1054   SDloadTre(SDData *sd, ezxml_t wtl)
1055   {
1056 <        return SDEsupport;
1056 >        SDError         ec;
1057 >        ezxml_t         wld, wdb;
1058 >        int             rank;
1059 >        char            *txt;
1060 >                                        /* basic checks and tensor rank */
1061 >        txt = ezxml_txt(ezxml_child(ezxml_child(wtl,
1062 >                        "DataDefinition"), "IncidentDataStructure"));
1063 >        if (txt == NULL || !*txt) {
1064 >                sprintf(SDerrorDetail,
1065 >                        "BSDF \"%s\": missing IncidentDataStructure",
1066 >                                sd->name);
1067 >                return SDEformat;
1068 >        }
1069 >        if (!strcasecmp(txt, "TensorTree3"))
1070 >                rank = 3;
1071 >        else if (!strcasecmp(txt, "TensorTree4"))
1072 >                rank = 4;
1073 >        else {
1074 >                sprintf(SDerrorDetail,
1075 >                        "BSDF \"%s\": unsupported IncidentDataStructure",
1076 >                                sd->name);
1077 >                return SDEsupport;
1078 >        }
1079 >                                        /* load BSDF components */
1080 >        for (wld = ezxml_child(wtl, "WavelengthData");
1081 >                                wld != NULL; wld = wld->next) {
1082 >                if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1083 >                                "Visible"))
1084 >                        continue;       /* just visible for now */
1085 >                for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1086 >                                        wdb != NULL; wdb = wdb->next)
1087 >                        if ((ec = load_bsdf_data(sd, wdb, rank)) != SDEnone)
1088 >                                return ec;
1089 >        }
1090 >                                        /* separate diffuse components */
1091 >        extract_diffuse(&sd->rLambFront, sd->rf);
1092 >        extract_diffuse(&sd->rLambBack, sd->rb);
1093 >        extract_diffuse(&sd->tLamb, sd->tf);
1094 >                                        /* return success */
1095 >        return SDEnone;
1096   }
1097  
1098   /* Variable resolution BSDF methods */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines