ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf.c
Revision: 2.22
Committed: Tue Apr 19 21:31:22 2011 UTC (13 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.21: +9 -8 lines
Log Message:
Fixed interface for determining BSDF solid angles

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.22 static const char RCSid[] = "$Id: bsdf.c,v 2.21 2011/04/17 17:45:13 greg Exp $";
3 greg 2.1 #endif
4     /*
5 greg 2.15 * bsdf.c
6     *
7     * Definitions for bidirectional scattering distribution functions.
8     *
9     * Created by Greg Ward on 1/10/11.
10     *
11     */
12    
13     #include <stdio.h>
14     #include <stdlib.h>
15     #include <math.h>
16     #include "ezxml.h"
17     #include "hilbert.h"
18     #include "bsdf.h"
19     #include "bsdf_m.h"
20     #include "bsdf_t.h"
21    
22     /* English ASCII strings corresponding to ennumerated errors */
23     const char *SDerrorEnglish[] = {
24     "No error",
25     "Memory error",
26     "File input/output error",
27     "File format error",
28     "Illegal argument",
29     "Invalid data",
30     "Unsupported feature",
31     "Internal program error",
32     "Unknown error"
33     };
34    
35     /* Additional information on last error (ASCII English) */
36     char SDerrorDetail[256];
37    
38     /* Cache of loaded BSDFs */
39     struct SDCache_s *SDcacheList = NULL;
40    
41     /* Retain BSDFs in cache list */
42     int SDretainSet = SDretainNone;
43    
44     /* Report any error to the indicated stream (in English) */
45     SDError
46     SDreportEnglish(SDError ec, FILE *fp)
47     {
48 greg 2.21 if (!ec)
49     return SDEnone;
50     if ((ec < SDEnone) | (ec > SDEunknown)) {
51     SDerrorDetail[0] = '\0';
52     ec = SDEunknown;
53     }
54 greg 2.15 if (fp == NULL)
55     return ec;
56     fputs(SDerrorEnglish[ec], fp);
57     if (SDerrorDetail[0]) {
58     fputs(": ", fp);
59     fputs(SDerrorDetail, fp);
60     }
61     fputc('\n', fp);
62     if (fp != stderr)
63     fflush(fp);
64     return ec;
65     }
66    
67     static double
68     to_meters( /* return factor to convert given unit to meters */
69     const char *unit
70     )
71     {
72     if (unit == NULL) return(1.); /* safe assumption? */
73     if (!strcasecmp(unit, "Meter")) return(1.);
74     if (!strcasecmp(unit, "Foot")) return(.3048);
75     if (!strcasecmp(unit, "Inch")) return(.0254);
76     if (!strcasecmp(unit, "Centimeter")) return(.01);
77     if (!strcasecmp(unit, "Millimeter")) return(.001);
78     sprintf(SDerrorDetail, "Unknown dimensional unit '%s'", unit);
79     return(-1.);
80     }
81    
82     /* Load geometric dimensions and description (if any) */
83     static SDError
84 greg 2.16 SDloadGeometry(SDData *sd, ezxml_t wdb)
85 greg 2.15 {
86     ezxml_t geom;
87     double cfact;
88     const char *fmt, *mgfstr;
89    
90 greg 2.16 if (wdb == NULL) /* no geometry section? */
91     return SDEnone;
92     sd->dim[0] = sd->dim[1] = sd->dim[2] = .0;
93 greg 2.15 if ((geom = ezxml_child(wdb, "Width")) != NULL)
94 greg 2.16 sd->dim[0] = atof(ezxml_txt(geom)) *
95 greg 2.15 to_meters(ezxml_attr(geom, "unit"));
96     if ((geom = ezxml_child(wdb, "Height")) != NULL)
97 greg 2.16 sd->dim[1] = atof(ezxml_txt(geom)) *
98 greg 2.15 to_meters(ezxml_attr(geom, "unit"));
99     if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
100 greg 2.16 sd->dim[2] = atof(ezxml_txt(geom)) *
101 greg 2.15 to_meters(ezxml_attr(geom, "unit"));
102 greg 2.17 if ((sd->dim[0] < .0) | (sd->dim[1] < .0) | (sd->dim[2] < .0)) {
103     sprintf(SDerrorDetail, "Negative size in \"%s\"", sd->name);
104 greg 2.15 return SDEdata;
105 greg 2.17 }
106 greg 2.15 if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
107     (mgfstr = ezxml_txt(geom)) == NULL)
108     return SDEnone;
109     if ((fmt = ezxml_attr(geom, "format")) != NULL &&
110     strcasecmp(fmt, "MGF")) {
111     sprintf(SDerrorDetail,
112     "Unrecognized geometry format '%s' in \"%s\"",
113 greg 2.16 fmt, sd->name);
114 greg 2.15 return SDEsupport;
115     }
116     cfact = to_meters(ezxml_attr(geom, "unit"));
117 greg 2.16 sd->mgf = (char *)malloc(strlen(mgfstr)+32);
118     if (sd->mgf == NULL) {
119 greg 2.15 strcpy(SDerrorDetail, "Out of memory in SDloadGeometry");
120     return SDEmemory;
121     }
122     if (cfact < 0.99 || cfact > 1.01)
123 greg 2.16 sprintf(sd->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
124 greg 2.15 else
125 greg 2.16 strcpy(sd->mgf, mgfstr);
126 greg 2.15 return SDEnone;
127     }
128    
129     /* Load a BSDF struct from the given file (free first and keep name) */
130     SDError
131     SDloadFile(SDData *sd, const char *fname)
132     {
133     SDError lastErr;
134 greg 2.16 ezxml_t fl, wtl;
135 greg 2.15
136     if ((sd == NULL) | (fname == NULL || !*fname))
137     return SDEargument;
138     /* free old data, keeping name */
139     SDfreeBSDF(sd);
140     /* parse XML file */
141     fl = ezxml_parse_file(fname);
142     if (fl == NULL) {
143     sprintf(SDerrorDetail, "Cannot open BSDF \"%s\"", fname);
144     return SDEfile;
145     }
146     if (ezxml_error(fl)[0]) {
147     sprintf(SDerrorDetail, "BSDF \"%s\" %s", fname, ezxml_error(fl));
148     ezxml_free(fl);
149     return SDEformat;
150     }
151 greg 2.16 if (strcmp(ezxml_name(fl), "WindowElement")) {
152     sprintf(SDerrorDetail,
153     "BSDF \"%s\": top level node not 'WindowElement'",
154     sd->name);
155     ezxml_free(fl);
156     return SDEformat;
157     }
158     wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
159     if (wtl == NULL) {
160     sprintf(SDerrorDetail, "BSDF \"%s\": no optical layer'",
161     sd->name);
162     ezxml_free(fl);
163     return SDEformat;
164     }
165 greg 2.15 /* load geometry if present */
166 greg 2.16 lastErr = SDloadGeometry(sd, ezxml_child(wtl, "Material"));
167     if (lastErr)
168 greg 2.15 return lastErr;
169     /* try loading variable resolution data */
170 greg 2.16 lastErr = SDloadTre(sd, wtl);
171 greg 2.15 /* check our result */
172     switch (lastErr) {
173     case SDEformat:
174     case SDEdata:
175     case SDEsupport: /* possibly we just tried the wrong format */
176 greg 2.16 lastErr = SDloadMtx(sd, wtl);
177 greg 2.15 break;
178     default: /* variable res. OK else serious error */
179     break;
180     }
181     /* done with XML file */
182     ezxml_free(fl);
183 greg 2.16
184     if (lastErr) { /* was there a load error? */
185     SDfreeBSDF(sd);
186     return lastErr;
187     }
188     /* remove any insignificant components */
189     if (sd->rf != NULL && sd->rf->maxHemi <= .001) {
190     SDfreeSpectralDF(sd->rf); sd->rf = NULL;
191     }
192     if (sd->rb != NULL && sd->rb->maxHemi <= .001) {
193     SDfreeSpectralDF(sd->rb); sd->rb = NULL;
194     }
195     if (sd->tf != NULL && sd->tf->maxHemi <= .001) {
196     SDfreeSpectralDF(sd->tf); sd->tf = NULL;
197     }
198     /* return success */
199     return SDEnone;
200 greg 2.15 }
201    
202     /* Allocate new spectral distribution function */
203     SDSpectralDF *
204     SDnewSpectralDF(int nc)
205     {
206     SDSpectralDF *df;
207    
208     if (nc <= 0) {
209     strcpy(SDerrorDetail, "Zero component spectral DF request");
210     return NULL;
211     }
212     df = (SDSpectralDF *)malloc(sizeof(SDSpectralDF) +
213     (nc-1)*sizeof(SDComponent));
214     if (df == NULL) {
215     sprintf(SDerrorDetail,
216     "Cannot allocate %d component spectral DF", nc);
217     return NULL;
218     }
219     df->minProjSA = .0;
220     df->maxHemi = .0;
221     df->ncomp = nc;
222     memset(df->comp, 0, nc*sizeof(SDComponent));
223     return df;
224     }
225    
226     /* Free cached cumulative distributions for BSDF component */
227     void
228     SDfreeCumulativeCache(SDSpectralDF *df)
229     {
230     int n;
231     SDCDst *cdp;
232    
233     if (df == NULL)
234     return;
235     for (n = df->ncomp; n-- > 0; )
236     while ((cdp = df->comp[n].cdList) != NULL) {
237     df->comp[n].cdList = cdp->next;
238     free(cdp);
239     }
240     }
241    
242     /* Free a spectral distribution function */
243     void
244     SDfreeSpectralDF(SDSpectralDF *df)
245     {
246     int n;
247    
248     if (df == NULL)
249     return;
250     SDfreeCumulativeCache(df);
251     for (n = df->ncomp; n-- > 0; )
252     (*df->comp[n].func->freeSC)(df->comp[n].dist);
253     free(df);
254     }
255    
256     /* Shorten file path to useable BSDF name, removing suffix */
257     void
258 greg 2.16 SDclipName(char *res, const char *fname)
259 greg 2.15 {
260     const char *cp, *dot = NULL;
261    
262     for (cp = fname; *cp; cp++)
263     if (*cp == '.')
264     dot = cp;
265     if ((dot == NULL) | (dot < fname+2))
266     dot = cp;
267     if (dot - fname >= SDnameLn)
268     fname = dot - SDnameLn + 1;
269     while (fname < dot)
270     *res++ = *fname++;
271     *res = '\0';
272     }
273    
274     /* Initialize an unused BSDF struct (simply clears to zeroes) */
275     void
276 greg 2.20 SDclearBSDF(SDData *sd, const char *fname)
277 greg 2.15 {
278 greg 2.20 if (sd == NULL)
279     return;
280     memset(sd, 0, sizeof(SDData));
281     if (fname == NULL)
282     return;
283     SDclipName(sd->name, fname);
284 greg 2.15 }
285    
286     /* Free data associated with BSDF struct */
287     void
288     SDfreeBSDF(SDData *sd)
289     {
290     if (sd == NULL)
291     return;
292     if (sd->mgf != NULL) {
293     free(sd->mgf);
294     sd->mgf = NULL;
295     }
296     if (sd->rf != NULL) {
297     SDfreeSpectralDF(sd->rf);
298     sd->rf = NULL;
299     }
300     if (sd->rb != NULL) {
301     SDfreeSpectralDF(sd->rb);
302     sd->rb = NULL;
303     }
304     if (sd->tf != NULL) {
305     SDfreeSpectralDF(sd->tf);
306     sd->tf = NULL;
307     }
308     sd->rLambFront.cieY = .0;
309 greg 2.16 sd->rLambFront.spec.flags = 0;
310 greg 2.15 sd->rLambBack.cieY = .0;
311 greg 2.16 sd->rLambBack.spec.flags = 0;
312 greg 2.15 sd->tLamb.cieY = .0;
313 greg 2.16 sd->tLamb.spec.flags = 0;
314 greg 2.15 }
315    
316     /* Find writeable BSDF by name, or allocate new cache entry if absent */
317     SDData *
318     SDgetCache(const char *bname)
319     {
320     struct SDCache_s *sdl;
321     char sdnam[SDnameLn];
322    
323     if (bname == NULL)
324     return NULL;
325    
326     SDclipName(sdnam, bname);
327     for (sdl = SDcacheList; sdl != NULL; sdl = sdl->next)
328     if (!strcmp(sdl->bsdf.name, sdnam)) {
329     sdl->refcnt++;
330     return &sdl->bsdf;
331     }
332    
333     sdl = (struct SDCache_s *)calloc(1, sizeof(struct SDCache_s));
334     if (sdl == NULL)
335     return NULL;
336    
337     strcpy(sdl->bsdf.name, sdnam);
338     sdl->next = SDcacheList;
339     SDcacheList = sdl;
340    
341 greg 2.21 sdl->refcnt = 1;
342 greg 2.15 return &sdl->bsdf;
343     }
344    
345     /* Get loaded BSDF from cache (or load and cache it on first call) */
346     /* Report any problem to stderr and return NULL on failure */
347     const SDData *
348     SDcacheFile(const char *fname)
349     {
350     SDData *sd;
351     SDError ec;
352    
353     if (fname == NULL || !*fname)
354     return NULL;
355     SDerrorDetail[0] = '\0';
356     if ((sd = SDgetCache(fname)) == NULL) {
357     SDreportEnglish(SDEmemory, stderr);
358     return NULL;
359     }
360     if (!SDisLoaded(sd) && (ec = SDloadFile(sd, fname))) {
361     SDreportEnglish(ec, stderr);
362     SDfreeCache(sd);
363     return NULL;
364     }
365     return sd;
366     }
367    
368     /* Free a BSDF from our cache (clear all if NULL) */
369     void
370     SDfreeCache(const SDData *sd)
371     {
372     struct SDCache_s *sdl, *sdLast = NULL;
373    
374     if (sd == NULL) { /* free entire list */
375     while ((sdl = SDcacheList) != NULL) {
376     SDcacheList = sdl->next;
377     SDfreeBSDF(&sdl->bsdf);
378     free(sdl);
379     }
380     return;
381     }
382     for (sdl = SDcacheList; sdl != NULL; sdl = (sdLast=sdl)->next)
383     if (&sdl->bsdf == sd)
384     break;
385 greg 2.21 if (sdl == NULL || (sdl->refcnt -= (sdl->refcnt > 0)))
386 greg 2.15 return; /* missing or still in use */
387     /* keep unreferenced data? */
388     if (SDisLoaded(sd) && SDretainSet) {
389     if (SDretainSet == SDretainAll)
390     return; /* keep everything */
391     /* else free cumulative data */
392     SDfreeCumulativeCache(sd->rf);
393     SDfreeCumulativeCache(sd->rb);
394     SDfreeCumulativeCache(sd->tf);
395     return;
396     }
397     /* remove from list and free */
398     if (sdLast == NULL)
399     SDcacheList = sdl->next;
400     else
401     sdLast->next = sdl->next;
402     SDfreeBSDF(&sdl->bsdf);
403     free(sdl);
404     }
405    
406     /* Sample an individual BSDF component */
407     SDError
408     SDsampComponent(SDValue *sv, FVECT outVec, const FVECT inVec,
409     double randX, SDComponent *sdc)
410     {
411     float coef[SDmaxCh];
412     SDError ec;
413     const SDCDst *cd;
414     double d;
415     int n;
416     /* check arguments */
417     if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sdc == NULL))
418     return SDEargument;
419     /* get cumulative distribution */
420     cd = (*sdc->func->getCDist)(inVec, sdc);
421     if (cd == NULL)
422     return SDEmemory;
423     if (cd->cTotal <= 1e-7) { /* anything to sample? */
424     sv->spec = c_dfcolor;
425     sv->cieY = .0;
426     memset(outVec, 0, 3*sizeof(double));
427     return SDEnone;
428     }
429     sv->cieY = cd->cTotal;
430     /* compute sample direction */
431     ec = (*sdc->func->sampCDist)(outVec, randX, cd);
432     if (ec)
433     return ec;
434     /* get BSDF color */
435     n = (*sdc->func->getBSDFs)(coef, outVec, inVec, sdc->dist);
436     if (n <= 0) {
437     strcpy(SDerrorDetail, "BSDF sample value error");
438     return SDEinternal;
439     }
440     sv->spec = sdc->cspec[0];
441     d = coef[0];
442     while (--n) {
443     c_cmix(&sv->spec, d, &sv->spec, coef[n], &sdc->cspec[n]);
444     d += coef[n];
445     }
446     /* make sure everything is set */
447     c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
448     return SDEnone;
449     }
450    
451     #define MS_MAXDIM 15
452    
453     /* Convert 1-dimensional random variable to N-dimensional */
454     void
455     SDmultiSamp(double t[], int n, double randX)
456     {
457     unsigned nBits;
458     double scale;
459     bitmask_t ndx, coord[MS_MAXDIM];
460    
461     while (n > MS_MAXDIM) /* punt for higher dimensions */
462 greg 2.19 t[--n] = rand()*(1./(RAND_MAX+.5));
463 greg 2.15 nBits = (8*sizeof(bitmask_t) - 1) / n;
464     ndx = randX * (double)((bitmask_t)1 << (nBits*n));
465     /* get coordinate on Hilbert curve */
466     hilbert_i2c(n, nBits, ndx, coord);
467     /* convert back to [0,1) range */
468     scale = 1. / (double)((bitmask_t)1 << nBits);
469     while (n--)
470 greg 2.19 t[n] = scale * ((double)coord[n] + rand()*(1./(RAND_MAX+.5)));
471 greg 2.15 }
472    
473     #undef MS_MAXDIM
474    
475     /* Generate diffuse hemispherical sample */
476     static void
477     SDdiffuseSamp(FVECT outVec, int outFront, double randX)
478     {
479     /* convert to position on hemisphere */
480     SDmultiSamp(outVec, 2, randX);
481     SDsquare2disk(outVec, outVec[0], outVec[1]);
482     outVec[2] = 1. - outVec[0]*outVec[0] - outVec[1]*outVec[1];
483     if (outVec[2] > .0) /* a bit of paranoia */
484     outVec[2] = sqrt(outVec[2]);
485     if (!outFront) /* going out back? */
486     outVec[2] = -outVec[2];
487     }
488    
489     /* Query projected solid angle coverage for non-diffuse BSDF direction */
490     SDError
491 greg 2.22 SDsizeBSDF(double *projSA, const FVECT v1, const RREAL *v2,
492     int qflags, const SDData *sd)
493 greg 2.15 {
494     SDSpectralDF *rdf;
495     SDError ec;
496     int i;
497     /* check arguments */
498 greg 2.22 if ((projSA == NULL) | (v1 == NULL))
499 greg 2.15 return SDEargument;
500     /* initialize extrema */
501 greg 2.17 switch (qflags) {
502 greg 2.15 case SDqueryMax:
503     projSA[0] = .0;
504     break;
505     case SDqueryMin+SDqueryMax:
506     projSA[1] = .0;
507     /* fall through */
508     case SDqueryMin:
509     projSA[0] = 10.;
510     break;
511     case 0:
512     return SDEargument;
513     }
514 greg 2.22 if (v1[2] > .0) /* front surface query? */
515 greg 2.15 rdf = sd->rf;
516     else
517     rdf = sd->rb;
518     ec = SDEdata; /* run through components */
519     for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
520 greg 2.22 ec = (*rdf->comp[i].func->queryProjSA)(projSA, v1, v2,
521     qflags, rdf->comp[i].dist);
522 greg 2.15 if (ec)
523     return ec;
524     }
525     for (i = (sd->tf==NULL) ? 0 : sd->tf->ncomp; i--; ) {
526 greg 2.22 ec = (*sd->tf->comp[i].func->queryProjSA)(projSA, v1, v2,
527     qflags, sd->tf->comp[i].dist);
528 greg 2.15 if (ec)
529     return ec;
530     }
531 greg 2.17 if (ec) { /* all diffuse? */
532     projSA[0] = M_PI;
533     if (qflags == SDqueryMin+SDqueryMax)
534     projSA[1] = M_PI;
535     }
536     return SDEnone;
537 greg 2.15 }
538    
539     /* Return BSDF for the given incident and scattered ray vectors */
540     SDError
541     SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
542     {
543     int inFront, outFront;
544     SDSpectralDF *sdf;
545     float coef[SDmaxCh];
546     int nch, i;
547     /* check arguments */
548     if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
549     return SDEargument;
550     /* whose side are we on? */
551     inFront = (inVec[2] > .0);
552     outFront = (outVec[2] > .0);
553     /* start with diffuse portion */
554     if (inFront & outFront) {
555     *sv = sd->rLambFront;
556     sdf = sd->rf;
557     } else if (!(inFront | outFront)) {
558     *sv = sd->rLambBack;
559     sdf = sd->rb;
560     } else /* inFront ^ outFront */ {
561     *sv = sd->tLamb;
562     sdf = sd->tf;
563     }
564     sv->cieY *= 1./M_PI;
565     /* add non-diffuse components */
566     i = (sdf != NULL) ? sdf->ncomp : 0;
567     while (i-- > 0) {
568     nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
569     sdf->comp[i].dist);
570     while (nch-- > 0) {
571     c_cmix(&sv->spec, sv->cieY, &sv->spec,
572     coef[nch], &sdf->comp[i].cspec[nch]);
573     sv->cieY += coef[nch];
574     }
575     }
576     /* make sure everything is set */
577     c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
578     return SDEnone;
579     }
580    
581     /* Compute directional hemispherical scattering at this incident angle */
582     double
583     SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
584     {
585     double hsum;
586     SDSpectralDF *rdf;
587     const SDCDst *cd;
588     int i;
589     /* check arguments */
590     if ((inVec == NULL) | (sd == NULL))
591     return .0;
592     /* gather diffuse components */
593     if (inVec[2] > .0) {
594     hsum = sd->rLambFront.cieY;
595     rdf = sd->rf;
596     } else /* !inFront */ {
597     hsum = sd->rLambBack.cieY;
598     rdf = sd->rb;
599     }
600     if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
601     hsum = .0;
602     if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
603     hsum += sd->tLamb.cieY;
604     /* gather non-diffuse components */
605     i = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
606     rdf != NULL) ? rdf->ncomp : 0;
607     while (i-- > 0) { /* non-diffuse reflection */
608     cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
609     if (cd != NULL)
610     hsum += cd->cTotal;
611     }
612     i = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
613     sd->tf != NULL) ? sd->tf->ncomp : 0;
614     while (i-- > 0) { /* non-diffuse transmission */
615     cd = (*sd->tf->comp[i].func->getCDist)(inVec, &sd->tf->comp[i]);
616     if (cd != NULL)
617     hsum += cd->cTotal;
618     }
619     return hsum;
620     }
621    
622     /* Sample BSDF direction based on the given random variable */
623     SDError
624     SDsampBSDF(SDValue *sv, FVECT outVec, const FVECT inVec,
625     double randX, int sflags, const SDData *sd)
626     {
627     SDError ec;
628     int inFront;
629     SDSpectralDF *rdf;
630     double rdiff;
631     float coef[SDmaxCh];
632     int i, j, n, nr;
633     SDComponent *sdc;
634     const SDCDst **cdarr = NULL;
635     /* check arguments */
636     if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL) |
637     (randX < .0) | (randX >= 1.))
638     return SDEargument;
639     /* whose side are we on? */
640     inFront = (inVec[2] > .0);
641     /* remember diffuse portions */
642     if (inFront) {
643     *sv = sd->rLambFront;
644     rdf = sd->rf;
645     } else /* !inFront */ {
646     *sv = sd->rLambBack;
647     rdf = sd->rb;
648     }
649     if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
650     sv->cieY = .0;
651     rdiff = sv->cieY;
652     if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
653     sv->cieY += sd->tLamb.cieY;
654     /* gather non-diffuse components */
655     i = nr = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
656     rdf != NULL) ? rdf->ncomp : 0;
657     j = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
658     sd->tf != NULL) ? sd->tf->ncomp : 0;
659     n = i + j;
660     if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
661     return SDEmemory;
662     while (j-- > 0) { /* non-diffuse transmission */
663     cdarr[i+j] = (*sd->tf->comp[j].func->getCDist)(inVec, &sd->tf->comp[j]);
664     if (cdarr[i+j] == NULL) {
665     free(cdarr);
666     return SDEmemory;
667     }
668     sv->cieY += cdarr[i+j]->cTotal;
669     }
670     while (i-- > 0) { /* non-diffuse reflection */
671     cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
672     if (cdarr[i] == NULL) {
673     free(cdarr);
674     return SDEmemory;
675     }
676     sv->cieY += cdarr[i]->cTotal;
677     }
678     if (sv->cieY <= 1e-7) { /* anything to sample? */
679     sv->cieY = .0;
680     memset(outVec, 0, 3*sizeof(double));
681     return SDEnone;
682     }
683     /* scale random variable */
684     randX *= sv->cieY;
685     /* diffuse reflection? */
686     if (randX < rdiff) {
687     SDdiffuseSamp(outVec, inFront, randX/rdiff);
688     goto done;
689     }
690     randX -= rdiff;
691     /* diffuse transmission? */
692     if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
693     if (randX < sd->tLamb.cieY) {
694     sv->spec = sd->tLamb.spec;
695     SDdiffuseSamp(outVec, !inFront, randX/sd->tLamb.cieY);
696     goto done;
697     }
698     randX -= sd->tLamb.cieY;
699     }
700     /* else one of cumulative dist. */
701     for (i = 0; i < n && randX < cdarr[i]->cTotal; i++)
702     randX -= cdarr[i]->cTotal;
703     if (i >= n)
704     return SDEinternal;
705     /* compute sample direction */
706     sdc = (i < nr) ? &rdf->comp[i] : &sd->tf->comp[i-nr];
707     ec = (*sdc->func->sampCDist)(outVec, randX/cdarr[i]->cTotal, cdarr[i]);
708     if (ec)
709     return ec;
710     /* compute color */
711     j = (*sdc->func->getBSDFs)(coef, outVec, inVec, sdc->dist);
712     if (j <= 0) {
713     sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
714     sd->name);
715     return SDEinternal;
716     }
717     sv->spec = sdc->cspec[0];
718     rdiff = coef[0];
719     while (--j) {
720     c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
721     rdiff += coef[j];
722     }
723     done:
724     if (cdarr != NULL)
725     free(cdarr);
726     /* make sure everything is set */
727     c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
728     return SDEnone;
729     }
730    
731     /* Compute World->BSDF transform from surface normal and up (Y) vector */
732     SDError
733     SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
734     {
735     if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
736     return SDEargument;
737     VCOPY(vMtx[2], sNrm);
738     if (normalize(vMtx[2]) == .0)
739     return SDEargument;
740     fcross(vMtx[0], uVec, vMtx[2]);
741     if (normalize(vMtx[0]) == .0)
742     return SDEargument;
743     fcross(vMtx[1], vMtx[2], vMtx[0]);
744     return SDEnone;
745     }
746    
747     /* Compute inverse transform */
748     SDError
749     SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
750     {
751     RREAL mTmp[3][3];
752     double d;
753    
754     if ((iMtx == NULL) | (vMtx == NULL))
755     return SDEargument;
756     /* compute determinant */
757     mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
758     mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
759     mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
760     d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
761     if (d == .0) {
762     strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
763     return SDEargument;
764     }
765     d = 1./d; /* invert matrix */
766     mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
767     mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
768     mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
769     mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
770     mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
771     mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
772     mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
773     memcpy(iMtx, mTmp, sizeof(mTmp));
774     return SDEnone;
775     }
776    
777     /* Transform and normalize direction (column) vector */
778     SDError
779     SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
780     {
781     FVECT vTmp;
782    
783     if ((resVec == NULL) | (inpVec == NULL))
784     return SDEargument;
785     if (vMtx == NULL) { /* assume they just want to normalize */
786     if (resVec != inpVec)
787     VCOPY(resVec, inpVec);
788     return (normalize(resVec) > .0) ? SDEnone : SDEargument;
789     }
790     vTmp[0] = DOT(vMtx[0], inpVec);
791     vTmp[1] = DOT(vMtx[1], inpVec);
792     vTmp[2] = DOT(vMtx[2], inpVec);
793     if (normalize(vTmp) == .0)
794     return SDEargument;
795     VCOPY(resVec, vTmp);
796     return SDEnone;
797     }
798    
799     /*################################################################*/
800     /*######### DEPRECATED ROUTINES AWAITING PERMANENT REMOVAL #######*/
801    
802     /*
803 greg 2.1 * Routines for handling BSDF data
804     */
805    
806     #include "standard.h"
807     #include "paths.h"
808     #include <ctype.h>
809    
810     #define MAXLATS 46 /* maximum number of latitudes */
811    
812     /* BSDF angle specification */
813     typedef struct {
814     char name[64]; /* basis name */
815     int nangles; /* total number of directions */
816     struct {
817     float tmin; /* starting theta */
818     short nphis; /* number of phis (0 term) */
819     } lat[MAXLATS+1]; /* latitudes */
820     } ANGLE_BASIS;
821    
822 greg 2.4 #define MAXABASES 7 /* limit on defined bases */
823 greg 2.1
824     static ANGLE_BASIS abase_list[MAXABASES] = {
825     {
826     "LBNL/Klems Full", 145,
827     { {-5., 1},
828     {5., 8},
829     {15., 16},
830     {25., 20},
831     {35., 24},
832     {45., 24},
833     {55., 24},
834     {65., 16},
835     {75., 12},
836     {90., 0} }
837     }, {
838     "LBNL/Klems Half", 73,
839     { {-6.5, 1},
840     {6.5, 8},
841     {19.5, 12},
842     {32.5, 16},
843     {46.5, 20},
844     {61.5, 12},
845     {76.5, 4},
846     {90., 0} }
847     }, {
848     "LBNL/Klems Quarter", 41,
849     { {-9., 1},
850     {9., 8},
851     {27., 12},
852     {46., 12},
853     {66., 8},
854     {90., 0} }
855     }
856     };
857    
858     static int nabases = 3; /* current number of defined bases */
859    
860 greg 2.9 #define FEQ(a,b) ((a)-(b) <= 1e-6 && (b)-(a) <= 1e-6)
861    
862     static int
863     fequal(double a, double b)
864     {
865     if (b != .0)
866     a = a/b - 1.;
867     return((a <= 1e-6) & (a >= -1e-6));
868     }
869 greg 2.3
870 greg 2.14 /* Returns the name of the given tag */
871 greg 2.3 #ifdef ezxml_name
872     #undef ezxml_name
873     static char *
874     ezxml_name(ezxml_t xml)
875     {
876     if (xml == NULL)
877     return(NULL);
878     return(xml->name);
879     }
880     #endif
881    
882 greg 2.14 /* Returns the given tag's character content or empty string if none */
883 greg 2.3 #ifdef ezxml_txt
884     #undef ezxml_txt
885     static char *
886     ezxml_txt(ezxml_t xml)
887     {
888     if (xml == NULL)
889     return("");
890     return(xml->txt);
891     }
892     #endif
893    
894 greg 2.1
895     static int
896     ab_getvec( /* get vector for this angle basis index */
897     FVECT v,
898     int ndx,
899     void *p
900     )
901     {
902     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
903     int li;
904 greg 2.2 double pol, azi, d;
905 greg 2.1
906     if ((ndx < 0) | (ndx >= ab->nangles))
907     return(0);
908     for (li = 0; ndx >= ab->lat[li].nphis; li++)
909     ndx -= ab->lat[li].nphis;
910 greg 2.2 pol = PI/180.*0.5*(ab->lat[li].tmin + ab->lat[li+1].tmin);
911 greg 2.1 azi = 2.*PI*ndx/ab->lat[li].nphis;
912 greg 2.2 v[2] = d = cos(pol);
913     d = sqrt(1. - d*d); /* sin(pol) */
914 greg 2.1 v[0] = cos(azi)*d;
915     v[1] = sin(azi)*d;
916     return(1);
917     }
918    
919    
920     static int
921     ab_getndx( /* get index corresponding to the given vector */
922     FVECT v,
923     void *p
924     )
925     {
926     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
927     int li, ndx;
928 greg 2.2 double pol, azi, d;
929 greg 2.1
930     if ((v[2] < -1.0) | (v[2] > 1.0))
931     return(-1);
932 greg 2.2 pol = 180.0/PI*acos(v[2]);
933 greg 2.1 azi = 180.0/PI*atan2(v[1], v[0]);
934     if (azi < 0.0) azi += 360.0;
935 greg 2.2 for (li = 1; ab->lat[li].tmin <= pol; li++)
936 greg 2.1 if (!ab->lat[li].nphis)
937     return(-1);
938     --li;
939     ndx = (int)((1./360.)*azi*ab->lat[li].nphis + 0.5);
940     if (ndx >= ab->lat[li].nphis) ndx = 0;
941     while (li--)
942     ndx += ab->lat[li].nphis;
943     return(ndx);
944     }
945    
946    
947     static double
948     ab_getohm( /* get solid angle for this angle basis index */
949     int ndx,
950     void *p
951     )
952     {
953     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
954     int li;
955     double theta, theta1;
956    
957     if ((ndx < 0) | (ndx >= ab->nangles))
958     return(0);
959     for (li = 0; ndx >= ab->lat[li].nphis; li++)
960     ndx -= ab->lat[li].nphis;
961     theta1 = PI/180. * ab->lat[li+1].tmin;
962     if (ab->lat[li].nphis == 1) { /* special case */
963     if (ab->lat[li].tmin > FTINY)
964     error(USER, "unsupported BSDF coordinate system");
965     return(2.*PI*(1. - cos(theta1)));
966     }
967     theta = PI/180. * ab->lat[li].tmin;
968     return(2.*PI*(cos(theta) - cos(theta1))/(double)ab->lat[li].nphis);
969     }
970    
971    
972     static int
973     ab_getvecR( /* get reverse vector for this angle basis index */
974     FVECT v,
975     int ndx,
976     void *p
977     )
978     {
979     if (!ab_getvec(v, ndx, p))
980     return(0);
981    
982     v[0] = -v[0];
983     v[1] = -v[1];
984     v[2] = -v[2];
985    
986     return(1);
987     }
988    
989    
990     static int
991     ab_getndxR( /* get index corresponding to the reverse vector */
992     FVECT v,
993     void *p
994     )
995     {
996     FVECT v2;
997    
998     v2[0] = -v[0];
999     v2[1] = -v[1];
1000     v2[2] = -v[2];
1001    
1002     return ab_getndx(v2, p);
1003     }
1004    
1005    
1006     static void
1007 greg 2.4 load_angle_basis( /* load custom BSDF angle basis */
1008 greg 2.3 ezxml_t wab
1009     )
1010     {
1011     char *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
1012     ezxml_t wbb;
1013     int i;
1014    
1015 greg 2.4 if (!abname || !*abname)
1016 greg 2.3 return;
1017     for (i = nabases; i--; )
1018 greg 2.12 if (!strcasecmp(abname, abase_list[i].name))
1019 greg 2.4 return; /* assume it's the same */
1020 greg 2.3 if (nabases >= MAXABASES)
1021     error(INTERNAL, "too many angle bases");
1022     strcpy(abase_list[nabases].name, abname);
1023     abase_list[nabases].nangles = 0;
1024     for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
1025     wbb != NULL; i++, wbb = wbb->next) {
1026     if (i >= MAXLATS)
1027     error(INTERNAL, "too many latitudes in custom basis");
1028     abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
1029     ezxml_child(ezxml_child(wbb,
1030     "ThetaBounds"), "UpperTheta")));
1031     if (!i)
1032     abase_list[nabases].lat[i].tmin =
1033     -abase_list[nabases].lat[i+1].tmin;
1034 greg 2.9 else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
1035 greg 2.3 "ThetaBounds"), "LowerTheta"))),
1036     abase_list[nabases].lat[i].tmin))
1037     error(WARNING, "theta values disagree in custom basis");
1038     abase_list[nabases].nangles +=
1039     abase_list[nabases].lat[i].nphis =
1040     atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
1041     }
1042     abase_list[nabases++].lat[i].nphis = 0;
1043     }
1044    
1045    
1046 greg 2.6 static void
1047     load_geometry( /* load geometric dimensions and description (if any) */
1048     struct BSDF_data *dp,
1049     ezxml_t wdb
1050     )
1051     {
1052     ezxml_t geom;
1053     double cfact;
1054     const char *fmt, *mgfstr;
1055    
1056     dp->dim[0] = dp->dim[1] = dp->dim[2] = 0;
1057     dp->mgf = NULL;
1058     if ((geom = ezxml_child(wdb, "Width")) != NULL)
1059     dp->dim[0] = atof(ezxml_txt(geom)) *
1060     to_meters(ezxml_attr(geom, "unit"));
1061     if ((geom = ezxml_child(wdb, "Height")) != NULL)
1062     dp->dim[1] = atof(ezxml_txt(geom)) *
1063     to_meters(ezxml_attr(geom, "unit"));
1064     if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
1065     dp->dim[2] = atof(ezxml_txt(geom)) *
1066     to_meters(ezxml_attr(geom, "unit"));
1067     if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
1068     (mgfstr = ezxml_txt(geom)) == NULL)
1069     return;
1070     if ((fmt = ezxml_attr(geom, "format")) != NULL &&
1071     strcasecmp(fmt, "MGF")) {
1072     sprintf(errmsg, "unrecognized geometry format '%s'", fmt);
1073     error(WARNING, errmsg);
1074     return;
1075     }
1076     cfact = to_meters(ezxml_attr(geom, "unit"));
1077     dp->mgf = (char *)malloc(strlen(mgfstr)+32);
1078     if (dp->mgf == NULL)
1079     error(SYSTEM, "out of memory in load_geometry");
1080     if (cfact < 0.99 || cfact > 1.01)
1081     sprintf(dp->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
1082     else
1083     strcpy(dp->mgf, mgfstr);
1084     }
1085    
1086    
1087 greg 2.3 static void
1088 greg 2.1 load_bsdf_data( /* load BSDF distribution for this wavelength */
1089     struct BSDF_data *dp,
1090     ezxml_t wdb
1091     )
1092     {
1093     char *cbasis = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
1094     char *rbasis = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
1095     char *sdata;
1096     int i;
1097    
1098 greg 2.4 if ((!cbasis || !*cbasis) | (!rbasis || !*rbasis)) {
1099 greg 2.1 error(WARNING, "missing column/row basis for BSDF");
1100     return;
1101     }
1102     for (i = nabases; i--; )
1103 greg 2.12 if (!strcasecmp(cbasis, abase_list[i].name)) {
1104 greg 2.1 dp->ninc = abase_list[i].nangles;
1105     dp->ib_priv = (void *)&abase_list[i];
1106     dp->ib_vec = ab_getvecR;
1107     dp->ib_ndx = ab_getndxR;
1108     dp->ib_ohm = ab_getohm;
1109     break;
1110     }
1111     if (i < 0) {
1112 greg 2.4 sprintf(errmsg, "undefined ColumnAngleBasis '%s'", cbasis);
1113 greg 2.1 error(WARNING, errmsg);
1114     return;
1115     }
1116     for (i = nabases; i--; )
1117 greg 2.12 if (!strcasecmp(rbasis, abase_list[i].name)) {
1118 greg 2.1 dp->nout = abase_list[i].nangles;
1119     dp->ob_priv = (void *)&abase_list[i];
1120     dp->ob_vec = ab_getvec;
1121     dp->ob_ndx = ab_getndx;
1122     dp->ob_ohm = ab_getohm;
1123     break;
1124     }
1125     if (i < 0) {
1126 greg 2.16 sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1127 greg 2.1 error(WARNING, errmsg);
1128     return;
1129     }
1130     /* read BSDF data */
1131     sdata = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
1132 greg 2.4 if (!sdata || !*sdata) {
1133 greg 2.1 error(WARNING, "missing BSDF ScatteringData");
1134     return;
1135     }
1136     dp->bsdf = (float *)malloc(sizeof(float)*dp->ninc*dp->nout);
1137     if (dp->bsdf == NULL)
1138     error(SYSTEM, "out of memory in load_bsdf_data");
1139     for (i = 0; i < dp->ninc*dp->nout; i++) {
1140     char *sdnext = fskip(sdata);
1141     if (sdnext == NULL) {
1142     error(WARNING, "bad/missing BSDF ScatteringData");
1143     free(dp->bsdf); dp->bsdf = NULL;
1144     return;
1145     }
1146     while (*sdnext && isspace(*sdnext))
1147     sdnext++;
1148     if (*sdnext == ',') sdnext++;
1149     dp->bsdf[i] = atof(sdata);
1150     sdata = sdnext;
1151     }
1152     while (isspace(*sdata))
1153     sdata++;
1154     if (*sdata) {
1155     sprintf(errmsg, "%d extra characters after BSDF ScatteringData",
1156 greg 2.5 (int)strlen(sdata));
1157 greg 2.1 error(WARNING, errmsg);
1158     }
1159     }
1160    
1161    
1162     static int
1163     check_bsdf_data( /* check that BSDF data is sane */
1164     struct BSDF_data *dp
1165     )
1166     {
1167 greg 2.2 double *omega_iarr, *omega_oarr;
1168 greg 2.7 double dom, contrib, hemi_total, full_total;
1169 greg 2.1 int nneg;
1170 greg 2.2 FVECT v;
1171 greg 2.1 int i, o;
1172    
1173     if (dp == NULL || dp->bsdf == NULL)
1174     return(0);
1175 greg 2.2 omega_iarr = (double *)calloc(dp->ninc, sizeof(double));
1176     omega_oarr = (double *)calloc(dp->nout, sizeof(double));
1177     if ((omega_iarr == NULL) | (omega_oarr == NULL))
1178 greg 2.1 error(SYSTEM, "out of memory in check_bsdf_data");
1179 greg 2.2 /* incoming projected solid angles */
1180     hemi_total = .0;
1181     for (i = dp->ninc; i--; ) {
1182     dom = getBSDF_incohm(dp,i);
1183     if (dom <= .0) {
1184     error(WARNING, "zero/negative incoming solid angle");
1185     continue;
1186     }
1187     if (!getBSDF_incvec(v,dp,i) || v[2] > FTINY) {
1188     error(WARNING, "illegal incoming BSDF direction");
1189     free(omega_iarr); free(omega_oarr);
1190     return(0);
1191     }
1192     hemi_total += omega_iarr[i] = dom * -v[2];
1193     }
1194     if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1195     sprintf(errmsg, "incoming BSDF hemisphere off by %.1f%%",
1196     100.*(hemi_total/PI - 1.));
1197     error(WARNING, errmsg);
1198     }
1199     dom = PI / hemi_total; /* fix normalization */
1200     for (i = dp->ninc; i--; )
1201     omega_iarr[i] *= dom;
1202     /* outgoing projected solid angles */
1203 greg 2.1 hemi_total = .0;
1204     for (o = dp->nout; o--; ) {
1205     dom = getBSDF_outohm(dp,o);
1206     if (dom <= .0) {
1207 greg 2.2 error(WARNING, "zero/negative outgoing solid angle");
1208 greg 2.1 continue;
1209     }
1210     if (!getBSDF_outvec(v,dp,o) || v[2] < -FTINY) {
1211     error(WARNING, "illegal outgoing BSDF direction");
1212 greg 2.2 free(omega_iarr); free(omega_oarr);
1213 greg 2.1 return(0);
1214     }
1215 greg 2.2 hemi_total += omega_oarr[o] = dom * v[2];
1216 greg 2.1 }
1217     if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1218     sprintf(errmsg, "outgoing BSDF hemisphere off by %.1f%%",
1219     100.*(hemi_total/PI - 1.));
1220     error(WARNING, errmsg);
1221     }
1222 greg 2.2 dom = PI / hemi_total; /* fix normalization */
1223 greg 2.1 for (o = dp->nout; o--; )
1224 greg 2.2 omega_oarr[o] *= dom;
1225     nneg = 0; /* check outgoing totals */
1226     for (i = 0; i < dp->ninc; i++) {
1227 greg 2.1 hemi_total = .0;
1228     for (o = dp->nout; o--; ) {
1229     double f = BSDF_value(dp,i,o);
1230 greg 2.2 if (f >= .0)
1231     hemi_total += f*omega_oarr[o];
1232     else {
1233     nneg += (f < -FTINY);
1234     BSDF_value(dp,i,o) = .0f;
1235     }
1236 greg 2.1 }
1237 greg 2.8 if (hemi_total > 1.01) {
1238 greg 2.2 sprintf(errmsg,
1239     "incoming BSDF direction %d passes %.1f%% of light",
1240     i, 100.*hemi_total);
1241 greg 2.1 error(WARNING, errmsg);
1242     }
1243     }
1244 greg 2.2 if (nneg) {
1245     sprintf(errmsg, "%d negative BSDF values (ignored)", nneg);
1246 greg 2.1 error(WARNING, errmsg);
1247     }
1248 greg 2.7 full_total = .0; /* reverse roles and check again */
1249 greg 2.2 for (o = 0; o < dp->nout; o++) {
1250     hemi_total = .0;
1251     for (i = dp->ninc; i--; )
1252     hemi_total += BSDF_value(dp,i,o) * omega_iarr[i];
1253    
1254 greg 2.8 if (hemi_total > 1.01) {
1255 greg 2.2 sprintf(errmsg,
1256     "outgoing BSDF direction %d collects %.1f%% of light",
1257     o, 100.*hemi_total);
1258     error(WARNING, errmsg);
1259     }
1260 greg 2.7 full_total += hemi_total*omega_oarr[o];
1261     }
1262     full_total /= PI;
1263 greg 2.8 if (full_total > 1.00001) {
1264     sprintf(errmsg, "BSDF transfers %.4f%% of light",
1265 greg 2.7 100.*full_total);
1266     error(WARNING, errmsg);
1267 greg 2.2 }
1268     free(omega_iarr); free(omega_oarr);
1269 greg 2.1 return(1);
1270     }
1271    
1272 greg 2.6
1273 greg 2.1 struct BSDF_data *
1274     load_BSDF( /* load BSDF data from file */
1275     char *fname
1276     )
1277     {
1278     char *path;
1279     ezxml_t fl, wtl, wld, wdb;
1280     struct BSDF_data *dp;
1281    
1282     path = getpath(fname, getrlibpath(), R_OK);
1283     if (path == NULL) {
1284     sprintf(errmsg, "cannot find BSDF file \"%s\"", fname);
1285     error(WARNING, errmsg);
1286     return(NULL);
1287     }
1288     fl = ezxml_parse_file(path);
1289     if (fl == NULL) {
1290     sprintf(errmsg, "cannot open BSDF \"%s\"", path);
1291     error(WARNING, errmsg);
1292     return(NULL);
1293     }
1294     if (ezxml_error(fl)[0]) {
1295     sprintf(errmsg, "BSDF \"%s\" %s", path, ezxml_error(fl));
1296     error(WARNING, errmsg);
1297     ezxml_free(fl);
1298     return(NULL);
1299     }
1300     if (strcmp(ezxml_name(fl), "WindowElement")) {
1301     sprintf(errmsg,
1302     "BSDF \"%s\": top level node not 'WindowElement'",
1303     path);
1304     error(WARNING, errmsg);
1305     ezxml_free(fl);
1306     return(NULL);
1307     }
1308     wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
1309 greg 2.10 if (strcasecmp(ezxml_txt(ezxml_child(ezxml_child(wtl,
1310     "DataDefinition"), "IncidentDataStructure")),
1311     "Columns")) {
1312     sprintf(errmsg,
1313     "BSDF \"%s\": unsupported IncidentDataStructure",
1314     path);
1315     error(WARNING, errmsg);
1316     ezxml_free(fl);
1317     return(NULL);
1318     }
1319 greg 2.3 load_angle_basis(ezxml_child(ezxml_child(wtl,
1320     "DataDefinition"), "AngleBasis"));
1321 greg 2.1 dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
1322 greg 2.6 load_geometry(dp, ezxml_child(wtl, "Material"));
1323 greg 2.1 for (wld = ezxml_child(wtl, "WavelengthData");
1324     wld != NULL; wld = wld->next) {
1325 greg 2.13 if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1326     "Visible"))
1327 greg 2.1 continue;
1328 greg 2.13 for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1329     wdb != NULL; wdb = wdb->next)
1330     if (!strcasecmp(ezxml_txt(ezxml_child(wdb,
1331     "WavelengthDataDirection")),
1332 greg 2.1 "Transmission Front"))
1333 greg 2.13 break;
1334     if (wdb != NULL) { /* load front BTDF */
1335     load_bsdf_data(dp, wdb);
1336     break; /* ignore the rest */
1337     }
1338 greg 2.1 }
1339     ezxml_free(fl); /* done with XML file */
1340     if (!check_bsdf_data(dp)) {
1341     sprintf(errmsg, "bad/missing BTDF data in \"%s\"", path);
1342     error(WARNING, errmsg);
1343     free_BSDF(dp);
1344     dp = NULL;
1345     }
1346     return(dp);
1347     }
1348    
1349    
1350     void
1351     free_BSDF( /* free BSDF data structure */
1352     struct BSDF_data *b
1353     )
1354     {
1355     if (b == NULL)
1356     return;
1357 greg 2.6 if (b->mgf != NULL)
1358     free(b->mgf);
1359 greg 2.1 if (b->bsdf != NULL)
1360     free(b->bsdf);
1361     free(b);
1362     }
1363    
1364    
1365     int
1366     r_BSDF_incvec( /* compute random input vector at given location */
1367     FVECT v,
1368     struct BSDF_data *b,
1369     int i,
1370     double rv,
1371     MAT4 xm
1372     )
1373     {
1374     FVECT pert;
1375     double rad;
1376     int j;
1377    
1378     if (!getBSDF_incvec(v, b, i))
1379     return(0);
1380     rad = sqrt(getBSDF_incohm(b, i) / PI);
1381     multisamp(pert, 3, rv);
1382     for (j = 0; j < 3; j++)
1383     v[j] += rad*(2.*pert[j] - 1.);
1384     if (xm != NULL)
1385     multv3(v, v, xm);
1386     return(normalize(v) != 0.0);
1387     }
1388    
1389    
1390     int
1391     r_BSDF_outvec( /* compute random output vector at given location */
1392     FVECT v,
1393     struct BSDF_data *b,
1394     int o,
1395     double rv,
1396     MAT4 xm
1397     )
1398     {
1399     FVECT pert;
1400     double rad;
1401     int j;
1402    
1403     if (!getBSDF_outvec(v, b, o))
1404     return(0);
1405     rad = sqrt(getBSDF_outohm(b, o) / PI);
1406     multisamp(pert, 3, rv);
1407     for (j = 0; j < 3; j++)
1408     v[j] += rad*(2.*pert[j] - 1.);
1409     if (xm != NULL)
1410     multv3(v, v, xm);
1411     return(normalize(v) != 0.0);
1412     }
1413    
1414    
1415     static int
1416     addrot( /* compute rotation (x,y,z) => (xp,yp,zp) */
1417     char *xfarg[],
1418     FVECT xp,
1419     FVECT yp,
1420     FVECT zp
1421     )
1422     {
1423     static char bufs[3][16];
1424     int bn = 0;
1425     char **xfp = xfarg;
1426     double theta;
1427    
1428     if (yp[2]*yp[2] + zp[2]*zp[2] < 2.*FTINY*FTINY) {
1429     /* Special case for X' along Z-axis */
1430     theta = -atan2(yp[0], yp[1]);
1431     *xfp++ = "-ry";
1432     *xfp++ = xp[2] < 0.0 ? "90" : "-90";
1433     *xfp++ = "-rz";
1434     sprintf(bufs[bn], "%f", theta*(180./PI));
1435     *xfp++ = bufs[bn++];
1436     return(xfp - xfarg);
1437     }
1438     theta = atan2(yp[2], zp[2]);
1439     if (!FEQ(theta,0.0)) {
1440     *xfp++ = "-rx";
1441     sprintf(bufs[bn], "%f", theta*(180./PI));
1442     *xfp++ = bufs[bn++];
1443     }
1444     theta = asin(-xp[2]);
1445     if (!FEQ(theta,0.0)) {
1446     *xfp++ = "-ry";
1447     sprintf(bufs[bn], " %f", theta*(180./PI));
1448     *xfp++ = bufs[bn++];
1449     }
1450     theta = atan2(xp[1], xp[0]);
1451     if (!FEQ(theta,0.0)) {
1452     *xfp++ = "-rz";
1453     sprintf(bufs[bn], "%f", theta*(180./PI));
1454     *xfp++ = bufs[bn++];
1455     }
1456     *xfp = NULL;
1457     return(xfp - xfarg);
1458     }
1459    
1460    
1461     int
1462     getBSDF_xfm( /* compute BSDF orient. -> world orient. transform */
1463     MAT4 xm,
1464     FVECT nrm,
1465 greg 2.6 UpDir ud,
1466     char *xfbuf
1467 greg 2.1 )
1468     {
1469     char *xfargs[7];
1470     XF myxf;
1471     FVECT updir, xdest, ydest;
1472 greg 2.6 int i;
1473 greg 2.1
1474     updir[0] = updir[1] = updir[2] = 0.;
1475     switch (ud) {
1476     case UDzneg:
1477     updir[2] = -1.;
1478     break;
1479     case UDyneg:
1480     updir[1] = -1.;
1481     break;
1482     case UDxneg:
1483     updir[0] = -1.;
1484     break;
1485     case UDxpos:
1486     updir[0] = 1.;
1487     break;
1488     case UDypos:
1489     updir[1] = 1.;
1490     break;
1491     case UDzpos:
1492     updir[2] = 1.;
1493     break;
1494     case UDunknown:
1495     return(0);
1496     }
1497     fcross(xdest, updir, nrm);
1498     if (normalize(xdest) == 0.0)
1499     return(0);
1500     fcross(ydest, nrm, xdest);
1501     xf(&myxf, addrot(xfargs, xdest, ydest, nrm), xfargs);
1502     copymat4(xm, myxf.xfm);
1503 greg 2.6 if (xfbuf == NULL)
1504     return(1);
1505     /* return xf arguments as well */
1506     for (i = 0; xfargs[i] != NULL; i++) {
1507     *xfbuf++ = ' ';
1508     strcpy(xfbuf, xfargs[i]);
1509     while (*xfbuf) ++xfbuf;
1510     }
1511 greg 2.1 return(1);
1512     }
1513 greg 2.15
1514     /*######### END DEPRECATED ROUTINES #######*/
1515     /*################################################################*/