ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_m.c
Revision: 3.6
Committed: Mon Feb 21 22:50:37 2011 UTC (13 years, 2 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 3.5: +10 -9 lines
Log Message:
Corrected notion of "front" and "back" to coincide with surface normals

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: bsdf_m.c,v 3.5 2011/02/19 23:42:09 greg Exp $";
3 #endif
4 /*
5 * bsdf_m.c
6 *
7 * Definitions supporting BSDF matrices
8 *
9 * Created by Greg Ward on 2/2/11.
10 * Copyright 2011 Anyhere Software. All rights reserved.
11 *
12 */
13
14 #include "rtio.h"
15 #include <stdlib.h>
16 #include <math.h>
17 #include <ctype.h>
18 #include "ezxml.h"
19 #include "bsdf.h"
20 #include "bsdf_m.h"
21
22 /* Function return codes */
23 #define RC_GOOD 1
24 #define RC_FAIL 0
25 #define RC_FORMERR (-1)
26 #define RC_DATERR (-2)
27 #define RC_UNSUPP (-3)
28 #define RC_INTERR (-4)
29 #define RC_MEMERR (-5)
30
31 #define MAXLATS 46 /* maximum number of latitudes */
32
33 /* BSDF angle specification */
34 typedef struct {
35 char name[64]; /* basis name */
36 int nangles; /* total number of directions */
37 struct {
38 float tmin; /* starting theta */
39 int nphis; /* number of phis (0 term) */
40 } lat[MAXLATS+1]; /* latitudes */
41 } ANGLE_BASIS;
42
43 #define MAXABASES 7 /* limit on defined bases */
44
45 static ANGLE_BASIS abase_list[MAXABASES] = {
46 {
47 "LBNL/Klems Full", 145,
48 { {-5., 1},
49 {5., 8},
50 {15., 16},
51 {25., 20},
52 {35., 24},
53 {45., 24},
54 {55., 24},
55 {65., 16},
56 {75., 12},
57 {90., 0} }
58 }, {
59 "LBNL/Klems Half", 73,
60 { {-6.5, 1},
61 {6.5, 8},
62 {19.5, 12},
63 {32.5, 16},
64 {46.5, 20},
65 {61.5, 12},
66 {76.5, 4},
67 {90., 0} }
68 }, {
69 "LBNL/Klems Quarter", 41,
70 { {-9., 1},
71 {9., 8},
72 {27., 12},
73 {46., 12},
74 {66., 8},
75 {90., 0} }
76 }
77 };
78
79 static int nabases = 3; /* current number of defined bases */
80
81 static int
82 fequal(double a, double b)
83 {
84 if (b != .0)
85 a = a/b - 1.;
86 return (a <= 1e-6) & (a >= -1e-6);
87 }
88
89 /* returns the name of the given tag */
90 #ifdef ezxml_name
91 #undef ezxml_name
92 static char *
93 ezxml_name(ezxml_t xml)
94 {
95 if (xml == NULL)
96 return NULL;
97 return xml->name;
98 }
99 #endif
100
101 /* returns the given tag's character content or empty string if none */
102 #ifdef ezxml_txt
103 #undef ezxml_txt
104 static char *
105 ezxml_txt(ezxml_t xml)
106 {
107 if (xml == NULL)
108 return "";
109 return xml->txt;
110 }
111 #endif
112
113 /* Convert error to standard BSDF code */
114 static SDError
115 convert_errcode(int ec)
116 {
117 switch (ec) {
118 case RC_GOOD:
119 return SDEnone;
120 case RC_FORMERR:
121 return SDEformat;
122 case RC_DATERR:
123 return SDEdata;
124 case RC_UNSUPP:
125 return SDEsupport;
126 case RC_INTERR:
127 return SDEinternal;
128 case RC_MEMERR:
129 return SDEmemory;
130 }
131 return SDEunknown;
132 }
133
134 /* Allocate a BSDF matrix of the given size */
135 static SDMat *
136 SDnewMatrix(int ni, int no)
137 {
138 SDMat *sm;
139
140 if ((ni <= 0) | (no <= 0)) {
141 strcpy(SDerrorDetail, "Empty BSDF matrix request");
142 return NULL;
143 }
144 sm = (SDMat *)malloc(sizeof(SDMat) + (ni*no - 1)*sizeof(float));
145 if (sm == NULL) {
146 sprintf(SDerrorDetail, "Cannot allocate %dx%d BSDF matrix",
147 ni, no);
148 return NULL;
149 }
150 memset(sm, 0, sizeof(SDMat)-sizeof(float));
151 sm->ninc = ni;
152 sm->nout = no;
153
154 return sm;
155 }
156
157 /* Free a BSDF matrix */
158 #define SDfreeMatrix free
159
160 /* get vector for this angle basis index */
161 static int
162 ab_getvec(FVECT v, int ndx, double randX, void *p)
163 {
164 ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
165 double rx[2];
166 int li;
167 double pol, azi, d;
168
169 if ((ndx < 0) | (ndx >= ab->nangles))
170 return RC_FAIL;
171 for (li = 0; ndx >= ab->lat[li].nphis; li++)
172 ndx -= ab->lat[li].nphis;
173 SDmultiSamp(rx, 2, randX);
174 pol = M_PI/180.*( (1.-rx[0])*ab->lat[li].tmin +
175 rx[0]*ab->lat[li+1].tmin );
176 azi = 2.*M_PI*(ndx + rx[1] - .5)/ab->lat[li].nphis;
177 v[2] = d = cos(pol);
178 d = sqrt(1. - d*d); /* sin(pol) */
179 v[0] = cos(azi)*d;
180 v[1] = sin(azi)*d;
181 return RC_GOOD;
182 }
183
184 /* get index corresponding to the given vector */
185 static int
186 ab_getndx(const FVECT v, void *p)
187 {
188 ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
189 int li, ndx;
190 double pol, azi, d;
191
192 if (v == NULL)
193 return -1;
194 if ((v[2] < .0) | (v[2] > 1.0))
195 return -1;
196 pol = 180.0/M_PI*acos(v[2]);
197 azi = 180.0/M_PI*atan2(v[1], v[0]);
198 if (azi < 0.0) azi += 360.0;
199 for (li = 1; ab->lat[li].tmin <= pol; li++)
200 if (!ab->lat[li].nphis)
201 return -1;
202 --li;
203 ndx = (int)((1./360.)*azi*ab->lat[li].nphis + 0.5);
204 if (ndx >= ab->lat[li].nphis) ndx = 0;
205 while (li--)
206 ndx += ab->lat[li].nphis;
207 return ndx;
208 }
209
210 /* compute square of real value */
211 static double sq(double x) { return x*x; }
212
213 /* get projected solid angle for this angle basis index */
214 static double
215 ab_getohm(int ndx, void *p)
216 {
217 static int last_li = -1;
218 static double last_ohm;
219 ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
220 int li;
221 double theta, theta1;
222
223 if ((ndx < 0) | (ndx >= ab->nangles))
224 return -1.;
225 for (li = 0; ndx >= ab->lat[li].nphis; li++)
226 ndx -= ab->lat[li].nphis;
227 if (li == last_li) /* cached latitude? */
228 return last_ohm;
229 last_li = li;
230 theta1 = M_PI/180. * ab->lat[li+1].tmin;
231 if (ab->lat[li].nphis == 1) /* special case */
232 return last_ohm = M_PI*(1. - sq(cos(theta1)));
233 theta = M_PI/180. * ab->lat[li].tmin;
234 return last_ohm = M_PI*(sq(cos(theta)) - sq(cos(theta1))) /
235 (double)ab->lat[li].nphis;
236 }
237
238 /* get reverse vector for this angle basis index */
239 static int
240 ab_getvecR(FVECT v, int ndx, double randX, void *p)
241 {
242 int na = (*(ANGLE_BASIS *)p).nangles;
243
244 if (!ab_getvec(v, ndx, randX, p))
245 return RC_FAIL;
246
247 v[0] = -v[0];
248 v[1] = -v[1];
249 v[2] = -v[2];
250
251 return RC_GOOD;
252 }
253
254 /* get index corresponding to the reverse vector */
255 static int
256 ab_getndxR(const FVECT v, void *p)
257 {
258 FVECT v2;
259
260 v2[0] = -v[0];
261 v2[1] = -v[1];
262 v2[2] = -v[2];
263
264 return ab_getndx(v2, p);
265 }
266
267 /* load custom BSDF angle basis */
268 static int
269 load_angle_basis(ezxml_t wab)
270 {
271 char *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
272 ezxml_t wbb;
273 int i;
274
275 if (!abname || !*abname)
276 return RC_FAIL;
277 for (i = nabases; i--; )
278 if (!strcasecmp(abname, abase_list[i].name))
279 return RC_GOOD; /* assume it's the same */
280 if (nabases >= MAXABASES) {
281 sprintf(SDerrorDetail, "Out of angle bases reading '%s'",
282 abname);
283 return RC_INTERR;
284 }
285 strcpy(abase_list[nabases].name, abname);
286 abase_list[nabases].nangles = 0;
287 for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
288 wbb != NULL; i++, wbb = wbb->next) {
289 if (i >= MAXLATS) {
290 sprintf(SDerrorDetail, "Too many latitudes for '%s'",
291 abname);
292 return RC_INTERR;
293 }
294 abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
295 ezxml_child(ezxml_child(wbb,
296 "ThetaBounds"), "UpperTheta")));
297 if (!i)
298 abase_list[nabases].lat[i].tmin =
299 -abase_list[nabases].lat[i+1].tmin;
300 else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
301 "ThetaBounds"), "LowerTheta"))),
302 abase_list[nabases].lat[i].tmin)) {
303 sprintf(SDerrorDetail, "Theta values disagree in '%s'",
304 abname);
305 return RC_DATERR;
306 }
307 abase_list[nabases].nangles +=
308 abase_list[nabases].lat[i].nphis =
309 atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
310 if (abase_list[nabases].lat[i].nphis <= 0 ||
311 (abase_list[nabases].lat[i].nphis == 1 &&
312 abase_list[nabases].lat[i].tmin > FTINY)) {
313 sprintf(SDerrorDetail, "Illegal phi count in '%s'",
314 abname);
315 return RC_DATERR;
316 }
317 }
318 abase_list[nabases++].lat[i].nphis = 0;
319 return RC_GOOD;
320 }
321
322 /* compute min. proj. solid angle and max. direct hemispherical scattering */
323 static int
324 get_extrema(SDSpectralDF *df)
325 {
326 SDMat *dp = (SDMat *)df->comp[0].dist;
327 double *ohma;
328 int i, o;
329 /* initialize extrema */
330 df->minProjSA = M_PI;
331 df->maxHemi = .0;
332 ohma = (double *)malloc(dp->nout*sizeof(double));
333 if (ohma == NULL)
334 return RC_MEMERR;
335 /* get outgoing solid angles */
336 for (o = dp->nout; o--; )
337 if ((ohma[o] = mBSDF_outohm(dp,o)) < df->minProjSA)
338 df->minProjSA = ohma[o];
339 /* compute hemispherical sums */
340 for (i = dp->ninc; i--; ) {
341 double hemi = .0;
342 for (o = dp->nout; o--; )
343 hemi += ohma[o] * mBSDF_value(dp, i, o);
344 if (hemi > df->maxHemi)
345 df->maxHemi = hemi;
346 }
347 free(ohma);
348 /* need incoming solid angles, too? */
349 if ((dp->ib_ohm != dp->ob_ohm) | (dp->ib_priv != dp->ob_priv)) {
350 double ohm;
351 for (i = dp->ninc; i--; )
352 if ((ohm = mBSDF_incohm(dp,i)) < df->minProjSA)
353 df->minProjSA = ohm;
354 }
355 return (df->maxHemi <= 1.01);
356 }
357
358 /* load BSDF distribution for this wavelength */
359 static int
360 load_bsdf_data(SDData *sd, ezxml_t wdb, int rowinc)
361 {
362 SDSpectralDF *df;
363 SDMat *dp;
364 char *sdata;
365 int inbi, outbi;
366 int i;
367 /* allocate BSDF component */
368 sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
369 if (!strcasecmp(sdata, "Transmission Back") || (sd->tf == NULL &&
370 !strcasecmp(sdata, "Transmission Front"))) {
371 if (sd->tf != NULL)
372 SDfreeSpectralDF(sd->tf);
373 if ((sd->tf = SDnewSpectralDF(1)) == NULL)
374 return RC_MEMERR;
375 df = sd->tf;
376 } else if (!strcasecmp(sdata, "Reflection Front")) {
377 if (sd->rb != NULL) /* note back-front reversal */
378 SDfreeSpectralDF(sd->rb);
379 if ((sd->rb = SDnewSpectralDF(1)) == NULL)
380 return RC_MEMERR;
381 df = sd->rb;
382 } else if (!strcasecmp(sdata, "Reflection Back")) {
383 if (sd->rf != NULL) /* note front-back reversal */
384 SDfreeSpectralDF(sd->rf);
385 if ((sd->rf = SDnewSpectralDF(1)) == NULL)
386 return RC_MEMERR;
387 df = sd->rf;
388 } else
389 return RC_FAIL;
390 /* XXX should also check "ScatteringDataType" for consistency? */
391 /* get angle bases */
392 sdata = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
393 if (!sdata || !*sdata) {
394 sprintf(SDerrorDetail, "Missing column basis for BSDF '%s'",
395 sd->name);
396 return RC_FORMERR;
397 }
398 for (inbi = nabases; inbi--; )
399 if (!strcasecmp(sdata, abase_list[inbi].name))
400 break;
401 if (inbi < 0) {
402 sprintf(SDerrorDetail, "Undefined ColumnAngleBasis '%s'", sdata);
403 return RC_FORMERR;
404 }
405 sdata = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
406 if (!sdata || !*sdata) {
407 sprintf(SDerrorDetail, "Missing row basis for BSDF '%s'",
408 sd->name);
409 return RC_FORMERR;
410 }
411 for (outbi = nabases; outbi--; )
412 if (!strcasecmp(sdata, abase_list[outbi].name))
413 break;
414 if (outbi < 0) {
415 sprintf(SDerrorDetail, "Undefined RowAngleBasis '%s'", sdata);
416 return RC_FORMERR;
417 }
418 /* allocate BSDF matrix */
419 dp = SDnewMatrix(abase_list[inbi].nangles, abase_list[outbi].nangles);
420 if (dp == NULL)
421 return RC_MEMERR;
422 dp->ib_priv = &abase_list[inbi];
423 dp->ob_priv = &abase_list[outbi];
424 if (df == sd->tf) {
425 dp->ib_vec = &ab_getvecR;
426 dp->ib_ndx = &ab_getndxR;
427 dp->ob_vec = &ab_getvec;
428 dp->ob_ndx = &ab_getndx;
429 } else if (df == sd->rf) {
430 dp->ib_vec = &ab_getvec;
431 dp->ib_ndx = &ab_getndx;
432 dp->ob_vec = &ab_getvec;
433 dp->ob_ndx = &ab_getndx;
434 } else /* df == sd->rb */ {
435 dp->ib_vec = &ab_getvecR;
436 dp->ib_ndx = &ab_getndxR;
437 dp->ob_vec = &ab_getvecR;
438 dp->ob_ndx = &ab_getndxR;
439 }
440 dp->ib_ohm = &ab_getohm;
441 dp->ob_ohm = &ab_getohm;
442 df->comp[0].cspec[0] = c_dfcolor; /* XXX monochrome for now */
443 df->comp[0].dist = dp;
444 df->comp[0].func = &SDhandleMtx;
445 /* read BSDF data */
446 sdata = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
447 if (!sdata || !*sdata) {
448 sprintf(SDerrorDetail, "Missing BSDF ScatteringData in '%s'",
449 sd->name);
450 return RC_FORMERR;
451 }
452 for (i = 0; i < dp->ninc*dp->nout; i++) {
453 char *sdnext = fskip(sdata);
454 if (sdnext == NULL) {
455 sprintf(SDerrorDetail,
456 "Bad/missing BSDF ScatteringData in '%s'",
457 sd->name);
458 return RC_FORMERR;
459 }
460 while (*sdnext && isspace(*sdnext))
461 sdnext++;
462 if (*sdnext == ',') sdnext++;
463 if (rowinc) {
464 int r = i/dp->nout;
465 int c = i - c*dp->nout;
466 mBSDF_value(dp,r,c) = atof(sdata);
467 } else
468 dp->bsdf[i] = atof(sdata);
469 sdata = sdnext;
470 }
471 return get_extrema(df);
472 }
473
474 /* Subtract minimum (diffuse) scattering amount from BSDF */
475 static double
476 subtract_min(SDMat *sm)
477 {
478 float minv = sm->bsdf[0];
479 int n = sm->ninc*sm->nout;
480 int i;
481
482 for (i = n; --i; )
483 if (sm->bsdf[i] < minv)
484 minv = sm->bsdf[i];
485 for (i = n; i--; )
486 sm->bsdf[i] -= minv;
487
488 return minv*M_PI; /* be sure to include multiplier */
489 }
490
491 /* Extract and separate diffuse portion of BSDF */
492 static void
493 extract_diffuse(SDValue *dv, SDSpectralDF *df)
494 {
495 int n;
496
497 if (df == NULL || df->ncomp <= 0) {
498 dv->spec = c_dfcolor;
499 dv->cieY = .0;
500 return;
501 }
502 dv->spec = df->comp[0].cspec[0];
503 dv->cieY = subtract_min((SDMat *)df->comp[0].dist);
504 /* in case of multiple components */
505 for (n = df->ncomp; --n; ) {
506 double ymin = subtract_min((SDMat *)df->comp[n].dist);
507 c_cmix(&dv->spec, dv->cieY, &dv->spec, ymin, &df->comp[n].cspec[0]);
508 dv->cieY += ymin;
509 }
510 df->maxHemi -= dv->cieY; /* adjust minimum hemispherical */
511 /* make sure everything is set */
512 c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
513 }
514
515 /* Load a BSDF matrix from an open XML file */
516 SDError
517 SDloadMtx(SDData *sd, ezxml_t wtl)
518 {
519 ezxml_t wld, wdb;
520 int rowIn;
521 struct BSDF_data *dp;
522 char *txt;
523 int rval;
524
525 txt = ezxml_txt(ezxml_child(ezxml_child(wtl,
526 "DataDefinition"), "IncidentDataStructure"));
527 if (txt == NULL || !*txt) {
528 sprintf(SDerrorDetail,
529 "BSDF \"%s\": missing IncidentDataStructure",
530 sd->name);
531 return SDEformat;
532 }
533 if (!strcasecmp(txt, "Rows"))
534 rowIn = 1;
535 else if (!strcasecmp(txt, "Columns"))
536 rowIn = 0;
537 else {
538 sprintf(SDerrorDetail,
539 "BSDF \"%s\": unsupported IncidentDataStructure",
540 sd->name);
541 return SDEsupport;
542 }
543 /* get angle basis */
544 rval = load_angle_basis(ezxml_child(ezxml_child(wtl,
545 "DataDefinition"), "AngleBasis"));
546 if (rval < 0)
547 return convert_errcode(rval);
548 /* load BSDF components */
549 for (wld = ezxml_child(wtl, "WavelengthData");
550 wld != NULL; wld = wld->next) {
551 if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
552 "Visible"))
553 continue; /* just visible for now */
554 for (wdb = ezxml_child(wld, "WavelengthDataBlock");
555 wdb != NULL; wdb = wdb->next)
556 if ((rval = load_bsdf_data(sd, wdb, rowIn)) < 0)
557 return convert_errcode(rval);
558 }
559 /* separate diffuse components */
560 extract_diffuse(&sd->rLambFront, sd->rf);
561 extract_diffuse(&sd->rLambBack, sd->rb);
562 extract_diffuse(&sd->tLamb, sd->tf);
563 /* return success */
564 return SDEnone;
565 }
566
567 /* Get Matrix BSDF value */
568 static int
569 SDgetMtxBSDF(float coef[SDmaxCh], const FVECT outVec,
570 const FVECT inVec, const void *dist)
571 {
572 const SDMat *dp = (const SDMat *)dist;
573 int i_ndx, o_ndx;
574 /* get angle indices */
575 i_ndx = mBSDF_incndx(dp, inVec);
576 o_ndx = mBSDF_outndx(dp, outVec);
577 /* try reciprocity if necessary */
578 if ((i_ndx < 0) & (o_ndx < 0)) {
579 i_ndx = mBSDF_incndx(dp, outVec);
580 o_ndx = mBSDF_outndx(dp, inVec);
581 }
582 if ((i_ndx < 0) | (o_ndx < 0))
583 return 0; /* nothing from this component */
584 coef[0] = mBSDF_value(dp, i_ndx, o_ndx);
585 return 1; /* XXX monochrome for now */
586 }
587
588 /* Query solid angle for vector */
589 static SDError
590 SDqueryMtxProjSA(double *psa, const FVECT vec, int qflags, const void *dist)
591 {
592 const SDMat *dp = (const SDMat *)dist;
593 double inc_psa, out_psa;
594 /* check arguments */
595 if ((psa == NULL) | (vec == NULL) | (dp == NULL))
596 return SDEargument;
597 /* get projected solid angles */
598 inc_psa = mBSDF_incohm(dp, mBSDF_incndx(dp, vec));
599 out_psa = mBSDF_outohm(dp, mBSDF_outndx(dp, vec));
600
601 switch (qflags) { /* record based on flag settings */
602 case SDqueryVal:
603 psa[0] = .0;
604 /* fall through */
605 case SDqueryMax:
606 if (inc_psa > psa[0])
607 psa[0] = inc_psa;
608 if (out_psa > psa[0])
609 psa[0] = out_psa;
610 break;
611 case SDqueryMin+SDqueryMax:
612 if (inc_psa > psa[0])
613 psa[1] = inc_psa;
614 if (out_psa > psa[0])
615 psa[1] = out_psa;
616 /* fall through */
617 case SDqueryMin:
618 if ((inc_psa > .0) & (inc_psa < psa[0]))
619 psa[0] = inc_psa;
620 if ((out_psa > .0) & (out_psa < psa[0]))
621 psa[0] = out_psa;
622 break;
623 }
624 /* make sure it's legal */
625 return (psa[0] <= .0) ? SDEinternal : SDEnone;
626 }
627
628 /* Compute new cumulative distribution from BSDF */
629 static int
630 make_cdist(SDMatCDst *cd, const FVECT inVec, SDMat *dp, int rev)
631 {
632 const unsigned maxval = ~0;
633 double *cmtab, scale;
634 int o;
635
636 cmtab = (double *)malloc((cd->calen+1)*sizeof(double));
637 if (cmtab == NULL)
638 return 0;
639 cmtab[0] = .0;
640 for (o = 0; o < cd->calen; o++) {
641 if (rev)
642 cmtab[o+1] = mBSDF_value(dp, o, cd->indx) *
643 (*dp->ib_ohm)(o, dp->ib_priv);
644 else
645 cmtab[o+1] = mBSDF_value(dp, cd->indx, o) *
646 (*dp->ob_ohm)(o, dp->ob_priv);
647 cmtab[o+1] += cmtab[o];
648 }
649 cd->cTotal = cmtab[cd->calen];
650 scale = (double)maxval / cd->cTotal;
651 cd->carr[0] = 0;
652 for (o = 1; o < cd->calen; o++)
653 cd->carr[o] = scale*cmtab[o] + .5;
654 cd->carr[cd->calen] = maxval;
655 free(cmtab);
656 return 1;
657 }
658
659 /* Get cumulative distribution for matrix BSDF */
660 static const SDCDst *
661 SDgetMtxCDist(const FVECT inVec, SDComponent *sdc)
662 {
663 SDMat *dp = (SDMat *)sdc->dist;
664 int reverse;
665 SDMatCDst myCD;
666 SDMatCDst *cd, *cdlast;
667 /* check arguments */
668 if ((inVec == NULL) | (dp == NULL))
669 return NULL;
670 memset(&myCD, 0, sizeof(myCD));
671 myCD.indx = mBSDF_incndx(dp, inVec);
672 if (myCD.indx >= 0) {
673 myCD.ob_priv = dp->ob_priv;
674 myCD.ob_vec = dp->ob_vec;
675 myCD.calen = dp->nout;
676 reverse = 0;
677 } else { /* try reciprocity */
678 myCD.indx = mBSDF_outndx(dp, inVec);
679 if (myCD.indx < 0)
680 return NULL;
681 myCD.ob_priv = dp->ib_priv;
682 myCD.ob_vec = dp->ib_vec;
683 myCD.calen = dp->ninc;
684 reverse = 1;
685 }
686 cdlast = NULL; /* check for it in cache list */
687 for (cd = (SDMatCDst *)sdc->cdList;
688 cd != NULL; cd = (SDMatCDst *)cd->next) {
689 if (cd->indx == myCD.indx && (cd->calen == myCD.calen) &
690 (cd->ob_priv == myCD.ob_priv) &
691 (cd->ob_vec == myCD.ob_vec))
692 break;
693 cdlast = cd;
694 }
695 if (cd == NULL) { /* need to allocate new entry */
696 cd = (SDMatCDst *)malloc(sizeof(SDMatCDst) +
697 myCD.calen*sizeof(myCD.carr[0]));
698 if (cd == NULL)
699 return NULL;
700 *cd = myCD; /* compute cumulative distribution */
701 if (!make_cdist(cd, inVec, dp, reverse)) {
702 free(cd);
703 return NULL;
704 }
705 cdlast = cd;
706 }
707 if (cdlast != NULL) { /* move entry to head of cache list */
708 cdlast->next = cd->next;
709 cd->next = sdc->cdList;
710 sdc->cdList = (SDCDst *)cd;
711 }
712 return (SDCDst *)cd; /* ready to go */
713 }
714
715 /* Sample cumulative distribution */
716 static SDError
717 SDsampMtxCDist(FVECT outVec, double randX, const SDCDst *cdp)
718 {
719 const unsigned maxval = ~0;
720 const SDMatCDst *mcd = (const SDMatCDst *)cdp;
721 const unsigned target = randX*maxval;
722 int i, iupper, ilower;
723 /* check arguments */
724 if ((outVec == NULL) | (mcd == NULL))
725 return SDEargument;
726 /* binary search to find index */
727 ilower = 0; iupper = mcd->calen;
728 while ((i = (iupper + ilower) >> 1) != ilower)
729 if ((long)target >= (long)mcd->carr[i])
730 ilower = i;
731 else
732 iupper = i;
733 /* localize random position */
734 randX = (randX*maxval - mcd->carr[ilower]) /
735 (double)(mcd->carr[iupper] - mcd->carr[ilower]);
736 /* convert index to vector */
737 if ((*mcd->ob_vec)(outVec, i, randX, mcd->ob_priv))
738 return SDEnone;
739 strcpy(SDerrorDetail, "BSDF sampling fault");
740 return SDEinternal;
741 }
742
743 /* Fixed resolution BSDF methods */
744 SDFunc SDhandleMtx = {
745 &SDgetMtxBSDF,
746 &SDqueryMtxProjSA,
747 &SDgetMtxCDist,
748 &SDsampMtxCDist,
749 &SDfreeMatrix,
750 };