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

Comparing ray/src/common/bsdf.c (file contents):
Revision 2.7 by greg, Tue Sep 7 23:10:50 2010 UTC vs.
Revision 2.41 by greg, Sat Jun 23 16:47:39 2012 UTC

# Line 2 | Line 2
2   static const char RCSid[] = "$Id$";
3   #endif
4   /*
5 + *  bsdf.c
6 + *  
7 + *  Definitions for bidirectional scattering distribution functions.
8 + *
9 + *  Created by Greg Ward on 1/10/11.
10 + *
11 + */
12 +
13 + #define _USE_MATH_DEFINES
14 + #include <stdio.h>
15 + #include <stdlib.h>
16 + #include <string.h>
17 + #include <math.h>
18 + #include <ctype.h>
19 + #include "ezxml.h"
20 + #include "hilbert.h"
21 + #include "bsdf.h"
22 + #include "bsdf_m.h"
23 + #include "bsdf_t.h"
24 +
25 + /* English ASCII strings corresponding to ennumerated errors */
26 + const char              *SDerrorEnglish[] = {
27 +                                "No error",
28 +                                "Memory error",
29 +                                "File input/output error",
30 +                                "File format error",
31 +                                "Illegal argument",
32 +                                "Invalid data",
33 +                                "Unsupported feature",
34 +                                "Internal program error",
35 +                                "Unknown error"
36 +                        };
37 +
38 + /* Additional information on last error (ASCII English) */
39 + char                    SDerrorDetail[256];
40 +
41 + /* Cache of loaded BSDFs */
42 + struct SDCache_s        *SDcacheList = NULL;
43 +
44 + /* Retain BSDFs in cache list */
45 + int                     SDretainSet = SDretainNone;
46 +
47 + /* Report any error to the indicated stream (in English) */
48 + SDError
49 + SDreportEnglish(SDError ec, FILE *fp)
50 + {
51 +        if (!ec)
52 +                return SDEnone;
53 +        if ((ec < SDEnone) | (ec > SDEunknown)) {
54 +                SDerrorDetail[0] = '\0';
55 +                ec = SDEunknown;
56 +        }
57 +        if (fp == NULL)
58 +                return ec;
59 +        fputs(SDerrorEnglish[ec], fp);
60 +        if (SDerrorDetail[0]) {
61 +                fputs(": ", fp);
62 +                fputs(SDerrorDetail, fp);
63 +        }
64 +        fputc('\n', fp);
65 +        if (fp != stderr)
66 +                fflush(fp);
67 +        return ec;
68 + }
69 +
70 + static double
71 + to_meters(              /* return factor to convert given unit to meters */
72 +        const char *unit
73 + )
74 + {
75 +        if (unit == NULL) return(1.);           /* safe assumption? */
76 +        if (!strcasecmp(unit, "Meter")) return(1.);
77 +        if (!strcasecmp(unit, "Foot")) return(.3048);
78 +        if (!strcasecmp(unit, "Inch")) return(.0254);
79 +        if (!strcasecmp(unit, "Centimeter")) return(.01);
80 +        if (!strcasecmp(unit, "Millimeter")) return(.001);
81 +        sprintf(SDerrorDetail, "Unknown dimensional unit '%s'", unit);
82 +        return(-1.);
83 + }
84 +
85 + /* Load geometric dimensions and description (if any) */
86 + static SDError
87 + SDloadGeometry(SDData *sd, ezxml_t wdb)
88 + {
89 +        ezxml_t         geom;
90 +        double          cfact;
91 +        const char      *fmt, *mgfstr;
92 +
93 +        if (wdb == NULL)                /* no geometry section? */
94 +                return SDEnone;
95 +        if ((geom = ezxml_child(wdb, "Name")) != NULL) {
96 +                strncpy(sd->matn, ezxml_txt(geom), SDnameLn);
97 +                if (sd->matn[SDnameLn-1])
98 +                        strcpy(sd->matn+(SDnameLn-4), "...");
99 +        }
100 +        if ((geom = ezxml_child(wdb, "Manufacturer")) != NULL) {
101 +                strncpy(sd->makr, ezxml_txt(geom), SDnameLn);
102 +                if (sd->makr[SDnameLn-1])
103 +                        strcpy(sd->makr+(SDnameLn-4), "...");
104 +        }
105 +        sd->dim[0] = sd->dim[1] = sd->dim[2] = .0;
106 +        SDerrorDetail[0] = '\0';
107 +        if ((geom = ezxml_child(wdb, "Width")) != NULL)
108 +                sd->dim[0] = atof(ezxml_txt(geom)) *
109 +                                to_meters(ezxml_attr(geom, "unit"));
110 +        if ((geom = ezxml_child(wdb, "Height")) != NULL)
111 +                sd->dim[1] = atof(ezxml_txt(geom)) *
112 +                                to_meters(ezxml_attr(geom, "unit"));
113 +        if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
114 +                sd->dim[2] = atof(ezxml_txt(geom)) *
115 +                                to_meters(ezxml_attr(geom, "unit"));
116 +        if ((sd->dim[0] < 0) | (sd->dim[1] < 0) | (sd->dim[2] < 0)) {
117 +                if (!SDerrorDetail[0])
118 +                        sprintf(SDerrorDetail, "Negative dimension in \"%s\"",
119 +                                                sd->name);
120 +                return SDEdata;
121 +        }
122 +        if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
123 +                        (mgfstr = ezxml_txt(geom)) == NULL)
124 +                return SDEnone;
125 +        while (isspace(*mgfstr))
126 +                ++mgfstr;
127 +        if (!*mgfstr)
128 +                return SDEnone;
129 +        if ((fmt = ezxml_attr(geom, "format")) != NULL &&
130 +                        strcasecmp(fmt, "MGF")) {
131 +                sprintf(SDerrorDetail,
132 +                        "Unrecognized geometry format '%s' in \"%s\"",
133 +                                        fmt, sd->name);
134 +                return SDEsupport;
135 +        }
136 +        cfact = to_meters(ezxml_attr(geom, "unit"));
137 +        if (cfact <= 0)
138 +                return SDEformat;
139 +        sd->mgf = (char *)malloc(strlen(mgfstr)+32);
140 +        if (sd->mgf == NULL) {
141 +                strcpy(SDerrorDetail, "Out of memory in SDloadGeometry");
142 +                return SDEmemory;
143 +        }
144 +        if (cfact < 0.99 || cfact > 1.01)
145 +                sprintf(sd->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
146 +        else
147 +                strcpy(sd->mgf, mgfstr);
148 +        return SDEnone;
149 + }
150 +
151 + /* Load a BSDF struct from the given file (free first and keep name) */
152 + SDError
153 + SDloadFile(SDData *sd, const char *fname)
154 + {
155 +        SDError         lastErr;
156 +        ezxml_t         fl, wtl;
157 +
158 +        if ((sd == NULL) | (fname == NULL || !*fname))
159 +                return SDEargument;
160 +                                /* free old data, keeping name */
161 +        SDfreeBSDF(sd);
162 +                                /* parse XML file */
163 +        fl = ezxml_parse_file(fname);
164 +        if (fl == NULL) {
165 +                sprintf(SDerrorDetail, "Cannot open BSDF \"%s\"", fname);
166 +                return SDEfile;
167 +        }
168 +        if (ezxml_error(fl)[0]) {
169 +                sprintf(SDerrorDetail, "BSDF \"%s\" %s", fname, ezxml_error(fl));
170 +                ezxml_free(fl);
171 +                return SDEformat;
172 +        }
173 +        if (strcmp(ezxml_name(fl), "WindowElement")) {
174 +                sprintf(SDerrorDetail,
175 +                        "BSDF \"%s\": top level node not 'WindowElement'",
176 +                                sd->name);
177 +                ezxml_free(fl);
178 +                return SDEformat;
179 +        }
180 +        wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
181 +        if (wtl == NULL) {
182 +                sprintf(SDerrorDetail, "BSDF \"%s\": no optical layers'",
183 +                                sd->name);
184 +                ezxml_free(fl);
185 +                return SDEformat;
186 +        }
187 +                                /* load geometry if present */
188 +        lastErr = SDloadGeometry(sd, ezxml_child(wtl, "Material"));
189 +        if (lastErr) {
190 +                ezxml_free(fl);
191 +                return lastErr;
192 +        }
193 +                                /* try loading variable resolution data */
194 +        lastErr = SDloadTre(sd, wtl);
195 +                                /* check our result */
196 +        if (lastErr == SDEsupport)      /* try matrix BSDF if not tree data */
197 +                lastErr = SDloadMtx(sd, wtl);
198 +                
199 +                                /* done with XML file */
200 +        ezxml_free(fl);
201 +        
202 +        if (lastErr) {          /* was there a load error? */
203 +                SDfreeBSDF(sd);
204 +                return lastErr;
205 +        }
206 +                                /* remove any insignificant components */
207 +        if (sd->rf != NULL && sd->rf->maxHemi <= .001) {
208 +                SDfreeSpectralDF(sd->rf); sd->rf = NULL;
209 +        }
210 +        if (sd->rb != NULL && sd->rb->maxHemi <= .001) {
211 +                SDfreeSpectralDF(sd->rb); sd->rb = NULL;
212 +        }
213 +        if (sd->tf != NULL && sd->tf->maxHemi <= .001) {
214 +                SDfreeSpectralDF(sd->tf); sd->tf = NULL;
215 +        }
216 +                                /* return success */
217 +        return SDEnone;
218 + }
219 +
220 + /* Allocate new spectral distribution function */
221 + SDSpectralDF *
222 + SDnewSpectralDF(int nc)
223 + {
224 +        SDSpectralDF    *df;
225 +        
226 +        if (nc <= 0) {
227 +                strcpy(SDerrorDetail, "Zero component spectral DF request");
228 +                return NULL;
229 +        }
230 +        df = (SDSpectralDF *)malloc(sizeof(SDSpectralDF) +
231 +                                        (nc-1)*sizeof(SDComponent));
232 +        if (df == NULL) {
233 +                sprintf(SDerrorDetail,
234 +                                "Cannot allocate %d component spectral DF", nc);
235 +                return NULL;
236 +        }
237 +        df->minProjSA = .0;
238 +        df->maxHemi = .0;
239 +        df->ncomp = nc;
240 +        memset(df->comp, 0, nc*sizeof(SDComponent));
241 +        return df;
242 + }
243 +
244 + /* Add component(s) to spectral distribution function */
245 + SDSpectralDF *
246 + SDaddComponent(SDSpectralDF *odf, int nadd)
247 + {
248 +        SDSpectralDF    *df;
249 +
250 +        if (odf == NULL)
251 +                return SDnewSpectralDF(nadd);
252 +        if (nadd <= 0)
253 +                return odf;
254 +        df = (SDSpectralDF *)realloc(odf, sizeof(SDSpectralDF) +
255 +                                (odf->ncomp+nadd-1)*sizeof(SDComponent));
256 +        if (df == NULL) {
257 +                sprintf(SDerrorDetail,
258 +                        "Cannot add %d component(s) to spectral DF", nadd);
259 +                SDfreeSpectralDF(odf);
260 +                return NULL;
261 +        }
262 +        memset(df->comp+df->ncomp, 0, nadd*sizeof(SDComponent));
263 +        df->ncomp += nadd;
264 +        return df;
265 + }
266 +
267 + /* Free cached cumulative distributions for BSDF component */
268 + void
269 + SDfreeCumulativeCache(SDSpectralDF *df)
270 + {
271 +        int     n;
272 +        SDCDst  *cdp;
273 +
274 +        if (df == NULL)
275 +                return;
276 +        for (n = df->ncomp; n-- > 0; )
277 +                while ((cdp = df->comp[n].cdList) != NULL) {
278 +                        df->comp[n].cdList = cdp->next;
279 +                        free(cdp);
280 +                }
281 + }
282 +
283 + /* Free a spectral distribution function */
284 + void
285 + SDfreeSpectralDF(SDSpectralDF *df)
286 + {
287 +        int     n;
288 +
289 +        if (df == NULL)
290 +                return;
291 +        SDfreeCumulativeCache(df);
292 +        for (n = df->ncomp; n-- > 0; )
293 +                if (df->comp[n].dist != NULL)
294 +                        (*df->comp[n].func->freeSC)(df->comp[n].dist);
295 +        free(df);
296 + }
297 +
298 + /* Shorten file path to useable BSDF name, removing suffix */
299 + void
300 + SDclipName(char *res, const char *fname)
301 + {
302 +        const char      *cp, *dot = NULL;
303 +        
304 +        for (cp = fname; *cp; cp++)
305 +                if (*cp == '.')
306 +                        dot = cp;
307 +        if ((dot == NULL) | (dot < fname+2))
308 +                dot = cp;
309 +        if (dot - fname >= SDnameLn)
310 +                fname = dot - SDnameLn + 1;
311 +        while (fname < dot)
312 +                *res++ = *fname++;
313 +        *res = '\0';
314 + }
315 +
316 + /* Initialize an unused BSDF struct (simply clears to zeroes) */
317 + void
318 + SDclearBSDF(SDData *sd, const char *fname)
319 + {
320 +        if (sd == NULL)
321 +                return;
322 +        memset(sd, 0, sizeof(SDData));
323 +        if (fname == NULL)
324 +                return;
325 +        SDclipName(sd->name, fname);
326 + }
327 +
328 + /* Free data associated with BSDF struct */
329 + void
330 + SDfreeBSDF(SDData *sd)
331 + {
332 +        if (sd == NULL)
333 +                return;
334 +        if (sd->mgf != NULL) {
335 +                free(sd->mgf);
336 +                sd->mgf = NULL;
337 +        }
338 +        if (sd->rf != NULL) {
339 +                SDfreeSpectralDF(sd->rf);
340 +                sd->rf = NULL;
341 +        }
342 +        if (sd->rb != NULL) {
343 +                SDfreeSpectralDF(sd->rb);
344 +                sd->rb = NULL;
345 +        }
346 +        if (sd->tf != NULL) {
347 +                SDfreeSpectralDF(sd->tf);
348 +                sd->tf = NULL;
349 +        }
350 +        sd->rLambFront.cieY = .0;
351 +        sd->rLambFront.spec.flags = 0;
352 +        sd->rLambBack.cieY = .0;
353 +        sd->rLambBack.spec.flags = 0;
354 +        sd->tLamb.cieY = .0;
355 +        sd->tLamb.spec.flags = 0;
356 + }
357 +
358 + /* Find writeable BSDF by name, or allocate new cache entry if absent */
359 + SDData *
360 + SDgetCache(const char *bname)
361 + {
362 +        struct SDCache_s        *sdl;
363 +        char                    sdnam[SDnameLn];
364 +
365 +        if (bname == NULL)
366 +                return NULL;
367 +
368 +        SDclipName(sdnam, bname);
369 +        for (sdl = SDcacheList; sdl != NULL; sdl = sdl->next)
370 +                if (!strcmp(sdl->bsdf.name, sdnam)) {
371 +                        sdl->refcnt++;
372 +                        return &sdl->bsdf;
373 +                }
374 +
375 +        sdl = (struct SDCache_s *)calloc(1, sizeof(struct SDCache_s));
376 +        if (sdl == NULL)
377 +                return NULL;
378 +
379 +        strcpy(sdl->bsdf.name, sdnam);
380 +        sdl->next = SDcacheList;
381 +        SDcacheList = sdl;
382 +
383 +        sdl->refcnt = 1;
384 +        return &sdl->bsdf;
385 + }
386 +
387 + /* Get loaded BSDF from cache (or load and cache it on first call) */
388 + /* Report any problem to stderr and return NULL on failure */
389 + const SDData *
390 + SDcacheFile(const char *fname)
391 + {
392 +        SDData          *sd;
393 +        SDError         ec;
394 +        
395 +        if (fname == NULL || !*fname)
396 +                return NULL;
397 +        SDerrorDetail[0] = '\0';
398 +        if ((sd = SDgetCache(fname)) == NULL) {
399 +                SDreportEnglish(SDEmemory, stderr);
400 +                return NULL;
401 +        }
402 +        if (!SDisLoaded(sd) && (ec = SDloadFile(sd, fname))) {
403 +                SDreportEnglish(ec, stderr);
404 +                SDfreeCache(sd);
405 +                return NULL;
406 +        }
407 +        return sd;
408 + }
409 +
410 + /* Free a BSDF from our cache (clear all if NULL) */
411 + void
412 + SDfreeCache(const SDData *sd)
413 + {
414 +        struct SDCache_s        *sdl, *sdLast = NULL;
415 +
416 +        if (sd == NULL) {               /* free entire list */
417 +                while ((sdl = SDcacheList) != NULL) {
418 +                        SDcacheList = sdl->next;
419 +                        SDfreeBSDF(&sdl->bsdf);
420 +                        free(sdl);
421 +                }
422 +                return;
423 +        }
424 +        for (sdl = SDcacheList; sdl != NULL; sdl = (sdLast=sdl)->next)
425 +                if (&sdl->bsdf == sd)
426 +                        break;
427 +        if (sdl == NULL || (sdl->refcnt -= (sdl->refcnt > 0)))
428 +                return;                 /* missing or still in use */
429 +                                        /* keep unreferenced data? */
430 +        if (SDisLoaded(sd) && SDretainSet) {
431 +                if (SDretainSet == SDretainAll)
432 +                        return;         /* keep everything */
433 +                                        /* else free cumulative data */
434 +                SDfreeCumulativeCache(sd->rf);
435 +                SDfreeCumulativeCache(sd->rb);
436 +                SDfreeCumulativeCache(sd->tf);
437 +                return;
438 +        }
439 +                                        /* remove from list and free */
440 +        if (sdLast == NULL)
441 +                SDcacheList = sdl->next;
442 +        else
443 +                sdLast->next = sdl->next;
444 +        SDfreeBSDF(&sdl->bsdf);
445 +        free(sdl);
446 + }
447 +
448 + /* Sample an individual BSDF component */
449 + SDError
450 + SDsampComponent(SDValue *sv, FVECT ioVec, double randX, SDComponent *sdc)
451 + {
452 +        float           coef[SDmaxCh];
453 +        SDError         ec;
454 +        FVECT           inVec;
455 +        const SDCDst    *cd;
456 +        double          d;
457 +        int             n;
458 +                                        /* check arguments */
459 +        if ((sv == NULL) | (ioVec == NULL) | (sdc == NULL))
460 +                return SDEargument;
461 +                                        /* get cumulative distribution */
462 +        VCOPY(inVec, ioVec);
463 +        cd = (*sdc->func->getCDist)(inVec, sdc);
464 +        if (cd == NULL)
465 +                return SDEmemory;
466 +        if (cd->cTotal <= 1e-6) {       /* anything to sample? */
467 +                sv->spec = c_dfcolor;
468 +                sv->cieY = .0;
469 +                memset(ioVec, 0, 3*sizeof(double));
470 +                return SDEnone;
471 +        }
472 +        sv->cieY = cd->cTotal;
473 +                                        /* compute sample direction */
474 +        ec = (*sdc->func->sampCDist)(ioVec, randX, cd);
475 +        if (ec)
476 +                return ec;
477 +                                        /* get BSDF color */
478 +        n = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
479 +        if (n <= 0) {
480 +                strcpy(SDerrorDetail, "BSDF sample value error");
481 +                return SDEinternal;
482 +        }
483 +        sv->spec = sdc->cspec[0];
484 +        d = coef[0];
485 +        while (--n) {
486 +                c_cmix(&sv->spec, d, &sv->spec, coef[n], &sdc->cspec[n]);
487 +                d += coef[n];
488 +        }
489 +                                        /* make sure everything is set */
490 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
491 +        return SDEnone;
492 + }
493 +
494 + #define MS_MAXDIM       15
495 +
496 + /* Convert 1-dimensional random variable to N-dimensional */
497 + void
498 + SDmultiSamp(double t[], int n, double randX)
499 + {
500 +        unsigned        nBits;
501 +        double          scale;
502 +        bitmask_t       ndx, coord[MS_MAXDIM];
503 +
504 +        if (n <= 0)                     /* check corner cases */
505 +                return;
506 +        if (randX < 0) randX = 0;
507 +        else if (randX >= 1.) randX = 0.999999999999999;
508 +        if (n == 1) {
509 +                t[0] = randX;
510 +                return;
511 +        }
512 +        while (n > MS_MAXDIM)           /* punt for higher dimensions */
513 +                t[--n] = rand()*(1./(RAND_MAX+.5));
514 +        nBits = (8*sizeof(bitmask_t) - 1) / n;
515 +        ndx = randX * (double)((bitmask_t)1 << (nBits*n));
516 +                                        /* get coordinate on Hilbert curve */
517 +        hilbert_i2c(n, nBits, ndx, coord);
518 +                                        /* convert back to [0,1) range */
519 +        scale = 1. / (double)((bitmask_t)1 << nBits);
520 +        while (n--)
521 +                t[n] = scale * ((double)coord[n] + rand()*(1./(RAND_MAX+.5)));
522 + }
523 +
524 + #undef MS_MAXDIM
525 +
526 + /* Generate diffuse hemispherical sample */
527 + static void
528 + SDdiffuseSamp(FVECT outVec, int outFront, double randX)
529 + {
530 +                                        /* convert to position on hemisphere */
531 +        SDmultiSamp(outVec, 2, randX);
532 +        SDsquare2disk(outVec, outVec[0], outVec[1]);
533 +        outVec[2] = 1. - outVec[0]*outVec[0] - outVec[1]*outVec[1];
534 +        if (outVec[2] > 0)              /* a bit of paranoia */
535 +                outVec[2] = sqrt(outVec[2]);
536 +        if (!outFront)                  /* going out back? */
537 +                outVec[2] = -outVec[2];
538 + }
539 +
540 + /* Query projected solid angle coverage for non-diffuse BSDF direction */
541 + SDError
542 + SDsizeBSDF(double *projSA, const FVECT v1, const RREAL *v2,
543 +                                int qflags, const SDData *sd)
544 + {
545 +        SDSpectralDF    *rdf, *tdf;
546 +        SDError         ec;
547 +        int             i;
548 +                                        /* check arguments */
549 +        if ((projSA == NULL) | (v1 == NULL) | (sd == NULL))
550 +                return SDEargument;
551 +                                        /* initialize extrema */
552 +        switch (qflags) {
553 +        case SDqueryMax:
554 +                projSA[0] = .0;
555 +                break;
556 +        case SDqueryMin+SDqueryMax:
557 +                projSA[1] = .0;
558 +                /* fall through */
559 +        case SDqueryMin:
560 +                projSA[0] = 10.;
561 +                break;
562 +        case 0:
563 +                return SDEargument;
564 +        }
565 +        if (v1[2] > 0)                  /* front surface query? */
566 +                rdf = sd->rf;
567 +        else
568 +                rdf = sd->rb;
569 +        tdf = sd->tf;
570 +        if (v2 != NULL)                 /* bidirectional? */
571 +                if (v1[2] > 0 ^ v2[2] > 0)
572 +                        rdf = NULL;
573 +                else
574 +                        tdf = NULL;
575 +        ec = SDEdata;                   /* run through components */
576 +        for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
577 +                ec = (*rdf->comp[i].func->queryProjSA)(projSA, v1, v2,
578 +                                                qflags, &rdf->comp[i]);
579 +                if (ec)
580 +                        return ec;
581 +        }
582 +        for (i = (tdf==NULL) ? 0 : tdf->ncomp; i--; ) {
583 +                ec = (*tdf->comp[i].func->queryProjSA)(projSA, v1, v2,
584 +                                                qflags, &tdf->comp[i]);
585 +                if (ec)
586 +                        return ec;
587 +        }
588 +        if (ec) {                       /* all diffuse? */
589 +                projSA[0] = M_PI;
590 +                if (qflags == SDqueryMin+SDqueryMax)
591 +                        projSA[1] = M_PI;
592 +        }
593 +        return SDEnone;
594 + }
595 +
596 + /* Return BSDF for the given incident and scattered ray vectors */
597 + SDError
598 + SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
599 + {
600 +        int             inFront, outFront;
601 +        SDSpectralDF    *sdf;
602 +        float           coef[SDmaxCh];
603 +        int             nch, i;
604 +                                        /* check arguments */
605 +        if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
606 +                return SDEargument;
607 +                                        /* whose side are we on? */
608 +        inFront = (inVec[2] > 0);
609 +        outFront = (outVec[2] > 0);
610 +                                        /* start with diffuse portion */
611 +        if (inFront & outFront) {
612 +                *sv = sd->rLambFront;
613 +                sdf = sd->rf;
614 +        } else if (!(inFront | outFront)) {
615 +                *sv = sd->rLambBack;
616 +                sdf = sd->rb;
617 +        } else /* inFront ^ outFront */ {
618 +                *sv = sd->tLamb;
619 +                sdf = sd->tf;
620 +        }
621 +        sv->cieY *= 1./M_PI;
622 +                                        /* add non-diffuse components */
623 +        i = (sdf != NULL) ? sdf->ncomp : 0;
624 +        while (i-- > 0) {
625 +                nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
626 +                                                        &sdf->comp[i]);
627 +                while (nch-- > 0) {
628 +                        c_cmix(&sv->spec, sv->cieY, &sv->spec,
629 +                                        coef[nch], &sdf->comp[i].cspec[nch]);
630 +                        sv->cieY += coef[nch];
631 +                }
632 +        }
633 +                                        /* make sure everything is set */
634 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
635 +        return SDEnone;
636 + }
637 +
638 + /* Compute directional hemispherical scattering at this incident angle */
639 + double
640 + SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
641 + {
642 +        double          hsum;
643 +        SDSpectralDF    *rdf;
644 +        const SDCDst    *cd;
645 +        int             i;
646 +                                        /* check arguments */
647 +        if ((inVec == NULL) | (sd == NULL))
648 +                return .0;
649 +                                        /* gather diffuse components */
650 +        if (inVec[2] > 0) {
651 +                hsum = sd->rLambFront.cieY;
652 +                rdf = sd->rf;
653 +        } else /* !inFront */ {
654 +                hsum = sd->rLambBack.cieY;
655 +                rdf = sd->rb;
656 +        }
657 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
658 +                hsum = .0;
659 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
660 +                hsum += sd->tLamb.cieY;
661 +                                        /* gather non-diffuse components */
662 +        i = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
663 +                        rdf != NULL) ? rdf->ncomp : 0;
664 +        while (i-- > 0) {               /* non-diffuse reflection */
665 +                cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
666 +                if (cd != NULL)
667 +                        hsum += cd->cTotal;
668 +        }
669 +        i = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
670 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
671 +        while (i-- > 0) {               /* non-diffuse transmission */
672 +                cd = (*sd->tf->comp[i].func->getCDist)(inVec, &sd->tf->comp[i]);
673 +                if (cd != NULL)
674 +                        hsum += cd->cTotal;
675 +        }
676 +        return hsum;
677 + }
678 +
679 + /* Sample BSDF direction based on the given random variable */
680 + SDError
681 + SDsampBSDF(SDValue *sv, FVECT ioVec, double randX, int sflags, const SDData *sd)
682 + {
683 +        SDError         ec;
684 +        FVECT           inVec;
685 +        int             inFront;
686 +        SDSpectralDF    *rdf;
687 +        double          rdiff;
688 +        float           coef[SDmaxCh];
689 +        int             i, j, n, nr;
690 +        SDComponent     *sdc;
691 +        const SDCDst    **cdarr = NULL;
692 +                                        /* check arguments */
693 +        if ((sv == NULL) | (ioVec == NULL) | (sd == NULL) |
694 +                        (randX < 0) | (randX >= 1.))
695 +                return SDEargument;
696 +                                        /* whose side are we on? */
697 +        VCOPY(inVec, ioVec);
698 +        inFront = (inVec[2] > 0);
699 +                                        /* remember diffuse portions */
700 +        if (inFront) {
701 +                *sv = sd->rLambFront;
702 +                rdf = sd->rf;
703 +        } else /* !inFront */ {
704 +                *sv = sd->rLambBack;
705 +                rdf = sd->rb;
706 +        }
707 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
708 +                sv->cieY = .0;
709 +        rdiff = sv->cieY;
710 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
711 +                sv->cieY += sd->tLamb.cieY;
712 +                                        /* gather non-diffuse components */
713 +        i = nr = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
714 +                        rdf != NULL) ? rdf->ncomp : 0;
715 +        j = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
716 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
717 +        n = i + j;
718 +        if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
719 +                return SDEmemory;
720 +        while (j-- > 0) {               /* non-diffuse transmission */
721 +                cdarr[i+j] = (*sd->tf->comp[j].func->getCDist)(inVec, &sd->tf->comp[j]);
722 +                if (cdarr[i+j] == NULL) {
723 +                        free(cdarr);
724 +                        return SDEmemory;
725 +                }
726 +                sv->cieY += cdarr[i+j]->cTotal;
727 +        }
728 +        while (i-- > 0) {               /* non-diffuse reflection */
729 +                cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
730 +                if (cdarr[i] == NULL) {
731 +                        free(cdarr);
732 +                        return SDEmemory;
733 +                }
734 +                sv->cieY += cdarr[i]->cTotal;
735 +        }
736 +        if (sv->cieY <= 1e-6) {         /* anything to sample? */
737 +                sv->cieY = .0;
738 +                memset(ioVec, 0, 3*sizeof(double));
739 +                return SDEnone;
740 +        }
741 +                                        /* scale random variable */
742 +        randX *= sv->cieY;
743 +                                        /* diffuse reflection? */
744 +        if (randX < rdiff) {
745 +                SDdiffuseSamp(ioVec, inFront, randX/rdiff);
746 +                goto done;
747 +        }
748 +        randX -= rdiff;
749 +                                        /* diffuse transmission? */
750 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
751 +                if (randX < sd->tLamb.cieY) {
752 +                        sv->spec = sd->tLamb.spec;
753 +                        SDdiffuseSamp(ioVec, !inFront, randX/sd->tLamb.cieY);
754 +                        goto done;
755 +                }
756 +                randX -= sd->tLamb.cieY;
757 +        }
758 +                                        /* else one of cumulative dist. */
759 +        for (i = 0; i < n && randX < cdarr[i]->cTotal; i++)
760 +                randX -= cdarr[i]->cTotal;
761 +        if (i >= n)
762 +                return SDEinternal;
763 +                                        /* compute sample direction */
764 +        sdc = (i < nr) ? &rdf->comp[i] : &sd->tf->comp[i-nr];
765 +        ec = (*sdc->func->sampCDist)(ioVec, randX/cdarr[i]->cTotal, cdarr[i]);
766 +        if (ec)
767 +                return ec;
768 +                                        /* compute color */
769 +        j = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
770 +        if (j <= 0) {
771 +                sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
772 +                                sd->name);
773 +                return SDEinternal;
774 +        }
775 +        sv->spec = sdc->cspec[0];
776 +        rdiff = coef[0];
777 +        while (--j) {
778 +                c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
779 +                rdiff += coef[j];
780 +        }
781 + done:
782 +        if (cdarr != NULL)
783 +                free(cdarr);
784 +                                        /* make sure everything is set */
785 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
786 +        return SDEnone;
787 + }
788 +
789 + /* Compute World->BSDF transform from surface normal and up (Y) vector */
790 + SDError
791 + SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
792 + {
793 +        if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
794 +                return SDEargument;
795 +        VCOPY(vMtx[2], sNrm);
796 +        if (normalize(vMtx[2]) == 0)
797 +                return SDEargument;
798 +        fcross(vMtx[0], uVec, vMtx[2]);
799 +        if (normalize(vMtx[0]) == 0)
800 +                return SDEargument;
801 +        fcross(vMtx[1], vMtx[2], vMtx[0]);
802 +        return SDEnone;
803 + }
804 +
805 + /* Compute inverse transform */
806 + SDError
807 + SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
808 + {
809 +        RREAL   mTmp[3][3];
810 +        double  d;
811 +
812 +        if ((iMtx == NULL) | (vMtx == NULL))
813 +                return SDEargument;
814 +                                        /* compute determinant */
815 +        mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
816 +        mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
817 +        mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
818 +        d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
819 +        if (d == 0) {
820 +                strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
821 +                return SDEargument;
822 +        }
823 +        d = 1./d;                       /* invert matrix */
824 +        mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
825 +        mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
826 +        mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
827 +        mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
828 +        mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
829 +        mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
830 +        mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
831 +        memcpy(iMtx, mTmp, sizeof(mTmp));
832 +        return SDEnone;
833 + }
834 +
835 + /* Transform and normalize direction (column) vector */
836 + SDError
837 + SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
838 + {
839 +        FVECT   vTmp;
840 +
841 +        if ((resVec == NULL) | (inpVec == NULL))
842 +                return SDEargument;
843 +        if (vMtx == NULL) {             /* assume they just want to normalize */
844 +                if (resVec != inpVec)
845 +                        VCOPY(resVec, inpVec);
846 +                return (normalize(resVec) > 0) ? SDEnone : SDEargument;
847 +        }
848 +        vTmp[0] = DOT(vMtx[0], inpVec);
849 +        vTmp[1] = DOT(vMtx[1], inpVec);
850 +        vTmp[2] = DOT(vMtx[2], inpVec);
851 +        if (normalize(vTmp) == 0)
852 +                return SDEargument;
853 +        VCOPY(resVec, vTmp);
854 +        return SDEnone;
855 + }
856 +
857 + /*################################################################*/
858 + /*######### DEPRECATED ROUTINES AWAITING PERMANENT REMOVAL #######*/
859 +
860 + /*
861   * Routines for handling BSDF data
862   */
863  
864   #include "standard.h"
9 #include "bsdf.h"
865   #include "paths.h"
11 #include "ezxml.h"
12 #include <ctype.h>
866  
867   #define MAXLATS         46              /* maximum number of latitudes */
868  
# Line 61 | Line 914 | static ANGLE_BASIS     abase_list[MAXABASES] = {
914  
915   static int      nabases = 3;    /* current number of defined bases */
916  
917 < #define  FEQ(a,b)       ((a)-(b) <= 1e-7 && (b)-(a) <= 1e-7)
917 > #define  FEQ(a,b)       ((a)-(b) <= 1e-6 && (b)-(a) <= 1e-6)
918  
919 < // returns the name of the given tag
919 > static int
920 > fequal(double a, double b)
921 > {
922 >        if (b != 0)
923 >                a = a/b - 1.;
924 >        return((a <= 1e-6) & (a >= -1e-6));
925 > }
926 >
927 > /* Returns the name of the given tag */
928   #ifdef ezxml_name
929   #undef ezxml_name
930   static char *
# Line 75 | Line 936 | ezxml_name(ezxml_t xml)
936   }
937   #endif
938  
939 < // returns the given tag's character content or empty string if none
939 > /* Returns the given tag's character content or empty string if none */
940   #ifdef ezxml_txt
941   #undef ezxml_txt
942   static char *
# Line 121 | Line 982 | ab_getndx(             /* get index corresponding to the given ve
982   {
983          ANGLE_BASIS  *ab = (ANGLE_BASIS *)p;
984          int     li, ndx;
985 <        double  pol, azi, d;
985 >        double  pol, azi;
986  
987          if ((v[2] < -1.0) | (v[2] > 1.0))
988                  return(-1);
# Line 211 | Line 1072 | load_angle_basis(      /* load custom BSDF angle basis */
1072          if (!abname || !*abname)
1073                  return;
1074          for (i = nabases; i--; )
1075 <                if (!strcmp(abname, abase_list[i].name))
1075 >                if (!strcasecmp(abname, abase_list[i].name))
1076                          return;         /* assume it's the same */
1077          if (nabases >= MAXABASES)
1078                  error(INTERNAL, "too many angle bases");
# Line 227 | Line 1088 | load_angle_basis(      /* load custom BSDF angle basis */
1088                  if (!i)
1089                          abase_list[nabases].lat[i].tmin =
1090                                          -abase_list[nabases].lat[i+1].tmin;
1091 <                else if (!FEQ(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
1091 >                else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
1092                                          "ThetaBounds"), "LowerTheta"))),
1093                                  abase_list[nabases].lat[i].tmin))
1094                          error(WARNING, "theta values disagree in custom basis");
# Line 239 | Line 1100 | load_angle_basis(      /* load custom BSDF angle basis */
1100   }
1101  
1102  
242 static double
243 to_meters(              /* return factor to convert given unit to meters */
244        const char *unit
245 )
246 {
247        if (unit == NULL) return(1.);           /* safe assumption? */
248        if (!strcasecmp(unit, "Meter")) return(1.);
249        if (!strcasecmp(unit, "Foot")) return(.3048);
250        if (!strcasecmp(unit, "Inch")) return(.0254);
251        if (!strcasecmp(unit, "Centimeter")) return(.01);
252        sprintf(errmsg, "unknown dimensional unit '%s'", unit);
253        error(USER, errmsg);
254 }
255
256
1103   static void
1104   load_geometry(          /* load geometric dimensions and description (if any) */
1105          struct BSDF_data *dp,
# Line 311 | Line 1157 | load_bsdf_data(                /* load BSDF distribution for this wa
1157                  return;
1158          }
1159          for (i = nabases; i--; )
1160 <                if (!strcmp(cbasis, abase_list[i].name)) {
1160 >                if (!strcasecmp(cbasis, abase_list[i].name)) {
1161                          dp->ninc = abase_list[i].nangles;
1162                          dp->ib_priv = (void *)&abase_list[i];
1163                          dp->ib_vec = ab_getvecR;
# Line 325 | Line 1171 | load_bsdf_data(                /* load BSDF distribution for this wa
1171                  return;
1172          }
1173          for (i = nabases; i--; )
1174 <                if (!strcmp(rbasis, abase_list[i].name)) {
1174 >                if (!strcasecmp(rbasis, abase_list[i].name)) {
1175                          dp->nout = abase_list[i].nangles;
1176                          dp->ob_priv = (void *)&abase_list[i];
1177                          dp->ob_vec = ab_getvec;
# Line 334 | Line 1180 | load_bsdf_data(                /* load BSDF distribution for this wa
1180                          break;
1181                  }
1182          if (i < 0) {
1183 <                sprintf(errmsg, "undefined RowAngleBasis '%s'", cbasis);
1183 >                sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1184                  error(WARNING, errmsg);
1185                  return;
1186          }
# Line 376 | Line 1222 | check_bsdf_data(       /* check that BSDF data is sane */
1222   )
1223   {
1224          double          *omega_iarr, *omega_oarr;
1225 <        double          dom, contrib, hemi_total, full_total;
1225 >        double          dom, hemi_total, full_total;
1226          int             nneg;
1227          FVECT           v;
1228          int             i, o;
# Line 391 | Line 1237 | check_bsdf_data(       /* check that BSDF data is sane */
1237          hemi_total = .0;
1238          for (i = dp->ninc; i--; ) {
1239                  dom = getBSDF_incohm(dp,i);
1240 <                if (dom <= .0) {
1240 >                if (dom <= 0) {
1241                          error(WARNING, "zero/negative incoming solid angle");
1242                          continue;
1243                  }
# Line 414 | Line 1260 | check_bsdf_data(       /* check that BSDF data is sane */
1260          hemi_total = .0;
1261          for (o = dp->nout; o--; ) {
1262                  dom = getBSDF_outohm(dp,o);
1263 <                if (dom <= .0) {
1263 >                if (dom <= 0) {
1264                          error(WARNING, "zero/negative outgoing solid angle");
1265                          continue;
1266                  }
# Line 438 | Line 1284 | check_bsdf_data(       /* check that BSDF data is sane */
1284                  hemi_total = .0;
1285                  for (o = dp->nout; o--; ) {
1286                          double  f = BSDF_value(dp,i,o);
1287 <                        if (f >= .0)
1287 >                        if (f >= 0)
1288                                  hemi_total += f*omega_oarr[o];
1289                          else {
1290                                  nneg += (f < -FTINY);
1291                                  BSDF_value(dp,i,o) = .0f;
1292                          }
1293                  }
1294 <                if (hemi_total > 1.02) {
1294 >                if (hemi_total > 1.01) {
1295                          sprintf(errmsg,
1296                          "incoming BSDF direction %d passes %.1f%% of light",
1297                                          i, 100.*hemi_total);
# Line 462 | Line 1308 | check_bsdf_data(       /* check that BSDF data is sane */
1308                  for (i = dp->ninc; i--; )
1309                          hemi_total += BSDF_value(dp,i,o) * omega_iarr[i];
1310  
1311 <                if (hemi_total > 1.02) {
1311 >                if (hemi_total > 1.01) {
1312                          sprintf(errmsg,
1313                          "outgoing BSDF direction %d collects %.1f%% of light",
1314                                          o, 100.*hemi_total);
# Line 471 | Line 1317 | check_bsdf_data(       /* check that BSDF data is sane */
1317                  full_total += hemi_total*omega_oarr[o];
1318          }
1319          full_total /= PI;
1320 <        if (full_total > 1.02) {
1321 <                sprintf(errmsg, "BSDF transfers %.1f%% of light",
1320 >        if (full_total > 1.00001) {
1321 >                sprintf(errmsg, "BSDF transfers %.4f%% of light",
1322                                  100.*full_total);
1323                  error(WARNING, errmsg);
1324          }
# Line 517 | Line 1363 | load_BSDF(             /* load BSDF data from file */
1363                  return(NULL);
1364          }
1365          wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
1366 <        load_angle_basis(ezxml_child(ezxml_child(wtl,
1367 <                                "DataDefinition"), "AngleBasis"));
1366 >        if (strcasecmp(ezxml_txt(ezxml_child(ezxml_child(wtl,
1367 >                        "DataDefinition"), "IncidentDataStructure")),
1368 >                        "Columns")) {
1369 >                sprintf(errmsg,
1370 >                        "BSDF \"%s\": unsupported IncidentDataStructure",
1371 >                                path);
1372 >                error(WARNING, errmsg);
1373 >                ezxml_free(fl);
1374 >                return(NULL);
1375 >        }
1376 >        for (wld = ezxml_child(ezxml_child(wtl,
1377 >                                "DataDefinition"), "AngleBasis");
1378 >                        wld != NULL; wld = wld->next)
1379 >                load_angle_basis(wld);
1380          dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
1381          load_geometry(dp, ezxml_child(wtl, "Material"));
1382          for (wld = ezxml_child(wtl, "WavelengthData");
1383                                  wld != NULL; wld = wld->next) {
1384 <                if (strcmp(ezxml_txt(ezxml_child(wld,"Wavelength")), "Visible"))
1384 >                if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1385 >                                "Visible"))
1386                          continue;
1387 <                wdb = ezxml_child(wld, "WavelengthDataBlock");
1388 <                if (wdb == NULL) continue;
1389 <                if (strcmp(ezxml_txt(ezxml_child(wdb,"WavelengthDataDirection")),
1387 >                for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1388 >                                wdb != NULL; wdb = wdb->next)
1389 >                        if (!strcasecmp(ezxml_txt(ezxml_child(wdb,
1390 >                                        "WavelengthDataDirection")),
1391                                          "Transmission Front"))
1392 <                        continue;
1393 <                load_bsdf_data(dp, wdb);        /* load front BTDF */
1394 <                break;                          /* ignore the rest */
1392 >                                break;
1393 >                if (wdb != NULL) {              /* load front BTDF */
1394 >                        load_bsdf_data(dp, wdb);
1395 >                        break;                  /* ignore the rest */
1396 >                }
1397          }
1398          ezxml_free(fl);                         /* done with XML file */
1399          if (!check_bsdf_data(dp)) {
# Line 575 | Line 1437 | r_BSDF_incvec(         /* compute random input vector at give
1437          if (!getBSDF_incvec(v, b, i))
1438                  return(0);
1439          rad = sqrt(getBSDF_incohm(b, i) / PI);
1440 <        multisamp(pert, 3, rv);
1440 >        SDmultiSamp(pert, 3, rv);
1441          for (j = 0; j < 3; j++)
1442                  v[j] += rad*(2.*pert[j] - 1.);
1443          if (xm != NULL)
# Line 600 | Line 1462 | r_BSDF_outvec(         /* compute random output vector at giv
1462          if (!getBSDF_outvec(v, b, o))
1463                  return(0);
1464          rad = sqrt(getBSDF_outohm(b, o) / PI);
1465 <        multisamp(pert, 3, rv);
1465 >        SDmultiSamp(pert, 3, rv);
1466          for (j = 0; j < 3; j++)
1467                  v[j] += rad*(2.*pert[j] - 1.);
1468          if (xm != NULL)
# Line 707 | Line 1569 | getBSDF_xfm(           /* compute BSDF orient. -> world orient.
1569          }
1570          return(1);
1571   }
1572 +
1573 + /*######### END DEPRECATED ROUTINES #######*/
1574 + /*################################################################*/

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines