ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf.c
Revision: 2.41
Committed: Sat Jun 23 16:47:39 2012 UTC (11 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.40: +12 -4 lines
Log Message:
Fixed incorrect call to multisamp()

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: bsdf.c,v 2.40 2012/03/05 15:27:08 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 <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"
865 #include "paths.h"
866
867 #define MAXLATS 46 /* maximum number of latitudes */
868
869 /* BSDF angle specification */
870 typedef struct {
871 char name[64]; /* basis name */
872 int nangles; /* total number of directions */
873 struct {
874 float tmin; /* starting theta */
875 short nphis; /* number of phis (0 term) */
876 } lat[MAXLATS+1]; /* latitudes */
877 } ANGLE_BASIS;
878
879 #define MAXABASES 7 /* limit on defined bases */
880
881 static ANGLE_BASIS abase_list[MAXABASES] = {
882 {
883 "LBNL/Klems Full", 145,
884 { {-5., 1},
885 {5., 8},
886 {15., 16},
887 {25., 20},
888 {35., 24},
889 {45., 24},
890 {55., 24},
891 {65., 16},
892 {75., 12},
893 {90., 0} }
894 }, {
895 "LBNL/Klems Half", 73,
896 { {-6.5, 1},
897 {6.5, 8},
898 {19.5, 12},
899 {32.5, 16},
900 {46.5, 20},
901 {61.5, 12},
902 {76.5, 4},
903 {90., 0} }
904 }, {
905 "LBNL/Klems Quarter", 41,
906 { {-9., 1},
907 {9., 8},
908 {27., 12},
909 {46., 12},
910 {66., 8},
911 {90., 0} }
912 }
913 };
914
915 static int nabases = 3; /* current number of defined bases */
916
917 #define FEQ(a,b) ((a)-(b) <= 1e-6 && (b)-(a) <= 1e-6)
918
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 *
931 ezxml_name(ezxml_t xml)
932 {
933 if (xml == NULL)
934 return(NULL);
935 return(xml->name);
936 }
937 #endif
938
939 /* Returns the given tag's character content or empty string if none */
940 #ifdef ezxml_txt
941 #undef ezxml_txt
942 static char *
943 ezxml_txt(ezxml_t xml)
944 {
945 if (xml == NULL)
946 return("");
947 return(xml->txt);
948 }
949 #endif
950
951
952 static int
953 ab_getvec( /* get vector for this angle basis index */
954 FVECT v,
955 int ndx,
956 void *p
957 )
958 {
959 ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
960 int li;
961 double pol, azi, d;
962
963 if ((ndx < 0) | (ndx >= ab->nangles))
964 return(0);
965 for (li = 0; ndx >= ab->lat[li].nphis; li++)
966 ndx -= ab->lat[li].nphis;
967 pol = PI/180.*0.5*(ab->lat[li].tmin + ab->lat[li+1].tmin);
968 azi = 2.*PI*ndx/ab->lat[li].nphis;
969 v[2] = d = cos(pol);
970 d = sqrt(1. - d*d); /* sin(pol) */
971 v[0] = cos(azi)*d;
972 v[1] = sin(azi)*d;
973 return(1);
974 }
975
976
977 static int
978 ab_getndx( /* get index corresponding to the given vector */
979 FVECT v,
980 void *p
981 )
982 {
983 ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
984 int li, ndx;
985 double pol, azi;
986
987 if ((v[2] < -1.0) | (v[2] > 1.0))
988 return(-1);
989 pol = 180.0/PI*acos(v[2]);
990 azi = 180.0/PI*atan2(v[1], v[0]);
991 if (azi < 0.0) azi += 360.0;
992 for (li = 1; ab->lat[li].tmin <= pol; li++)
993 if (!ab->lat[li].nphis)
994 return(-1);
995 --li;
996 ndx = (int)((1./360.)*azi*ab->lat[li].nphis + 0.5);
997 if (ndx >= ab->lat[li].nphis) ndx = 0;
998 while (li--)
999 ndx += ab->lat[li].nphis;
1000 return(ndx);
1001 }
1002
1003
1004 static double
1005 ab_getohm( /* get solid angle for this angle basis index */
1006 int ndx,
1007 void *p
1008 )
1009 {
1010 ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
1011 int li;
1012 double theta, theta1;
1013
1014 if ((ndx < 0) | (ndx >= ab->nangles))
1015 return(0);
1016 for (li = 0; ndx >= ab->lat[li].nphis; li++)
1017 ndx -= ab->lat[li].nphis;
1018 theta1 = PI/180. * ab->lat[li+1].tmin;
1019 if (ab->lat[li].nphis == 1) { /* special case */
1020 if (ab->lat[li].tmin > FTINY)
1021 error(USER, "unsupported BSDF coordinate system");
1022 return(2.*PI*(1. - cos(theta1)));
1023 }
1024 theta = PI/180. * ab->lat[li].tmin;
1025 return(2.*PI*(cos(theta) - cos(theta1))/(double)ab->lat[li].nphis);
1026 }
1027
1028
1029 static int
1030 ab_getvecR( /* get reverse vector for this angle basis index */
1031 FVECT v,
1032 int ndx,
1033 void *p
1034 )
1035 {
1036 if (!ab_getvec(v, ndx, p))
1037 return(0);
1038
1039 v[0] = -v[0];
1040 v[1] = -v[1];
1041 v[2] = -v[2];
1042
1043 return(1);
1044 }
1045
1046
1047 static int
1048 ab_getndxR( /* get index corresponding to the reverse vector */
1049 FVECT v,
1050 void *p
1051 )
1052 {
1053 FVECT v2;
1054
1055 v2[0] = -v[0];
1056 v2[1] = -v[1];
1057 v2[2] = -v[2];
1058
1059 return ab_getndx(v2, p);
1060 }
1061
1062
1063 static void
1064 load_angle_basis( /* load custom BSDF angle basis */
1065 ezxml_t wab
1066 )
1067 {
1068 char *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
1069 ezxml_t wbb;
1070 int i;
1071
1072 if (!abname || !*abname)
1073 return;
1074 for (i = nabases; i--; )
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");
1079 strcpy(abase_list[nabases].name, abname);
1080 abase_list[nabases].nangles = 0;
1081 for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
1082 wbb != NULL; i++, wbb = wbb->next) {
1083 if (i >= MAXLATS)
1084 error(INTERNAL, "too many latitudes in custom basis");
1085 abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
1086 ezxml_child(ezxml_child(wbb,
1087 "ThetaBounds"), "UpperTheta")));
1088 if (!i)
1089 abase_list[nabases].lat[i].tmin =
1090 -abase_list[nabases].lat[i+1].tmin;
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");
1095 abase_list[nabases].nangles +=
1096 abase_list[nabases].lat[i].nphis =
1097 atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
1098 }
1099 abase_list[nabases++].lat[i].nphis = 0;
1100 }
1101
1102
1103 static void
1104 load_geometry( /* load geometric dimensions and description (if any) */
1105 struct BSDF_data *dp,
1106 ezxml_t wdb
1107 )
1108 {
1109 ezxml_t geom;
1110 double cfact;
1111 const char *fmt, *mgfstr;
1112
1113 dp->dim[0] = dp->dim[1] = dp->dim[2] = 0;
1114 dp->mgf = NULL;
1115 if ((geom = ezxml_child(wdb, "Width")) != NULL)
1116 dp->dim[0] = atof(ezxml_txt(geom)) *
1117 to_meters(ezxml_attr(geom, "unit"));
1118 if ((geom = ezxml_child(wdb, "Height")) != NULL)
1119 dp->dim[1] = atof(ezxml_txt(geom)) *
1120 to_meters(ezxml_attr(geom, "unit"));
1121 if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
1122 dp->dim[2] = atof(ezxml_txt(geom)) *
1123 to_meters(ezxml_attr(geom, "unit"));
1124 if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
1125 (mgfstr = ezxml_txt(geom)) == NULL)
1126 return;
1127 if ((fmt = ezxml_attr(geom, "format")) != NULL &&
1128 strcasecmp(fmt, "MGF")) {
1129 sprintf(errmsg, "unrecognized geometry format '%s'", fmt);
1130 error(WARNING, errmsg);
1131 return;
1132 }
1133 cfact = to_meters(ezxml_attr(geom, "unit"));
1134 dp->mgf = (char *)malloc(strlen(mgfstr)+32);
1135 if (dp->mgf == NULL)
1136 error(SYSTEM, "out of memory in load_geometry");
1137 if (cfact < 0.99 || cfact > 1.01)
1138 sprintf(dp->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
1139 else
1140 strcpy(dp->mgf, mgfstr);
1141 }
1142
1143
1144 static void
1145 load_bsdf_data( /* load BSDF distribution for this wavelength */
1146 struct BSDF_data *dp,
1147 ezxml_t wdb
1148 )
1149 {
1150 char *cbasis = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
1151 char *rbasis = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
1152 char *sdata;
1153 int i;
1154
1155 if ((!cbasis || !*cbasis) | (!rbasis || !*rbasis)) {
1156 error(WARNING, "missing column/row basis for BSDF");
1157 return;
1158 }
1159 for (i = nabases; i--; )
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;
1164 dp->ib_ndx = ab_getndxR;
1165 dp->ib_ohm = ab_getohm;
1166 break;
1167 }
1168 if (i < 0) {
1169 sprintf(errmsg, "undefined ColumnAngleBasis '%s'", cbasis);
1170 error(WARNING, errmsg);
1171 return;
1172 }
1173 for (i = nabases; i--; )
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;
1178 dp->ob_ndx = ab_getndx;
1179 dp->ob_ohm = ab_getohm;
1180 break;
1181 }
1182 if (i < 0) {
1183 sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1184 error(WARNING, errmsg);
1185 return;
1186 }
1187 /* read BSDF data */
1188 sdata = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
1189 if (!sdata || !*sdata) {
1190 error(WARNING, "missing BSDF ScatteringData");
1191 return;
1192 }
1193 dp->bsdf = (float *)malloc(sizeof(float)*dp->ninc*dp->nout);
1194 if (dp->bsdf == NULL)
1195 error(SYSTEM, "out of memory in load_bsdf_data");
1196 for (i = 0; i < dp->ninc*dp->nout; i++) {
1197 char *sdnext = fskip(sdata);
1198 if (sdnext == NULL) {
1199 error(WARNING, "bad/missing BSDF ScatteringData");
1200 free(dp->bsdf); dp->bsdf = NULL;
1201 return;
1202 }
1203 while (*sdnext && isspace(*sdnext))
1204 sdnext++;
1205 if (*sdnext == ',') sdnext++;
1206 dp->bsdf[i] = atof(sdata);
1207 sdata = sdnext;
1208 }
1209 while (isspace(*sdata))
1210 sdata++;
1211 if (*sdata) {
1212 sprintf(errmsg, "%d extra characters after BSDF ScatteringData",
1213 (int)strlen(sdata));
1214 error(WARNING, errmsg);
1215 }
1216 }
1217
1218
1219 static int
1220 check_bsdf_data( /* check that BSDF data is sane */
1221 struct BSDF_data *dp
1222 )
1223 {
1224 double *omega_iarr, *omega_oarr;
1225 double dom, hemi_total, full_total;
1226 int nneg;
1227 FVECT v;
1228 int i, o;
1229
1230 if (dp == NULL || dp->bsdf == NULL)
1231 return(0);
1232 omega_iarr = (double *)calloc(dp->ninc, sizeof(double));
1233 omega_oarr = (double *)calloc(dp->nout, sizeof(double));
1234 if ((omega_iarr == NULL) | (omega_oarr == NULL))
1235 error(SYSTEM, "out of memory in check_bsdf_data");
1236 /* incoming projected solid angles */
1237 hemi_total = .0;
1238 for (i = dp->ninc; i--; ) {
1239 dom = getBSDF_incohm(dp,i);
1240 if (dom <= 0) {
1241 error(WARNING, "zero/negative incoming solid angle");
1242 continue;
1243 }
1244 if (!getBSDF_incvec(v,dp,i) || v[2] > FTINY) {
1245 error(WARNING, "illegal incoming BSDF direction");
1246 free(omega_iarr); free(omega_oarr);
1247 return(0);
1248 }
1249 hemi_total += omega_iarr[i] = dom * -v[2];
1250 }
1251 if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1252 sprintf(errmsg, "incoming BSDF hemisphere off by %.1f%%",
1253 100.*(hemi_total/PI - 1.));
1254 error(WARNING, errmsg);
1255 }
1256 dom = PI / hemi_total; /* fix normalization */
1257 for (i = dp->ninc; i--; )
1258 omega_iarr[i] *= dom;
1259 /* outgoing projected solid angles */
1260 hemi_total = .0;
1261 for (o = dp->nout; o--; ) {
1262 dom = getBSDF_outohm(dp,o);
1263 if (dom <= 0) {
1264 error(WARNING, "zero/negative outgoing solid angle");
1265 continue;
1266 }
1267 if (!getBSDF_outvec(v,dp,o) || v[2] < -FTINY) {
1268 error(WARNING, "illegal outgoing BSDF direction");
1269 free(omega_iarr); free(omega_oarr);
1270 return(0);
1271 }
1272 hemi_total += omega_oarr[o] = dom * v[2];
1273 }
1274 if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1275 sprintf(errmsg, "outgoing BSDF hemisphere off by %.1f%%",
1276 100.*(hemi_total/PI - 1.));
1277 error(WARNING, errmsg);
1278 }
1279 dom = PI / hemi_total; /* fix normalization */
1280 for (o = dp->nout; o--; )
1281 omega_oarr[o] *= dom;
1282 nneg = 0; /* check outgoing totals */
1283 for (i = 0; i < dp->ninc; i++) {
1284 hemi_total = .0;
1285 for (o = dp->nout; o--; ) {
1286 double f = BSDF_value(dp,i,o);
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.01) {
1295 sprintf(errmsg,
1296 "incoming BSDF direction %d passes %.1f%% of light",
1297 i, 100.*hemi_total);
1298 error(WARNING, errmsg);
1299 }
1300 }
1301 if (nneg) {
1302 sprintf(errmsg, "%d negative BSDF values (ignored)", nneg);
1303 error(WARNING, errmsg);
1304 }
1305 full_total = .0; /* reverse roles and check again */
1306 for (o = 0; o < dp->nout; o++) {
1307 hemi_total = .0;
1308 for (i = dp->ninc; i--; )
1309 hemi_total += BSDF_value(dp,i,o) * omega_iarr[i];
1310
1311 if (hemi_total > 1.01) {
1312 sprintf(errmsg,
1313 "outgoing BSDF direction %d collects %.1f%% of light",
1314 o, 100.*hemi_total);
1315 error(WARNING, errmsg);
1316 }
1317 full_total += hemi_total*omega_oarr[o];
1318 }
1319 full_total /= PI;
1320 if (full_total > 1.00001) {
1321 sprintf(errmsg, "BSDF transfers %.4f%% of light",
1322 100.*full_total);
1323 error(WARNING, errmsg);
1324 }
1325 free(omega_iarr); free(omega_oarr);
1326 return(1);
1327 }
1328
1329
1330 struct BSDF_data *
1331 load_BSDF( /* load BSDF data from file */
1332 char *fname
1333 )
1334 {
1335 char *path;
1336 ezxml_t fl, wtl, wld, wdb;
1337 struct BSDF_data *dp;
1338
1339 path = getpath(fname, getrlibpath(), R_OK);
1340 if (path == NULL) {
1341 sprintf(errmsg, "cannot find BSDF file \"%s\"", fname);
1342 error(WARNING, errmsg);
1343 return(NULL);
1344 }
1345 fl = ezxml_parse_file(path);
1346 if (fl == NULL) {
1347 sprintf(errmsg, "cannot open BSDF \"%s\"", path);
1348 error(WARNING, errmsg);
1349 return(NULL);
1350 }
1351 if (ezxml_error(fl)[0]) {
1352 sprintf(errmsg, "BSDF \"%s\" %s", path, ezxml_error(fl));
1353 error(WARNING, errmsg);
1354 ezxml_free(fl);
1355 return(NULL);
1356 }
1357 if (strcmp(ezxml_name(fl), "WindowElement")) {
1358 sprintf(errmsg,
1359 "BSDF \"%s\": top level node not 'WindowElement'",
1360 path);
1361 error(WARNING, errmsg);
1362 ezxml_free(fl);
1363 return(NULL);
1364 }
1365 wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
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 (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1385 "Visible"))
1386 continue;
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 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)) {
1400 sprintf(errmsg, "bad/missing BTDF data in \"%s\"", path);
1401 error(WARNING, errmsg);
1402 free_BSDF(dp);
1403 dp = NULL;
1404 }
1405 return(dp);
1406 }
1407
1408
1409 void
1410 free_BSDF( /* free BSDF data structure */
1411 struct BSDF_data *b
1412 )
1413 {
1414 if (b == NULL)
1415 return;
1416 if (b->mgf != NULL)
1417 free(b->mgf);
1418 if (b->bsdf != NULL)
1419 free(b->bsdf);
1420 free(b);
1421 }
1422
1423
1424 int
1425 r_BSDF_incvec( /* compute random input vector at given location */
1426 FVECT v,
1427 struct BSDF_data *b,
1428 int i,
1429 double rv,
1430 MAT4 xm
1431 )
1432 {
1433 FVECT pert;
1434 double rad;
1435 int j;
1436
1437 if (!getBSDF_incvec(v, b, i))
1438 return(0);
1439 rad = sqrt(getBSDF_incohm(b, i) / PI);
1440 SDmultiSamp(pert, 3, rv);
1441 for (j = 0; j < 3; j++)
1442 v[j] += rad*(2.*pert[j] - 1.);
1443 if (xm != NULL)
1444 multv3(v, v, xm);
1445 return(normalize(v) != 0.0);
1446 }
1447
1448
1449 int
1450 r_BSDF_outvec( /* compute random output vector at given location */
1451 FVECT v,
1452 struct BSDF_data *b,
1453 int o,
1454 double rv,
1455 MAT4 xm
1456 )
1457 {
1458 FVECT pert;
1459 double rad;
1460 int j;
1461
1462 if (!getBSDF_outvec(v, b, o))
1463 return(0);
1464 rad = sqrt(getBSDF_outohm(b, o) / PI);
1465 SDmultiSamp(pert, 3, rv);
1466 for (j = 0; j < 3; j++)
1467 v[j] += rad*(2.*pert[j] - 1.);
1468 if (xm != NULL)
1469 multv3(v, v, xm);
1470 return(normalize(v) != 0.0);
1471 }
1472
1473
1474 static int
1475 addrot( /* compute rotation (x,y,z) => (xp,yp,zp) */
1476 char *xfarg[],
1477 FVECT xp,
1478 FVECT yp,
1479 FVECT zp
1480 )
1481 {
1482 static char bufs[3][16];
1483 int bn = 0;
1484 char **xfp = xfarg;
1485 double theta;
1486
1487 if (yp[2]*yp[2] + zp[2]*zp[2] < 2.*FTINY*FTINY) {
1488 /* Special case for X' along Z-axis */
1489 theta = -atan2(yp[0], yp[1]);
1490 *xfp++ = "-ry";
1491 *xfp++ = xp[2] < 0.0 ? "90" : "-90";
1492 *xfp++ = "-rz";
1493 sprintf(bufs[bn], "%f", theta*(180./PI));
1494 *xfp++ = bufs[bn++];
1495 return(xfp - xfarg);
1496 }
1497 theta = atan2(yp[2], zp[2]);
1498 if (!FEQ(theta,0.0)) {
1499 *xfp++ = "-rx";
1500 sprintf(bufs[bn], "%f", theta*(180./PI));
1501 *xfp++ = bufs[bn++];
1502 }
1503 theta = asin(-xp[2]);
1504 if (!FEQ(theta,0.0)) {
1505 *xfp++ = "-ry";
1506 sprintf(bufs[bn], " %f", theta*(180./PI));
1507 *xfp++ = bufs[bn++];
1508 }
1509 theta = atan2(xp[1], xp[0]);
1510 if (!FEQ(theta,0.0)) {
1511 *xfp++ = "-rz";
1512 sprintf(bufs[bn], "%f", theta*(180./PI));
1513 *xfp++ = bufs[bn++];
1514 }
1515 *xfp = NULL;
1516 return(xfp - xfarg);
1517 }
1518
1519
1520 int
1521 getBSDF_xfm( /* compute BSDF orient. -> world orient. transform */
1522 MAT4 xm,
1523 FVECT nrm,
1524 UpDir ud,
1525 char *xfbuf
1526 )
1527 {
1528 char *xfargs[7];
1529 XF myxf;
1530 FVECT updir, xdest, ydest;
1531 int i;
1532
1533 updir[0] = updir[1] = updir[2] = 0.;
1534 switch (ud) {
1535 case UDzneg:
1536 updir[2] = -1.;
1537 break;
1538 case UDyneg:
1539 updir[1] = -1.;
1540 break;
1541 case UDxneg:
1542 updir[0] = -1.;
1543 break;
1544 case UDxpos:
1545 updir[0] = 1.;
1546 break;
1547 case UDypos:
1548 updir[1] = 1.;
1549 break;
1550 case UDzpos:
1551 updir[2] = 1.;
1552 break;
1553 case UDunknown:
1554 return(0);
1555 }
1556 fcross(xdest, updir, nrm);
1557 if (normalize(xdest) == 0.0)
1558 return(0);
1559 fcross(ydest, nrm, xdest);
1560 xf(&myxf, addrot(xfargs, xdest, ydest, nrm), xfargs);
1561 copymat4(xm, myxf.xfm);
1562 if (xfbuf == NULL)
1563 return(1);
1564 /* return xf arguments as well */
1565 for (i = 0; xfargs[i] != NULL; i++) {
1566 *xfbuf++ = ' ';
1567 strcpy(xfbuf, xfargs[i]);
1568 while (*xfbuf) ++xfbuf;
1569 }
1570 return(1);
1571 }
1572
1573 /*######### END DEPRECATED ROUTINES #######*/
1574 /*################################################################*/