ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/wrapBSDF.c
Revision: 2.20
Committed: Sun Mar 6 01:13:18 2016 UTC (6 years, 8 months ago) by schorsch
Content type: text/plain
Branch: MAIN
Changes since 2.19: +4 -2 lines
Log Message:
Prepare for SCons build on Win32 and Win64

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 schorsch 2.20 static const char RCSid[] = "$Id: wrapBSDF.c,v 2.19 2016/02/03 00:22:55 greg Exp $";
3 greg 2.1 #endif
4     /*
5 greg 2.2 * Wrap BSDF data in valid WINDOW XML file
6 greg 2.1 *
7 greg 2.2 * G. Ward February 2015
8 greg 2.1 */
9    
10 schorsch 2.20 #include "platform.h"
11 greg 2.1 #include <ctype.h>
12     #include "rtio.h"
13 greg 2.17 #include "paths.h"
14 greg 2.1 #include "ezxml.h"
15     #include "bsdf.h"
16     #include "bsdf_m.h"
17     /* XML template file names */
18     const char def_template[] = "minimalBSDFt.xml";
19 greg 2.3 const char win6_template[] = "WINDOW6BSDFt.xml";
20 greg 2.1
21     const char stdin_name[] = "<stdin>";
22     /* input files (can be stdin_name) */
23     const char *xml_input = NULL;
24     /* unit for materials & geometry */
25 greg 2.2 const char *attr_unit = "meter";
26 greg 2.1 const char legal_units[] = "meter|foot|inch|centimeter|millimeter";
27     /* system materials & geometry */
28     const char *mgf_geometry = NULL;
29 greg 2.16 /* comment list */
30     #define MAXCOMM 30
31     const char *commlist[MAXCOMM];
32     int ncomm = 0;
33 greg 2.6 /* angle bases */
34 greg 2.1 enum { ABdefault=-1, ABklemsFull=0, ABklemsHalf, ABklemsQuarter,
35     ABtensorTree3, ABtensorTree4, ABend };
36    
37     int angle_basis = ABdefault;
38    
39 greg 2.7 int correct_solid_angle = 0;
40    
41     const char *klems_basis_name[] = {
42     "LBNL/Klems Full",
43     "LBNL/Klems Half",
44     "LBNL/Klems Quarter",
45     };
46 greg 2.1 /* field IDs and nicknames */
47     struct s_fieldID {
48     char nickName[4];
49 greg 2.3 short has_unit;
50     short win_need;
51 greg 2.1 const char *fullName;
52     } XMLfieldID[] = {
53 greg 2.3 {"m", 0, 1, "Manufacturer"},
54     {"n", 0, 1, "Name"},
55     {"c", 0, 0, "ThermalConductivity"},
56     {"ef", 0, 0, "EmissivityFront"},
57     {"eb", 0, 0, "EmissivityBack"},
58     {"tir", 0, 0, "TIR"},
59     {"eo", 0, 0, "EffectiveOpennessFraction"},
60     {"t", 1, 1, "Thickness"},
61     {"h", 1, 0, "Height"},
62     {"w", 1, 0, "Width"},
63     {"\0", 0, 0, NULL} /* terminator */
64 greg 2.1 };
65     /* field assignments */
66     #define MAXASSIGN 12
67     const char *field_assignment[MAXASSIGN];
68     int nfield_assign = 0;
69     #define FASEP ';'
70     /* data file(s) & spectra */
71     enum { DTtransForward, DTtransBackward, DTreflForward, DTreflBackward };
72    
73 greg 2.11 enum { DSsolar=-1, DSnir=-2, DSxbar31=-3, DSvisible=-4, DSzbar31=-5,
74     DSuprime=-6, DSvprime=-7 };
75 greg 2.1
76     #define MAXFILES 20
77    
78     struct s_dfile {
79     const char *fname; /* input data file name */
80     short type; /* BSDF data type */
81     short spectrum; /* BSDF sensor spectrum */
82     } data_file[MAXFILES];
83    
84     int ndataf = 0; /* number of data files */
85    
86 greg 2.18 int unlink_datafiles = 0; /* unlink data files when done */
87    
88 greg 2.1 const char *spectr_file[MAXFILES]; /* custom spectral curve input */
89    
90     const char top_level_name[] = "WindowElement";
91    
92 greg 2.3 static char basis_definition[][256] = {
93 greg 2.1
94 greg 2.4 "\t<DataDefinition>\n"
95 greg 2.1 "\t\t<IncidentDataStructure>Columns</IncidentDataStructure>\n"
96     "\t\t<AngleBasis>\n"
97     "\t\t\t<AngleBasisName>LBNL/Klems Full</AngleBasisName>\n"
98 greg 2.4 "\t\t\t</AngleBasis>\n"
99     "\t</DataDefinition>\n",
100 greg 2.1
101 greg 2.4 "\t<DataDefinition>\n"
102 greg 2.1 "\t\t<IncidentDataStructure>Columns</IncidentDataStructure>\n"
103     "\t\t<AngleBasis>\n"
104     "\t\t\t<AngleBasisName>LBNL/Klems Half</AngleBasisName>\n"
105 greg 2.4 "\t\t\t</AngleBasis>\n"
106     "\t</DataDefinition>\n",
107 greg 2.1
108 greg 2.4 "\t<DataDefinition>\n"
109 greg 2.1 "\t\t<IncidentDataStructure>Columns</IncidentDataStructure>\n"
110     "\t\t<AngleBasis>\n"
111     "\t\t\t<AngleBasisName>LBNL/Klems Quarter</AngleBasisName>\n"
112 greg 2.4 "\t\t\t</AngleBasis>\n"
113     "\t</DataDefinition>\n",
114 greg 2.1
115 greg 2.4 "\t<DataDefinition>\n"
116     "\t\t<IncidentDataStructure>TensorTree3</IncidentDataStructure>\n"
117     "\t</DataDefinition>\n",
118    
119     "\t<DataDefinition>\n"
120     "\t\t<IncidentDataStructure>TensorTree4</IncidentDataStructure>\n"
121     "\t</DataDefinition>\n",
122 greg 2.1 };
123    
124     /* Copy data from file descriptor to stdout and close */
125     static int
126     copy_and_close(int fd)
127     {
128     int ok = 1;
129     char buf[8192];
130     int n;
131    
132     if (fd < 0)
133     return 0;
134     while ((n = read(fd, buf, sizeof(buf))) > 0)
135     if (write(fileno(stdout), buf, n) != n) {
136     ok = 0;
137     break;
138     }
139     ok &= (n == 0);
140     close(fd);
141     return ok;
142     }
143    
144     /* Allocate and assign string from file or stream */
145     static char *
146     input2str(const char *inpspec)
147     {
148     FILE *fp = NULL;
149     char *str;
150     int len, pos, n;
151    
152     if (inpspec == NULL || !*inpspec)
153     return "";
154     if (inpspec == stdin_name) { /* read from stdin */
155     fp = stdin;
156 greg 2.2 } else if (inpspec[0] == '!') { /* read from command */
157 greg 2.1 fp = popen(inpspec+1, "r");
158     if (fp == NULL) {
159     fprintf(stderr, "Cannot start process '%s'\n",
160 greg 2.2 inpspec);
161 greg 2.1 return "";
162     }
163     } else { /* else load file */
164     int fd = open(inpspec, O_RDONLY);
165     if (fd < 0) {
166     fprintf(stderr, "%s: cannot open\n", inpspec);
167     return "";
168     }
169 schorsch 2.20 #if !defined(_WIN32) && !defined(_WIN64)
170     /* XXX somehow broken on Windows */
171 greg 2.1 len = lseek(fd, 0L, SEEK_END);
172 greg 2.3 if (len > 0) {
173     lseek(fd, 0L, SEEK_SET);
174     str = (char *)malloc(len+1);
175     if (str == NULL) {
176     close(fd);
177     goto memerr;
178     }
179     if (read(fd, str, len) != len) {
180     fprintf(stderr, "%s: read error\n", inpspec);
181     free(str);
182     close(fd);
183     return "";
184     }
185     str[len] = '\0';
186 greg 2.1 close(fd);
187 greg 2.3 return str;
188 greg 2.1 }
189 greg 2.12 #endif
190 greg 2.3 fp = fdopen(fd, "r"); /* not a regular file */
191 greg 2.1 }
192     /* reading from stream */
193     str = (char *)malloc((len=8192)+1);
194     if (str == NULL)
195     goto memerr;
196     pos = 0;
197     while ((n = read(fileno(fp), str+pos, len-pos)) > 0)
198     if ((pos += n) >= len) { /* need more space? */
199     str = (char *)realloc(str, (len += len>>2) + 1);
200     if (str == NULL)
201     goto memerr;
202     }
203     if (n < 0) {
204     fprintf(stderr, "%s: read error\n", inpspec);
205     free(str);
206     str = "";
207     } else { /* tidy up result */
208     str[pos] = '\0';
209     str = (char *)realloc(str, (len=pos)+1);
210     if (str == NULL)
211     goto memerr;
212     }
213 greg 2.2 if (inpspec[0] != '!')
214 greg 2.1 fclose(fp);
215     else if (pclose(fp))
216 greg 2.2 fprintf(stderr, "Error running command '%s'\n", inpspec);
217 greg 2.1 return str;
218     memerr:
219     fprintf(stderr, "%s: error allocating memory\n", inpspec);
220     if (fp != NULL)
221 greg 2.2 (inpspec[0] == '!') ? pclose(fp) : fclose(fp);
222 greg 2.1 return "";
223     }
224    
225     /* Make material assignments in field_assignment to XML fields */
226     static int
227     mat_assignments(const char *caller, const char *fn, ezxml_t wtl)
228     {
229     int i;
230    
231     wtl = ezxml_child(wtl, "Material");
232     if (wtl == NULL) {
233     fprintf(stderr, "%s: missing <Material> tag\n", fn);
234     return 0;
235     }
236     for (i = 0; i < nfield_assign; i++) {
237     const char *fnext = field_assignment[i];
238     for ( ; ; ) {
239 greg 2.5 int added = 0;
240 greg 2.1 ezxml_t fld;
241     char sbuf[512];
242     int j;
243    
244     while (isspace(*fnext))
245     ++fnext;
246     if (!*fnext)
247     break;
248 greg 2.3 for (j = 0; *fnext != '=' && !isspace(*fnext); ) {
249 greg 2.1 if (!*fnext | (*fnext == FASEP) |
250     (j >= sizeof(sbuf)-1)) {
251     fprintf(stderr,
252     "%s: bad tag name in assignment '%s'\n",
253     caller, field_assignment[i]);
254     return 0;
255     }
256     sbuf[j++] = *fnext++;
257     }
258 greg 2.2 sbuf[j] = '\0'; /* check known field */
259 greg 2.1 for (j = 0; XMLfieldID[j].nickName[0]; j++)
260 greg 2.2 if (!strcasecmp(sbuf, XMLfieldID[j].nickName) ||
261     !strcasecmp(sbuf, XMLfieldID[j].fullName)) {
262 greg 2.1 strcpy(sbuf, XMLfieldID[j].fullName);
263     break;
264     }
265     /* check if tag exists */
266     fld = ezxml_child(wtl, sbuf);
267     if (fld == NULL) { /* otherwise, create one */
268 greg 2.3 if (!XMLfieldID[j].nickName[0])
269     fprintf(stderr,
270     "%s: warning - adding tag <%s>\n",
271     fn, sbuf);
272 greg 2.5 ezxml_add_txt(wtl, "\t");
273 greg 2.1 fld = ezxml_add_child_d(wtl, sbuf, strlen(wtl->txt));
274 greg 2.5 ++added;
275 greg 2.1 }
276     if (XMLfieldID[j].has_unit)
277     ezxml_set_attr(fld, "unit", attr_unit);
278 greg 2.3 XMLfieldID[j].win_need = 0;
279 greg 2.1 while (isspace(*fnext))
280     ++fnext;
281     if (*fnext++ != '=') {
282     fprintf(stderr,
283     "%s: missing '=' in assignment '%s'\n",
284     caller, field_assignment[i]);
285     return 0;
286     }
287 greg 2.3 for (j = 0; *fnext && *fnext != FASEP; ) {
288 greg 2.1 if (j >= sizeof(sbuf)-1) {
289     fprintf(stderr,
290     "%s: field too long in '%s'\n",
291     caller, field_assignment[i]);
292     return 0;
293     }
294     sbuf[j++] = *fnext++;
295     }
296     sbuf[j] = '\0';
297     ezxml_set_txt_d(fld, sbuf);
298 greg 2.5 if (added)
299     ezxml_add_txt(wtl, "\n\t");
300 greg 2.1 fnext += (*fnext == FASEP);
301     }
302     }
303 greg 2.3 /* check required WINDOW settings */
304     if (xml_input == win6_template)
305     for (i = 0; XMLfieldID[i].nickName[0]; i++)
306     if (XMLfieldID[i].win_need &&
307 greg 2.10 !ezxml_txt(ezxml_child(wtl,XMLfieldID[i].fullName))[0])
308 greg 2.3 fprintf(stderr,
309 greg 2.10 "%s: warning - missing '%s' assignment for WINDOW <%s>\n",
310 greg 2.3 caller, XMLfieldID[i].nickName,
311     XMLfieldID[i].fullName);
312 greg 2.10 return 1;
313 greg 2.1 }
314    
315     /* Complete angle basis specification */
316     static int
317     finish_angle_basis(ezxml_t ab)
318     {
319     const char *bn = ezxml_txt(ezxml_child(ab, "AngleBasisName"));
320     int i, n = nabases;
321     char buf[32];
322    
323     if (!*bn) {
324     fputs("Internal error - missing <AngleBasisName>!\n", stderr);
325     return 0;
326     }
327     while (n-- > 0)
328     if (!strcasecmp(bn, abase_list[n].name))
329     break;
330     if (n < 0) {
331     fprintf(stderr, "Internal error - unknown angle basis '%s'", bn);
332     return 0;
333     }
334     for (i = 0; abase_list[n].lat[i].nphis; i++) {
335     ezxml_t tb, abb = ezxml_add_child(ab, "AngleBasisBlock",
336     strlen(ab->txt));
337     sprintf(buf, "%g", i ?
338     .5*(abase_list[n].lat[i].tmin + abase_list[n].lat[i+1].tmin) :
339     .0);
340 greg 2.4 ezxml_add_txt(abb, "\n\t\t\t\t");
341 greg 2.1 ezxml_set_txt_d(ezxml_add_child(abb,"Theta",strlen(abb->txt)), buf);
342     sprintf(buf, "%d", abase_list[n].lat[i].nphis);
343 greg 2.4 ezxml_add_txt(abb, "\n\t\t\t\t");
344 greg 2.1 ezxml_set_txt_d(ezxml_add_child(abb,"nPhis",strlen(abb->txt)), buf);
345 greg 2.4 ezxml_add_txt(abb, "\n\t\t\t\t");
346 greg 2.1 tb = ezxml_add_child(abb, "ThetaBounds", strlen(abb->txt));
347 greg 2.4 ezxml_add_txt(tb, "\n\t\t\t\t\t");
348 greg 2.1 sprintf(buf, "%g", abase_list[n].lat[i].tmin);
349 greg 2.4 ezxml_set_txt_d(ezxml_add_child(tb,"LowerTheta",strlen(tb->txt)), buf);
350     ezxml_add_txt(tb, "\n\t\t\t\t\t");
351 greg 2.1 sprintf(buf, "%g", abase_list[n].lat[i+1].tmin);
352 greg 2.4 ezxml_set_txt_d(ezxml_add_child(tb,"UpperTheta",strlen(tb->txt)), buf);
353     ezxml_add_txt(tb, "\n\t\t\t\t");
354     ezxml_add_txt(abb, "\n\t\t\t");
355     ezxml_add_txt(ab, "\n\t\t\t");
356 greg 2.1 }
357     return 1;
358     }
359    
360     /* Determine our angle basis from current tags */
361     static int
362     determine_angle_basis(const char *fn, ezxml_t wtl)
363     {
364     const char *ids;
365     int i;
366    
367     wtl = ezxml_child(wtl, "DataDefinition");
368     if (wtl == NULL)
369     return -1;
370     ids = ezxml_txt(ezxml_child(wtl, "IncidentDataStructure"));
371 greg 2.4 if (!ids[0])
372 greg 2.1 return -1;
373     for (i = 0; i < ABend; i++) {
374     ezxml_t parsed = ezxml_parse_str(basis_definition[i],
375     strlen(basis_definition[i]));
376     int match = 0;
377     if (!strcmp(ids, ezxml_txt(ezxml_child(parsed,
378     "IncidentDataStructure")))) {
379     const char *abn0 = ezxml_txt(
380     ezxml_child(ezxml_child(wtl,
381     "AngleBasis"), "AngleBasisName"));
382     const char *abn1 = ezxml_txt(
383     ezxml_child(ezxml_child(parsed,
384     "AngleBasis"), "AngleBasisName"));
385     match = !strcmp(abn0, abn1);
386     }
387     ezxml_free(parsed);
388     if (match)
389     return i;
390     }
391     return -1;
392     }
393    
394 greg 2.7 /* Filter Klems angle basis, factoring out incident projected solid angle */
395 greg 2.6 static int
396     filter_klems_matrix(FILE *fp)
397     {
398     #define MAX_COLUMNS 145
399 greg 2.7 const char *bn = klems_basis_name[angle_basis];
400 greg 2.6 float col_corr[MAX_COLUMNS];
401     int i, j, n = nabases;
402     /* get angle basis */
403     while (n-- > 0)
404     if (!strcasecmp(bn, abase_list[n].name))
405     break;
406     if (n < 0)
407     return 0;
408     if (abase_list[n].nangles > MAX_COLUMNS) {
409 greg 2.7 fputs("Internal error - too many Klems columns!\n", stderr);
410 greg 2.6 return 0;
411     }
412     /* get correction factors */
413     for (j = abase_list[n].nangles; j--; )
414     col_corr[j] = 1.f / io_getohm(j, &abase_list[n]);
415     /* read/correct/write matrix */
416     for (i = 0; i < abase_list[n].nangles; i++) {
417     for (j = 0; j < abase_list[n].nangles; j++) {
418     double d;
419     if (fscanf(fp, "%lf", &d) != 1)
420     return 0;
421 greg 2.7 if (d < -1e-3) {
422     fputs("Negative BSDF data!\n", stderr);
423     return 0;
424     }
425     printf(" %.3e", d*col_corr[j]*(d > 0));
426 greg 2.6 }
427     fputc('\n', stdout);
428     }
429 greg 2.7 while ((i = getc(fp)) != EOF)
430     if (!isspace(i)) {
431     fputs("Unexpected data past EOF\n", stderr);
432     return 0;
433     }
434     return 1; /* all is good */
435 greg 2.6 #undef MAX_COLUMNS
436     }
437    
438 greg 2.1 /* Write out BSDF data block with surrounding tags */
439     static int
440     writeBSDFblock(const char *caller, struct s_dfile *df)
441     {
442 greg 2.7 int correct_klems = correct_solid_angle;
443 greg 2.1 char *cp;
444    
445     puts("\t<WavelengthData>");
446     puts("\t\t<LayerNumber>System</LayerNumber>");
447     switch (df->spectrum) {
448     case DSvisible:
449     puts("\t\t<Wavelength unit=\"Integral\">Visible</Wavelength>");
450 greg 2.7 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
451 greg 2.1 puts("\t\t<DetectorSpectrum>ASTM E308 1931 Y.dsp</DetectorSpectrum>");
452     break;
453     case DSxbar31:
454     puts("\t\t<Wavelength unit=\"Integral\">CIE-X</Wavelength>");
455 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
456 greg 2.1 puts("\t\t<DetectorSpectrum>ASTM E308 1931 X.dsp</DetectorSpectrum>");
457     break;
458     case DSzbar31:
459     puts("\t\t<Wavelength unit=\"Integral\">CIE-Z</Wavelength>");
460 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
461 greg 2.1 puts("\t\t<DetectorSpectrum>ASTM E308 1931 Z.dsp</DetectorSpectrum>");
462     break;
463 greg 2.11 case DSuprime:
464 greg 2.13 puts("\t\t<Wavelength unit=\"Integral\">CIE-u</Wavelength>");
465 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
466 greg 2.11 break;
467     case DSvprime:
468 greg 2.13 puts("\t\t<Wavelength unit=\"Integral\">CIE-v</Wavelength>");
469 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
470 greg 2.11 break;
471 greg 2.1 case DSsolar:
472     puts("\t\t<Wavelength unit=\"Integral\">Solar</Wavelength>");
473 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
474 greg 2.1 puts("\t\t<DetectorSpectrum>None</DetectorSpectrum>");
475     break;
476     case DSnir:
477     puts("\t\t<Wavelength unit=\"Integral\">NIR</Wavelength>");
478 greg 2.14 puts("\t\t<SourceSpectrum>PLACE_HOLDER</SourceSpectrum>");
479 greg 2.1 puts("\t\t<DetectorSpectrum>PLACE_HOLDER</DetectorSpectrum>");
480     break;
481     default:
482     cp = strrchr(spectr_file[df->spectrum], '.');
483     if (cp != NULL)
484     *cp = '\0';
485     printf("\t\t<Wavelength unit=\"Integral\">%s</Wavelength>\n",
486     spectr_file[df->spectrum]);
487     if (cp != NULL)
488     *cp = '.';
489 greg 2.14 puts("\t\t<SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>");
490 greg 2.1 printf("\t\t<DetectorSpectrum>%s</DetectorSpectrum>\n",
491     spectr_file[df->spectrum]);
492     break;
493     }
494     puts("\t\t<WavelengthDataBlock>");
495     fputs("\t\t\t<WavelengthDataDirection>", stdout);
496     switch (df->type) {
497     case DTtransForward:
498     fputs("Transmission Front", stdout);
499     break;
500     case DTtransBackward:
501     fputs("Transmission Back", stdout);
502     break;
503     case DTreflForward:
504     fputs("Reflection Front", stdout);
505     break;
506     case DTreflBackward:
507     fputs("Reflection Back", stdout);
508     break;
509     default:
510     fprintf(stderr, "%s: internal - bad BSDF type (%d)\n", caller, df->type);
511     return 0;
512     }
513     puts("</WavelengthDataDirection>");
514     switch (angle_basis) {
515     case ABklemsFull:
516     case ABklemsHalf:
517     case ABklemsQuarter:
518 greg 2.7 fputs("\t\t\t<ColumnAngleBasis>", stdout);
519     fputs(klems_basis_name[angle_basis], stdout);
520     puts("</ColumnAngleBasis>");
521     fputs("\t\t\t<RowAngleBasis>", stdout);
522     fputs(klems_basis_name[angle_basis], stdout);
523     puts("</RowAngleBasis>");
524 greg 2.1 break;
525     case ABtensorTree3:
526     case ABtensorTree4:
527     puts("\t\t\t<AngleBasis>LBNL/Shirley-Chiu</AngleBasis>");
528 greg 2.7 correct_klems = 0;
529 greg 2.1 break;
530     default:
531     fprintf(stderr, "%s: bad angle basis (%d)\n", caller, angle_basis);
532     return 0;
533     }
534     puts("\t\t\t<ScatteringDataType>BTDF</ScatteringDataType>");
535     puts("\t\t\t<ScatteringData>");
536     fflush(stdout);
537 greg 2.7 if (correct_klems) { /* correct Klems matrix data */
538 greg 2.6 FILE *fp = stdin;
539     if (df->fname[0] == '!')
540     fp = popen(df->fname+1, "r");
541     else if (df->fname != stdin_name)
542     fp = fopen(df->fname, "r");
543     if (fp == NULL) {
544     fprintf(stderr, "%s: cannot open '%s'\n",
545     caller, df->fname);
546     return 0;
547     }
548     if (!filter_klems_matrix(fp)) {
549     fprintf(stderr, "%s: Klems data error from '%s'\n",
550     caller, df->fname);
551     return 0;
552     }
553     if (df->fname[0] != '!') {
554     fclose(fp);
555     } else if (pclose(fp)) {
556     fprintf(stderr, "%s: error running '%s'\n",
557     caller, df->fname);
558     return 0;
559     }
560     } else if (df->fname == stdin_name) {
561 greg 2.1 copy_and_close(fileno(stdin));
562 greg 2.2 } else if (df->fname[0] != '!') {
563 greg 2.1 if (!copy_and_close(open(df->fname, O_RDONLY))) {
564     fprintf(stderr, "%s: error reading from '%s'\n",
565     caller, df->fname);
566     return 0;
567     }
568     } else if (system(df->fname+1)) {
569 greg 2.2 fprintf(stderr, "%s: error running '%s'\n", caller, df->fname);
570 greg 2.1 return 0;
571     }
572     puts("\t\t\t</ScatteringData>");
573     puts("\t\t</WavelengthDataBlock>");
574     puts("\t</WavelengthData>");
575     return 1;
576     }
577    
578     /* Write out XML, interpolating BSDF data block(s) */
579     static int
580     writeBSDF(const char *caller, ezxml_t fl)
581     {
582 greg 2.2 char *xml = ezxml_toxml(fl); /* store XML in string */
583 greg 2.1 int ei, i;
584     /* locate trailer */
585     for (ei = strlen(xml)-strlen("</Layer></Optical></WindowElement>");
586     ei >= 0; ei--)
587     if (!strncmp(xml+ei, "</Layer>", 8))
588     break;
589     if (ei < 0) {
590     fprintf(stderr, "%s: internal - cannot find trailer\n",
591     caller);
592     free(xml);
593     return 0;
594     }
595 greg 2.15 puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
596 greg 2.16 for (i = 0; i < ncomm; i++)
597     printf("<!-- %s -->\n", commlist[i]);
598 greg 2.1 fflush(stdout); /* write previous XML info. */
599     if (write(fileno(stdout), xml, ei) != ei) {
600     free(xml);
601     return 0;
602     }
603     for (i = 0; i < ndataf; i++) /* interpolate new data */
604     if (!writeBSDFblock(caller, &data_file[i])) {
605     free(xml);
606     return 0;
607     }
608     fputs(xml+ei, stdout); /* write trailer */
609 greg 2.2 free(xml); /* free string */
610 greg 2.4 fputc('\n', stdout);
611 greg 2.18 if (fflush(stdout) != 0)
612     return 0;
613     /* unlink data files if req. */
614     for (i = ndataf*(unlink_datafiles != 0); i--; )
615     if (data_file[i].fname != stdin_name &&
616     data_file[i].fname[0] != '!')
617     unlink(data_file[i].fname);
618 greg 2.19 if (unlink_datafiles > 1 && mgf_geometry != NULL &&
619     mgf_geometry != stdin_name &&
620     mgf_geometry[0] != '!')
621     unlink(mgf_geometry);
622 greg 2.18 return 1;
623 greg 2.1 }
624    
625     /* Insert BSDF data into XML wrapper */
626     static int
627     wrapBSDF(const char *caller)
628     {
629 greg 2.2 const char *xml_path = xml_input;
630 greg 2.1 ezxml_t fl, wtl;
631     /* load previous XML/template */
632 greg 2.2 if (xml_input == stdin_name) {
633     fl = ezxml_parse_fp(stdin);
634     } else if (xml_input[0] == '!') {
635     FILE *pfp = popen(xml_input+1, "r");
636     if (pfp == NULL) {
637     fprintf(stderr, "%s: cannot start process '%s'\n",
638     caller, xml_input);
639     return 0;
640     }
641     fl = ezxml_parse_fp(pfp);
642     if (pclose(pfp)) {
643     fprintf(stderr, "%s: error running '%s'\n",
644     caller, xml_input);
645     return 0;
646     }
647     } else {
648     xml_path = getpath((char *)xml_input, getrlibpath(), R_OK);
649     if (xml_path == NULL) {
650     fprintf(stderr, "%s: cannot find XML file named '%s'\n",
651     caller, xml_input==NULL ? "NULL" : xml_input);
652     return 0;
653     }
654     fl = ezxml_parse_file(xml_path);
655 greg 2.1 }
656     if (fl == NULL) {
657 greg 2.2 fprintf(stderr, "%s: cannot load XML '%s'\n", caller, xml_path);
658 greg 2.1 return 0;
659     }
660     if (ezxml_error(fl)[0]) {
661 greg 2.2 fprintf(stderr, "%s: error in XML '%s': %s\n", caller, xml_path,
662 greg 2.1 ezxml_error(fl));
663     goto failure;
664     }
665     if (strcmp(ezxml_name(fl), top_level_name)) {
666     fprintf(stderr, "%s: top level in XML '%s' not '%s'\n",
667     caller, xml_path, top_level_name);
668     goto failure;
669     }
670     wtl = ezxml_child(fl, "FileType");
671     if (wtl != NULL && strcmp(ezxml_txt(wtl), "BSDF")) {
672     fprintf(stderr, "%s: wrong FileType in XML '%s' (must be 'BSDF')",
673     caller, xml_path);
674     goto failure;
675     }
676     wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
677     if (wtl == NULL) {
678     fprintf(stderr, "%s: no optical layers in XML '%s'",
679     caller, xml_path);
680     goto failure;
681     }
682     /* make material assignments */
683 greg 2.3 if (!mat_assignments(caller, xml_path, wtl))
684 greg 2.1 goto failure;
685     if (mgf_geometry != NULL) { /* add geometry if specified */
686     ezxml_t geom = ezxml_child(wtl, "Geometry");
687     if (geom == NULL)
688 greg 2.3 geom = ezxml_add_child(wtl, "Geometry", strlen(wtl->txt));
689 greg 2.1 ezxml_set_attr(geom, "format", "MGF");
690     geom = ezxml_child(geom, "MGFblock");
691     if (geom == NULL) {
692     geom = ezxml_child(wtl, "Geometry");
693 greg 2.3 geom = ezxml_add_child(geom, "MGFblock", 0);
694 greg 2.1 }
695     ezxml_set_attr(geom, "unit", attr_unit);
696     ezxml_set_txt(geom, input2str(mgf_geometry));
697     if (geom->txt[0])
698     ezxml_set_flag(geom, EZXML_TXTM);
699     }
700     /* check basis */
701     if (angle_basis != ABdefault) {
702 greg 2.4 size_t offset = 0;
703 greg 2.1 ezxml_t ab, dd = ezxml_child(wtl, "DataDefinition");
704 greg 2.4 if (dd != NULL) {
705     offset = dd->off;
706 greg 2.5 if (dd->child != NULL)
707     fprintf(stderr,
708 greg 2.1 "%s: warning - replacing existing <DataDefinition> in '%s'\n",
709     caller, xml_path);
710 greg 2.4 ezxml_remove(dd);
711     } else
712     offset = strlen(wtl->txt);
713     dd = ezxml_insert(ezxml_parse_str(basis_definition[angle_basis],
714 greg 2.1 strlen(basis_definition[angle_basis])),
715 greg 2.4 wtl, offset);
716 greg 2.1 if ((ab = ezxml_child(dd, "AngleBasis")) != NULL &&
717     !finish_angle_basis(ab))
718     goto failure;
719     } else if ((angle_basis = determine_angle_basis(xml_path, wtl)) < 0) {
720     fprintf(stderr, "%s: need -a option to set angle basis\n",
721     caller);
722     goto failure;
723     }
724     /* write & add BSDF data blocks */
725     if (!writeBSDF(caller, fl))
726     goto failure;
727     ezxml_free(fl); /* all done */
728     return 1;
729     failure:
730     ezxml_free(fl);
731     return 0;
732     }
733    
734     /* Report usage and exit */
735     static void
736     UsageExit(const char *pname)
737     {
738     fputs("Usage: ", stderr);
739     fputs(pname, stderr);
740 greg 2.11 fputs(" [-W][-c][-a {kf|kh|kq|t3|t4}][-u unit][-g geom][-f 'x=string;y=string']", stderr);
741 greg 2.16 fputs(" [-s spectr][-tb inp][-tf inp][-rb inp][-rf inp][-C comm]", stderr);
742 greg 2.2 fputs(" [input.xml]\n", stderr);
743 greg 2.1 exit(1);
744     }
745    
746     /* Load XML file and use to wrap BSDF data (or modify fields) */
747     int
748     main(int argc, char *argv[])
749     {
750     int cur_spectrum = DSvisible;
751     int ncust_spec = 0;
752     int used_stdin = 0;
753     int units_set = 0;
754     int i;
755     /* get/check arguments */
756     for (i = 1; i < argc && argv[i][0] == '-'; i++) {
757     switch (argv[i][1]) {
758     case 'W': /* customize for WINDOW 6 output */
759     xml_input = win6_template;
760     continue;
761     case 'f': /* field assignment(s) */
762     if (++i >= argc)
763     UsageExit(argv[0]);
764     if (nfield_assign >= MAXASSIGN) {
765     fprintf(stderr, "%s: too many -f options",
766     argv[0]);
767     return 1;
768     }
769     field_assignment[nfield_assign++] = argv[i];
770     continue;
771     case 'u': /* unit */
772     if (++i >= argc)
773     UsageExit(argv[0]);
774     if (units_set++) {
775     fprintf(stderr, "%s: only one -u option allowed\n",
776     argv[0]);
777     return 1;
778     }
779 greg 2.2 if (strstr(legal_units, argv[i]) == NULL) {
780     fprintf(stderr, "%s: -u unit must be one of (%s)\n",
781 greg 2.1 argv[0], legal_units);
782     return 1;
783     }
784     attr_unit = argv[i];
785     continue;
786 greg 2.18 case 'U': /* unlink data files when done */
787 greg 2.19 unlink_datafiles = 1 + (argv[i][2] == 'U');
788 greg 2.18 continue;
789 greg 2.1 case 'a': /* angle basis */
790     if (++i >= argc)
791     UsageExit(argv[0]);
792     if (angle_basis != ABdefault) {
793     fprintf(stderr, "%s: only one -a option allowed\n",
794     argv[0]);
795     return 1;
796     }
797     if (!strcasecmp(argv[i], "kf"))
798     angle_basis = ABklemsFull;
799     else if (!strcasecmp(argv[i], "kh"))
800     angle_basis = ABklemsHalf;
801     else if (!strcasecmp(argv[i], "kq"))
802     angle_basis = ABklemsQuarter;
803     else if (!strcasecmp(argv[i], "t3"))
804     angle_basis = ABtensorTree3;
805     else if (!strcasecmp(argv[i], "t4"))
806     angle_basis = ABtensorTree4;
807     else
808     UsageExit(argv[0]);
809     continue;
810 greg 2.7 case 'c': /* correct solid angle */
811 greg 2.9 correct_solid_angle = 1;
812 greg 2.7 continue;
813 greg 2.16 case 'C': /* comment */
814     if (ncomm >= MAXCOMM) {
815     fprintf(stderr, "%s: too many comments\n",
816     argv[0]);
817     return 1;
818     }
819     if (strchr(argv[++i], '>') != NULL) {
820     fprintf(stderr, "%s: illegal character in comment\n",
821     argv[0]);
822     return 1;
823     }
824     commlist[ncomm++] = argv[i];
825     continue;
826 greg 2.1 case 't': /* transmission */
827     if (i >= argc-1)
828     UsageExit(argv[0]);
829     if (ndataf >= MAXFILES) {
830     fprintf(stderr, "%s: too many data files\n",
831     argv[0]);
832     return 1;
833     }
834     if (!strcmp(argv[i], "-tf"))
835     data_file[ndataf].type = DTtransForward;
836     else if (!strcmp(argv[i], "-tb"))
837     data_file[ndataf].type = DTtransBackward;
838     else
839     UsageExit(argv[0]);
840     if (!strcmp(argv[++i], "-")) {
841     if (used_stdin++) UsageExit(argv[i]);
842     argv[i] = (char *)stdin_name;
843     }
844     data_file[ndataf].fname = argv[i];
845     data_file[ndataf].spectrum = cur_spectrum;
846     ndataf++;
847     continue;
848     case 'r': /* reflection */
849     if (i >= argc-1)
850     UsageExit(argv[0]);
851     if (ndataf >= MAXFILES) {
852     fprintf(stderr, "%s: too many data files\n",
853     argv[0]);
854     return 1;
855     }
856     if (!strcmp(argv[i], "-rf"))
857     data_file[ndataf].type = DTreflForward;
858     else if (!strcmp(argv[i], "-rb"))
859     data_file[ndataf].type = DTreflBackward;
860     else
861     UsageExit(argv[0]);
862     if (!strcmp(argv[++i], "-")) {
863     if (used_stdin++) UsageExit(argv[i]);
864     argv[i] = (char *)stdin_name;
865     }
866     data_file[ndataf].fname = argv[i];
867 greg 2.8 data_file[ndataf].spectrum = cur_spectrum;
868     ndataf++;
869 greg 2.1 continue;
870     case 's': /* spectrum name or input file */
871     if (++i >= argc)
872     UsageExit(argv[0]);
873     if (!strcasecmp(argv[i], "Solar"))
874     cur_spectrum = DSsolar;
875     else if (!strcasecmp(argv[i], "Visible") ||
876     !strcasecmp(argv[i], "CIE-Y"))
877     cur_spectrum = DSvisible;
878     else if (!strcasecmp(argv[i], "CIE-X"))
879     cur_spectrum = DSxbar31;
880     else if (!strcasecmp(argv[i], "CIE-Z"))
881     cur_spectrum = DSzbar31;
882 greg 2.11 else if (!strcasecmp(argv[i], "CIE-u"))
883     cur_spectrum = DSuprime;
884     else if (!strcasecmp(argv[i], "CIE-v"))
885     cur_spectrum = DSvprime;
886 greg 2.1 else if (!strcasecmp(argv[i], "NIR"))
887     cur_spectrum = DSnir;
888     else {
889     if (!strcmp(argv[i], "-")) {
890     fprintf(stderr,
891     "%s: cannot read spectra from stdin",
892     argv[0]);
893     return 1;
894     }
895     cur_spectrum = ncust_spec;
896     spectr_file[ncust_spec++] = argv[i];
897     }
898     continue;
899     case 'g': /* MGF geometry file */
900     if (i >= argc-1)
901     UsageExit(argv[0]);
902     if (mgf_geometry != NULL) {
903     fprintf(stderr, "%s: only one -g option allowed\n",
904     argv[0]);
905     return 1;
906     }
907     if (!strcmp(argv[++i], "-")) {
908     if (used_stdin++) UsageExit(argv[i]);
909     argv[i] = (char *)stdin_name;
910     }
911     mgf_geometry = argv[i];
912     continue;
913     case '\0': /* input XML from stdin */
914     break;
915     default:
916     UsageExit(argv[0]);
917     break;
918     }
919     break;
920     }
921     doneOptions: /* get XML input */
922     if (i >= argc) {
923     if (xml_input == NULL)
924     xml_input = def_template;
925     } else if ((i < argc-1) | (xml_input != NULL)) {
926     fprintf(stderr, "%s: only one XML input allowed\n", argv[0]);
927     UsageExit(argv[0]);
928     } else if (!strcmp(argv[i], "-")) {
929     if (used_stdin++) UsageExit(argv[0]);
930     xml_input = stdin_name;
931     } else {
932     xml_input = argv[i];
933     }
934     /* wrap it! */
935     return !wrapBSDF(argv[0]);
936     }