ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf.c
Revision: 2.31
Committed: Fri Jun 10 01:11:26 2011 UTC (12 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.30: +2 -1 lines
Log Message:
Added missing header

File Contents

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