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.10 by greg, Thu Jan 6 04:36:16 2011 UTC vs.
Revision 2.40 by greg, Mon Mar 5 15:27:08 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 +        while (n > MS_MAXDIM)           /* punt for higher dimensions */
505 +                t[--n] = rand()*(1./(RAND_MAX+.5));
506 +        nBits = (8*sizeof(bitmask_t) - 1) / n;
507 +        ndx = randX * (double)((bitmask_t)1 << (nBits*n));
508 +                                        /* get coordinate on Hilbert curve */
509 +        hilbert_i2c(n, nBits, ndx, coord);
510 +                                        /* convert back to [0,1) range */
511 +        scale = 1. / (double)((bitmask_t)1 << nBits);
512 +        while (n--)
513 +                t[n] = scale * ((double)coord[n] + rand()*(1./(RAND_MAX+.5)));
514 + }
515 +
516 + #undef MS_MAXDIM
517 +
518 + /* Generate diffuse hemispherical sample */
519 + static void
520 + SDdiffuseSamp(FVECT outVec, int outFront, double randX)
521 + {
522 +                                        /* convert to position on hemisphere */
523 +        SDmultiSamp(outVec, 2, randX);
524 +        SDsquare2disk(outVec, outVec[0], outVec[1]);
525 +        outVec[2] = 1. - outVec[0]*outVec[0] - outVec[1]*outVec[1];
526 +        if (outVec[2] > 0)              /* a bit of paranoia */
527 +                outVec[2] = sqrt(outVec[2]);
528 +        if (!outFront)                  /* going out back? */
529 +                outVec[2] = -outVec[2];
530 + }
531 +
532 + /* Query projected solid angle coverage for non-diffuse BSDF direction */
533 + SDError
534 + SDsizeBSDF(double *projSA, const FVECT v1, const RREAL *v2,
535 +                                int qflags, const SDData *sd)
536 + {
537 +        SDSpectralDF    *rdf, *tdf;
538 +        SDError         ec;
539 +        int             i;
540 +                                        /* check arguments */
541 +        if ((projSA == NULL) | (v1 == NULL) | (sd == NULL))
542 +                return SDEargument;
543 +                                        /* initialize extrema */
544 +        switch (qflags) {
545 +        case SDqueryMax:
546 +                projSA[0] = .0;
547 +                break;
548 +        case SDqueryMin+SDqueryMax:
549 +                projSA[1] = .0;
550 +                /* fall through */
551 +        case SDqueryMin:
552 +                projSA[0] = 10.;
553 +                break;
554 +        case 0:
555 +                return SDEargument;
556 +        }
557 +        if (v1[2] > 0)                  /* front surface query? */
558 +                rdf = sd->rf;
559 +        else
560 +                rdf = sd->rb;
561 +        tdf = sd->tf;
562 +        if (v2 != NULL)                 /* bidirectional? */
563 +                if (v1[2] > 0 ^ v2[2] > 0)
564 +                        rdf = NULL;
565 +                else
566 +                        tdf = NULL;
567 +        ec = SDEdata;                   /* run through components */
568 +        for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
569 +                ec = (*rdf->comp[i].func->queryProjSA)(projSA, v1, v2,
570 +                                                qflags, &rdf->comp[i]);
571 +                if (ec)
572 +                        return ec;
573 +        }
574 +        for (i = (tdf==NULL) ? 0 : tdf->ncomp; i--; ) {
575 +                ec = (*tdf->comp[i].func->queryProjSA)(projSA, v1, v2,
576 +                                                qflags, &tdf->comp[i]);
577 +                if (ec)
578 +                        return ec;
579 +        }
580 +        if (ec) {                       /* all diffuse? */
581 +                projSA[0] = M_PI;
582 +                if (qflags == SDqueryMin+SDqueryMax)
583 +                        projSA[1] = M_PI;
584 +        }
585 +        return SDEnone;
586 + }
587 +
588 + /* Return BSDF for the given incident and scattered ray vectors */
589 + SDError
590 + SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
591 + {
592 +        int             inFront, outFront;
593 +        SDSpectralDF    *sdf;
594 +        float           coef[SDmaxCh];
595 +        int             nch, i;
596 +                                        /* check arguments */
597 +        if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
598 +                return SDEargument;
599 +                                        /* whose side are we on? */
600 +        inFront = (inVec[2] > 0);
601 +        outFront = (outVec[2] > 0);
602 +                                        /* start with diffuse portion */
603 +        if (inFront & outFront) {
604 +                *sv = sd->rLambFront;
605 +                sdf = sd->rf;
606 +        } else if (!(inFront | outFront)) {
607 +                *sv = sd->rLambBack;
608 +                sdf = sd->rb;
609 +        } else /* inFront ^ outFront */ {
610 +                *sv = sd->tLamb;
611 +                sdf = sd->tf;
612 +        }
613 +        sv->cieY *= 1./M_PI;
614 +                                        /* add non-diffuse components */
615 +        i = (sdf != NULL) ? sdf->ncomp : 0;
616 +        while (i-- > 0) {
617 +                nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
618 +                                                        &sdf->comp[i]);
619 +                while (nch-- > 0) {
620 +                        c_cmix(&sv->spec, sv->cieY, &sv->spec,
621 +                                        coef[nch], &sdf->comp[i].cspec[nch]);
622 +                        sv->cieY += coef[nch];
623 +                }
624 +        }
625 +                                        /* make sure everything is set */
626 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
627 +        return SDEnone;
628 + }
629 +
630 + /* Compute directional hemispherical scattering at this incident angle */
631 + double
632 + SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
633 + {
634 +        double          hsum;
635 +        SDSpectralDF    *rdf;
636 +        const SDCDst    *cd;
637 +        int             i;
638 +                                        /* check arguments */
639 +        if ((inVec == NULL) | (sd == NULL))
640 +                return .0;
641 +                                        /* gather diffuse components */
642 +        if (inVec[2] > 0) {
643 +                hsum = sd->rLambFront.cieY;
644 +                rdf = sd->rf;
645 +        } else /* !inFront */ {
646 +                hsum = sd->rLambBack.cieY;
647 +                rdf = sd->rb;
648 +        }
649 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
650 +                hsum = .0;
651 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
652 +                hsum += sd->tLamb.cieY;
653 +                                        /* gather non-diffuse components */
654 +        i = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
655 +                        rdf != NULL) ? rdf->ncomp : 0;
656 +        while (i-- > 0) {               /* non-diffuse reflection */
657 +                cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
658 +                if (cd != NULL)
659 +                        hsum += cd->cTotal;
660 +        }
661 +        i = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
662 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
663 +        while (i-- > 0) {               /* non-diffuse transmission */
664 +                cd = (*sd->tf->comp[i].func->getCDist)(inVec, &sd->tf->comp[i]);
665 +                if (cd != NULL)
666 +                        hsum += cd->cTotal;
667 +        }
668 +        return hsum;
669 + }
670 +
671 + /* Sample BSDF direction based on the given random variable */
672 + SDError
673 + SDsampBSDF(SDValue *sv, FVECT ioVec, double randX, int sflags, const SDData *sd)
674 + {
675 +        SDError         ec;
676 +        FVECT           inVec;
677 +        int             inFront;
678 +        SDSpectralDF    *rdf;
679 +        double          rdiff;
680 +        float           coef[SDmaxCh];
681 +        int             i, j, n, nr;
682 +        SDComponent     *sdc;
683 +        const SDCDst    **cdarr = NULL;
684 +                                        /* check arguments */
685 +        if ((sv == NULL) | (ioVec == NULL) | (sd == NULL) |
686 +                        (randX < 0) | (randX >= 1.))
687 +                return SDEargument;
688 +                                        /* whose side are we on? */
689 +        VCOPY(inVec, ioVec);
690 +        inFront = (inVec[2] > 0);
691 +                                        /* remember diffuse portions */
692 +        if (inFront) {
693 +                *sv = sd->rLambFront;
694 +                rdf = sd->rf;
695 +        } else /* !inFront */ {
696 +                *sv = sd->rLambBack;
697 +                rdf = sd->rb;
698 +        }
699 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
700 +                sv->cieY = .0;
701 +        rdiff = sv->cieY;
702 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
703 +                sv->cieY += sd->tLamb.cieY;
704 +                                        /* gather non-diffuse components */
705 +        i = nr = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
706 +                        rdf != NULL) ? rdf->ncomp : 0;
707 +        j = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
708 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
709 +        n = i + j;
710 +        if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
711 +                return SDEmemory;
712 +        while (j-- > 0) {               /* non-diffuse transmission */
713 +                cdarr[i+j] = (*sd->tf->comp[j].func->getCDist)(inVec, &sd->tf->comp[j]);
714 +                if (cdarr[i+j] == NULL) {
715 +                        free(cdarr);
716 +                        return SDEmemory;
717 +                }
718 +                sv->cieY += cdarr[i+j]->cTotal;
719 +        }
720 +        while (i-- > 0) {               /* non-diffuse reflection */
721 +                cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
722 +                if (cdarr[i] == NULL) {
723 +                        free(cdarr);
724 +                        return SDEmemory;
725 +                }
726 +                sv->cieY += cdarr[i]->cTotal;
727 +        }
728 +        if (sv->cieY <= 1e-6) {         /* anything to sample? */
729 +                sv->cieY = .0;
730 +                memset(ioVec, 0, 3*sizeof(double));
731 +                return SDEnone;
732 +        }
733 +                                        /* scale random variable */
734 +        randX *= sv->cieY;
735 +                                        /* diffuse reflection? */
736 +        if (randX < rdiff) {
737 +                SDdiffuseSamp(ioVec, inFront, randX/rdiff);
738 +                goto done;
739 +        }
740 +        randX -= rdiff;
741 +                                        /* diffuse transmission? */
742 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
743 +                if (randX < sd->tLamb.cieY) {
744 +                        sv->spec = sd->tLamb.spec;
745 +                        SDdiffuseSamp(ioVec, !inFront, randX/sd->tLamb.cieY);
746 +                        goto done;
747 +                }
748 +                randX -= sd->tLamb.cieY;
749 +        }
750 +                                        /* else one of cumulative dist. */
751 +        for (i = 0; i < n && randX < cdarr[i]->cTotal; i++)
752 +                randX -= cdarr[i]->cTotal;
753 +        if (i >= n)
754 +                return SDEinternal;
755 +                                        /* compute sample direction */
756 +        sdc = (i < nr) ? &rdf->comp[i] : &sd->tf->comp[i-nr];
757 +        ec = (*sdc->func->sampCDist)(ioVec, randX/cdarr[i]->cTotal, cdarr[i]);
758 +        if (ec)
759 +                return ec;
760 +                                        /* compute color */
761 +        j = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
762 +        if (j <= 0) {
763 +                sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
764 +                                sd->name);
765 +                return SDEinternal;
766 +        }
767 +        sv->spec = sdc->cspec[0];
768 +        rdiff = coef[0];
769 +        while (--j) {
770 +                c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
771 +                rdiff += coef[j];
772 +        }
773 + done:
774 +        if (cdarr != NULL)
775 +                free(cdarr);
776 +                                        /* make sure everything is set */
777 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
778 +        return SDEnone;
779 + }
780 +
781 + /* Compute World->BSDF transform from surface normal and up (Y) vector */
782 + SDError
783 + SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
784 + {
785 +        if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
786 +                return SDEargument;
787 +        VCOPY(vMtx[2], sNrm);
788 +        if (normalize(vMtx[2]) == 0)
789 +                return SDEargument;
790 +        fcross(vMtx[0], uVec, vMtx[2]);
791 +        if (normalize(vMtx[0]) == 0)
792 +                return SDEargument;
793 +        fcross(vMtx[1], vMtx[2], vMtx[0]);
794 +        return SDEnone;
795 + }
796 +
797 + /* Compute inverse transform */
798 + SDError
799 + SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
800 + {
801 +        RREAL   mTmp[3][3];
802 +        double  d;
803 +
804 +        if ((iMtx == NULL) | (vMtx == NULL))
805 +                return SDEargument;
806 +                                        /* compute determinant */
807 +        mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
808 +        mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
809 +        mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
810 +        d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
811 +        if (d == 0) {
812 +                strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
813 +                return SDEargument;
814 +        }
815 +        d = 1./d;                       /* invert matrix */
816 +        mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
817 +        mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
818 +        mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
819 +        mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
820 +        mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
821 +        mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
822 +        mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
823 +        memcpy(iMtx, mTmp, sizeof(mTmp));
824 +        return SDEnone;
825 + }
826 +
827 + /* Transform and normalize direction (column) vector */
828 + SDError
829 + SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
830 + {
831 +        FVECT   vTmp;
832 +
833 +        if ((resVec == NULL) | (inpVec == NULL))
834 +                return SDEargument;
835 +        if (vMtx == NULL) {             /* assume they just want to normalize */
836 +                if (resVec != inpVec)
837 +                        VCOPY(resVec, inpVec);
838 +                return (normalize(resVec) > 0) ? SDEnone : SDEargument;
839 +        }
840 +        vTmp[0] = DOT(vMtx[0], inpVec);
841 +        vTmp[1] = DOT(vMtx[1], inpVec);
842 +        vTmp[2] = DOT(vMtx[2], inpVec);
843 +        if (normalize(vTmp) == 0)
844 +                return SDEargument;
845 +        VCOPY(resVec, vTmp);
846 +        return SDEnone;
847 + }
848 +
849 + /*################################################################*/
850 + /*######### DEPRECATED ROUTINES AWAITING PERMANENT REMOVAL #######*/
851 +
852 + /*
853   * Routines for handling BSDF data
854   */
855  
856   #include "standard.h"
9 #include "bsdf.h"
857   #include "paths.h"
11 #include "ezxml.h"
12 #include <ctype.h>
858  
859   #define MAXLATS         46              /* maximum number of latitudes */
860  
# Line 66 | Line 911 | static int     nabases = 3;    /* current number of defined b
911   static int
912   fequal(double a, double b)
913   {
914 <        if (b != .0)
914 >        if (b != 0)
915                  a = a/b - 1.;
916          return((a <= 1e-6) & (a >= -1e-6));
917   }
918  
919 < // returns the name of the given tag
919 > /* Returns the name of the given tag */
920   #ifdef ezxml_name
921   #undef ezxml_name
922   static char *
# Line 83 | Line 928 | ezxml_name(ezxml_t xml)
928   }
929   #endif
930  
931 < // returns the given tag's character content or empty string if none
931 > /* Returns the given tag's character content or empty string if none */
932   #ifdef ezxml_txt
933   #undef ezxml_txt
934   static char *
# Line 129 | Line 974 | ab_getndx(             /* get index corresponding to the given ve
974   {
975          ANGLE_BASIS  *ab = (ANGLE_BASIS *)p;
976          int     li, ndx;
977 <        double  pol, azi, d;
977 >        double  pol, azi;
978  
979          if ((v[2] < -1.0) | (v[2] > 1.0))
980                  return(-1);
# Line 219 | Line 1064 | load_angle_basis(      /* load custom BSDF angle basis */
1064          if (!abname || !*abname)
1065                  return;
1066          for (i = nabases; i--; )
1067 <                if (!strcmp(abname, abase_list[i].name))
1067 >                if (!strcasecmp(abname, abase_list[i].name))
1068                          return;         /* assume it's the same */
1069          if (nabases >= MAXABASES)
1070                  error(INTERNAL, "too many angle bases");
# Line 247 | Line 1092 | load_angle_basis(      /* load custom BSDF angle basis */
1092   }
1093  
1094  
250 static double
251 to_meters(              /* return factor to convert given unit to meters */
252        const char *unit
253 )
254 {
255        if (unit == NULL) return(1.);           /* safe assumption? */
256        if (!strcasecmp(unit, "Meter")) return(1.);
257        if (!strcasecmp(unit, "Foot")) return(.3048);
258        if (!strcasecmp(unit, "Inch")) return(.0254);
259        if (!strcasecmp(unit, "Centimeter")) return(.01);
260        if (!strcasecmp(unit, "Millimeter")) return(.001);
261        sprintf(errmsg, "unknown dimensional unit '%s'", unit);
262        error(USER, errmsg);
263 }
264
265
1095   static void
1096   load_geometry(          /* load geometric dimensions and description (if any) */
1097          struct BSDF_data *dp,
# Line 320 | Line 1149 | load_bsdf_data(                /* load BSDF distribution for this wa
1149                  return;
1150          }
1151          for (i = nabases; i--; )
1152 <                if (!strcmp(cbasis, abase_list[i].name)) {
1152 >                if (!strcasecmp(cbasis, abase_list[i].name)) {
1153                          dp->ninc = abase_list[i].nangles;
1154                          dp->ib_priv = (void *)&abase_list[i];
1155                          dp->ib_vec = ab_getvecR;
# Line 334 | Line 1163 | load_bsdf_data(                /* load BSDF distribution for this wa
1163                  return;
1164          }
1165          for (i = nabases; i--; )
1166 <                if (!strcmp(rbasis, abase_list[i].name)) {
1166 >                if (!strcasecmp(rbasis, abase_list[i].name)) {
1167                          dp->nout = abase_list[i].nangles;
1168                          dp->ob_priv = (void *)&abase_list[i];
1169                          dp->ob_vec = ab_getvec;
# Line 343 | Line 1172 | load_bsdf_data(                /* load BSDF distribution for this wa
1172                          break;
1173                  }
1174          if (i < 0) {
1175 <                sprintf(errmsg, "undefined RowAngleBasis '%s'", cbasis);
1175 >                sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1176                  error(WARNING, errmsg);
1177                  return;
1178          }
# Line 385 | Line 1214 | check_bsdf_data(       /* check that BSDF data is sane */
1214   )
1215   {
1216          double          *omega_iarr, *omega_oarr;
1217 <        double          dom, contrib, hemi_total, full_total;
1217 >        double          dom, hemi_total, full_total;
1218          int             nneg;
1219          FVECT           v;
1220          int             i, o;
# Line 400 | Line 1229 | check_bsdf_data(       /* check that BSDF data is sane */
1229          hemi_total = .0;
1230          for (i = dp->ninc; i--; ) {
1231                  dom = getBSDF_incohm(dp,i);
1232 <                if (dom <= .0) {
1232 >                if (dom <= 0) {
1233                          error(WARNING, "zero/negative incoming solid angle");
1234                          continue;
1235                  }
# Line 423 | Line 1252 | check_bsdf_data(       /* check that BSDF data is sane */
1252          hemi_total = .0;
1253          for (o = dp->nout; o--; ) {
1254                  dom = getBSDF_outohm(dp,o);
1255 <                if (dom <= .0) {
1255 >                if (dom <= 0) {
1256                          error(WARNING, "zero/negative outgoing solid angle");
1257                          continue;
1258                  }
# Line 447 | Line 1276 | check_bsdf_data(       /* check that BSDF data is sane */
1276                  hemi_total = .0;
1277                  for (o = dp->nout; o--; ) {
1278                          double  f = BSDF_value(dp,i,o);
1279 <                        if (f >= .0)
1279 >                        if (f >= 0)
1280                                  hemi_total += f*omega_oarr[o];
1281                          else {
1282                                  nneg += (f < -FTINY);
# Line 535 | Line 1364 | load_BSDF(             /* load BSDF data from file */
1364                  error(WARNING, errmsg);
1365                  ezxml_free(fl);
1366                  return(NULL);
1367 <        }              
1368 <        load_angle_basis(ezxml_child(ezxml_child(wtl,
1369 <                                "DataDefinition"), "AngleBasis"));
1367 >        }
1368 >        for (wld = ezxml_child(ezxml_child(wtl,
1369 >                                "DataDefinition"), "AngleBasis");
1370 >                        wld != NULL; wld = wld->next)
1371 >                load_angle_basis(wld);
1372          dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
1373          load_geometry(dp, ezxml_child(wtl, "Material"));
1374          for (wld = ezxml_child(wtl, "WavelengthData");
1375                                  wld != NULL; wld = wld->next) {
1376 <                if (strcmp(ezxml_txt(ezxml_child(wld,"Wavelength")), "Visible"))
1376 >                if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1377 >                                "Visible"))
1378                          continue;
1379 <                wdb = ezxml_child(wld, "WavelengthDataBlock");
1380 <                if (wdb == NULL) continue;
1381 <                if (strcmp(ezxml_txt(ezxml_child(wdb,"WavelengthDataDirection")),
1379 >                for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1380 >                                wdb != NULL; wdb = wdb->next)
1381 >                        if (!strcasecmp(ezxml_txt(ezxml_child(wdb,
1382 >                                        "WavelengthDataDirection")),
1383                                          "Transmission Front"))
1384 <                        continue;
1385 <                load_bsdf_data(dp, wdb);        /* load front BTDF */
1386 <                break;                          /* ignore the rest */
1384 >                                break;
1385 >                if (wdb != NULL) {              /* load front BTDF */
1386 >                        load_bsdf_data(dp, wdb);
1387 >                        break;                  /* ignore the rest */
1388 >                }
1389          }
1390          ezxml_free(fl);                         /* done with XML file */
1391          if (!check_bsdf_data(dp)) {
# Line 726 | Line 1561 | getBSDF_xfm(           /* compute BSDF orient. -> world orient.
1561          }
1562          return(1);
1563   }
1564 +
1565 + /*######### END DEPRECATED ROUTINES #######*/
1566 + /*################################################################*/

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines