ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.24
Committed: Fri Jun 17 16:07:18 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad3R7P1, rad3R7P2
Changes since 1.23: +8 -3 lines
Log Message:
Added check for complete output with -r option

File Contents

# User Rev Content
1 greg 1.1 #ifndef lint
2 greg 1.24 static const char RCSid[] = "$Id: rtcontrib.c,v 1.23 2005/06/16 19:37:26 greg Exp $";
3 greg 1.1 #endif
4     /*
5     * Gather rtrace output to compute contributions from particular sources
6     */
7    
8 greg 1.4 #include "standard.h"
9 greg 1.1 #include <ctype.h>
10 greg 1.7 #include <signal.h>
11 greg 1.1 #include "platform.h"
12     #include "rtprocess.h"
13     #include "selcall.h"
14     #include "color.h"
15     #include "resolu.h"
16     #include "lookup.h"
17     #include "calcomp.h"
18    
19 greg 1.19 #ifndef MAXMODLIST
20 greg 1.1 #define MAXMODLIST 1024 /* maximum modifiers we'll track */
21 greg 1.19 #endif
22 greg 1.1
23     int treebufsiz = BUFSIZ; /* current tree buffer size */
24    
25 greg 1.2 typedef double DCOLOR[3]; /* double-precision color */
26    
27 greg 1.1 /*
28     * The modcont structure is used to accumulate ray contributions
29     * for a particular modifier, which may be subdivided into bins
30     * if binv is non-NULL. If outspec contains a %s in it, this will
31     * be replaced with the modifier name. If outspec contains a %d in it,
32     * this will be used to create one output file per bin, otherwise all bins
33     * will be written to the same file, in order. If the global outfmt
34     * is 'c', then a 4-byte RGBE pixel will be output for each bin value
35     * and the file will conform to a RADIANCE image if xres & yres are set.
36     */
37     typedef struct {
38     const char *outspec; /* output file specification */
39     const char *modname; /* modifier name */
40     EPNODE *binv; /* bin value expression */
41     int nbins; /* number of accumulation bins */
42 greg 1.2 DCOLOR cbin[1]; /* contribution bins (extends struct) */
43 greg 1.1 } MODCONT; /* modifier contribution */
44    
45     static void mcfree(void *p) { epfree((*(MODCONT *)p).binv); free(p); }
46    
47     LUTAB modconttab = LU_SINIT(NULL,mcfree); /* modifier lookup table */
48    
49     /* close output stream */
50     static void closefile(void *p) { fclose((FILE *)p); }
51    
52     LUTAB ofiletab = LU_SINIT(free,closefile); /* output file table */
53    
54 greg 1.14 #define OF_MODIFIER 01
55     #define OF_BIN 02
56    
57 greg 1.1 FILE *getofile(const char *ospec, const char *mname, int bn);
58 greg 1.14 int ofname(char *oname, const char *ospec, const char *mname, int bn);
59     void printheader(FILE *fout, const char *info);
60 greg 1.1
61     /*
62     * The rcont structure is used to manage i/o with a particular
63     * rtrace child process. Input is passed unchanged from stdin,
64     * and output is processed in input order and accumulated according
65     * to the corresponding modifier and bin number.
66     */
67     struct rtproc {
68     struct rtproc *next; /* next in list of processes */
69     SUBPROC pd; /* rtrace pipe descriptors */
70 greg 1.2 unsigned long raynum; /* ray number for this tree */
71     int bsiz; /* ray tree buffer length */
72     char *buf; /* ray tree buffer */
73     int nbr; /* number of bytes from rtrace */
74 greg 1.5 }; /* rtrace process buffer */
75 greg 1.1
76     /* rtrace command and defaults */
77 greg 1.18 char *rtargv[256+2*MAXMODLIST] = { "rtrace",
78     "-dj", ".5", "-dr", "3",
79 greg 1.13 "-ab", "1", "-ad", "128", };
80     int rtargc = 9;
81 greg 1.1 /* overriding rtrace options */
82 greg 1.6 char *myrtopts[] = { "-o~~TmWdp", "-h-", "-x", "1", "-y", "0",
83     "-dt", "0", "-as", "0", "-aa", "0", NULL };
84 greg 1.1
85     struct rtproc rt0; /* head of rtrace process list */
86    
87     struct rtproc *rt_unproc = NULL; /* unprocessed ray trees */
88    
89     char persistfn[] = "pfXXXXXX"; /* persist file name */
90    
91     int gargc; /* global argc */
92     char **gargv; /* global argv */
93     #define progname gargv[0]
94    
95     char *octree; /* global octree argument */
96    
97     int inpfmt = 'a'; /* input format */
98     int outfmt = 'a'; /* output format */
99    
100     int header = 1; /* output header? */
101     int xres = 0; /* horiz. output resolution */
102     int yres = 0; /* vert. output resolution */
103    
104 greg 1.14 unsigned long raysleft; /* number of rays left to trace */
105 greg 1.1 long waitflush; /* how long until next flush */
106    
107     unsigned long lastray = 0; /* last ray number sent */
108     unsigned long lastdone = 0; /* last ray processed */
109    
110 greg 1.2 int using_stdout = 0; /* are we using stdout? */
111    
112 greg 1.1 const char *modname[MAXMODLIST]; /* ordered modifier name list */
113     int nmods = 0; /* number of modifiers */
114    
115     MODCONT *addmodifier(char *modn, char *outf, char *binv);
116 greg 1.17 void addmodfile(char *fname, char *outf, char *binv);
117 greg 1.1
118 greg 1.5 void init(int np);
119 greg 1.1 int done_rprocs(struct rtproc *rtp);
120 greg 1.14 void recover_output(FILE *fin);
121     void trace_contribs(FILE *fin);
122 greg 1.1 struct rtproc *wait_rproc(void);
123     struct rtproc *get_rproc(void);
124 greg 1.3 void queue_raytree(struct rtproc *rtp);
125     void process_queue(void);
126 greg 1.1
127 greg 1.14 void put_contrib(const DCOLOR cnt, FILE *fout);
128 greg 1.2 void add_contrib(const char *modn);
129 greg 1.1 void done_contrib(void);
130    
131     /* set input/output format */
132     static void
133     setformat(const char *fmt)
134     {
135     switch (fmt[0]) {
136     case 'f':
137     case 'd':
138 greg 1.10 SET_FILE_BINARY(stdin);
139     /* fall through */
140     case 'a':
141 greg 1.1 inpfmt = fmt[0];
142     break;
143     default:
144     goto fmterr;
145     }
146     switch (fmt[1]) {
147     case '\0':
148     outfmt = inpfmt;
149     return;
150     case 'a':
151     case 'f':
152     case 'd':
153     case 'c':
154     outfmt = fmt[1];
155     break;
156     default:
157     goto fmterr;
158     }
159     if (!fmt[2])
160     return;
161     fmterr:
162     sprintf(errmsg, "Illegal i/o format: -f%s", fmt);
163     error(USER, errmsg);
164     }
165    
166     /* gather rays from rtrace and output contributions */
167     int
168     main(int argc, char *argv[])
169     {
170     int nprocs = 1;
171 greg 1.14 int recover = 0;
172 greg 1.1 char *curout = NULL;
173     char *binval = NULL;
174 greg 1.5 char fmt[8];
175 greg 1.2 int i, j;
176     /* global program name */
177 greg 1.1 gargv = argv;
178 greg 1.11 /* initialize calcomp routines */
179 greg 1.1 esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
180     esupport &= ~(E_OUTCHAN);
181 greg 1.11 varset("PI", ':', PI);
182 greg 1.1 /* get our options */
183 greg 1.2 for (i = 1; i < argc-1; i++) {
184     /* expand arguments */
185     while ((j = expandarg(&argc, &argv, i)) > 0)
186     ;
187     if (j < 0) {
188     fprintf(stderr, "%s: cannot expand '%s'",
189     argv[0], argv[i]);
190     exit(1);
191     }
192     if (argv[i][0] == '-')
193     switch (argv[i][1]) {
194 greg 1.14 case 'r': /* recover output */
195     if (argv[i][2]) break;
196     recover++;
197     continue;
198 greg 1.2 case 'n': /* number of processes */
199 greg 1.21 if (argv[i][2] || i >= argc-2) break;
200 greg 1.2 nprocs = atoi(argv[++i]);
201     if (nprocs <= 0)
202     error(USER, "illegal number of processes");
203     continue;
204     case 'h': /* output header? */
205     switch (argv[i][2]) {
206     case '\0':
207     header = !header;
208     continue;
209 greg 1.3 case '+': case '1':
210     case 'T': case 't':
211     case 'Y': case 'y':
212 greg 1.2 header = 1;
213     continue;
214 greg 1.3 case '-': case '0':
215     case 'F': case 'f':
216     case 'N': case 'n':
217 greg 1.2 header = 0;
218     continue;
219     }
220     break;
221     case 'f': /* file or i/o format */
222     if (!argv[i][2]) {
223 greg 1.9 char *fpath;
224 greg 1.21 if (i >= argc-2) break;
225 greg 1.9 fpath = getpath(argv[++i],
226     getrlibpath(), R_OK);
227     if (fpath == NULL) {
228     sprintf(errmsg,
229     "cannot find file '%s'",
230     argv[i]);
231     error(USER, errmsg);
232     }
233     fcompile(fpath);
234 greg 1.2 continue;
235     }
236     setformat(argv[i]+2);
237     continue;
238     case 'e': /* expression */
239 greg 1.21 if (argv[i][2] || i >= argc-2) break;
240 greg 1.2 scompile(argv[++i], NULL, 0);
241 greg 1.1 continue;
242 greg 1.2 case 'o': /* output file spec. */
243 greg 1.21 if (argv[i][2] || i >= argc-2) break;
244 greg 1.2 curout = argv[++i];
245 greg 1.1 continue;
246 greg 1.2 case 'x': /* horiz. output resolution */
247 greg 1.21 if (argv[i][2] || i >= argc-2) break;
248 greg 1.2 xres = atoi(argv[++i]);
249 greg 1.1 continue;
250 greg 1.2 case 'y': /* vert. output resolution */
251 greg 1.21 if (argv[i][2] || i >= argc-2) break;
252 greg 1.2 yres = atoi(argv[++i]);
253     continue;
254     case 'b': /* bin expression */
255 greg 1.21 if (argv[i][2] || i >= argc-2) break;
256 greg 1.2 binval = argv[++i];
257     continue;
258     case 'm': /* modifier name */
259 greg 1.21 if (argv[i][2] || i >= argc-2) break;
260 greg 1.2 rtargv[rtargc++] = "-ti";
261     rtargv[rtargc++] = argv[++i];
262     addmodifier(argv[i], curout, binval);
263 greg 1.1 continue;
264 greg 1.17 case 'M': /* modifier file */
265 greg 1.21 if (argv[i][2] || i >= argc-2) break;
266 greg 1.19 rtargv[rtargc++] = "-tI";
267     rtargv[rtargc++] = argv[++i];
268     addmodfile(argv[i], curout, binval);
269 greg 1.17 continue;
270 greg 1.1 }
271 greg 1.2 rtargv[rtargc++] = argv[i]; /* assume rtrace option */
272 greg 1.1 }
273 greg 1.2 /* set global argument list */
274     gargc = argc; gargv = argv;
275 greg 1.1 /* add "mandatory" rtrace settings */
276 greg 1.2 for (j = 0; myrtopts[j] != NULL; j++)
277     rtargv[rtargc++] = myrtopts[j];
278     /* just asking for defaults? */
279     if (!strcmp(argv[i], "-defaults")) {
280 greg 1.1 char sxres[16], syres[16];
281     char *rtpath;
282 greg 1.2 printf("-n %-2d\t\t\t\t# number of processes\n", nprocs);
283 greg 1.1 fflush(stdout); /* report OUR options */
284     rtargv[rtargc++] = header ? "-h+" : "-h-";
285     sprintf(fmt, "-f%c%c", inpfmt, outfmt);
286     rtargv[rtargc++] = fmt;
287     rtargv[rtargc++] = "-x";
288     sprintf(sxres, "%d", xres);
289     rtargv[rtargc++] = sxres;
290     rtargv[rtargc++] = "-y";
291     sprintf(syres, "%d", yres);
292     rtargv[rtargc++] = syres;
293 greg 1.2 rtargv[rtargc++] = "-oTW";
294 greg 1.1 rtargv[rtargc++] = "-defaults";
295     rtargv[rtargc] = NULL;
296     rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
297     if (rtpath == NULL) {
298     eputs(rtargv[0]);
299     eputs(": command not found\n");
300     exit(1);
301     }
302     execv(rtpath, rtargv);
303     perror(rtpath); /* execv() should not return */
304     exit(1);
305 greg 1.5 }
306     if (nprocs > 1) { /* add persist file if parallel */
307 greg 1.2 rtargv[rtargc++] = "-PP";
308     rtargv[rtargc++] = mktemp(persistfn);
309     }
310 greg 1.1 /* add format string */
311     sprintf(fmt, "-f%cf", inpfmt);
312     rtargv[rtargc++] = fmt;
313     /* octree argument is last */
314 greg 1.2 if (i <= 0 || i != argc-1 || argv[i][0] == '-')
315     error(USER, "missing octree argument");
316     rtargv[rtargc++] = octree = argv[i];
317 greg 1.1 rtargv[rtargc] = NULL;
318 greg 1.24 /* start rtrace */
319 greg 1.1 init(nprocs);
320 greg 1.14 if (recover) /* perform recovery if requested */
321     recover_output(stdin);
322 greg 1.24 trace_contribs(stdin); /* compute contributions */
323 greg 1.1 quit(0);
324     }
325    
326     /* kill persistent rtrace process */
327     static void
328     killpersist(void)
329     {
330     FILE *fp = fopen(persistfn, "r");
331     int pid;
332    
333     if (fp == NULL)
334     return;
335     if (fscanf(fp, "%*s %d", &pid) != 1 || kill(pid, SIGALRM) < 0)
336     unlink(persistfn);
337     fclose(fp);
338     }
339    
340     /* close rtrace processes and clean up */
341     int
342     done_rprocs(struct rtproc *rtp)
343     {
344     int st0, st1 = 0;
345    
346     if (rtp->next != NULL) { /* close last opened first! */
347     st1 = done_rprocs(rtp->next);
348     free((void *)rtp->next);
349     rtp->next = NULL;
350     }
351     st0 = close_process(&rtp->pd);
352     if (st0 < 0)
353     error(WARNING, "unknown return status from rtrace process");
354     else if (st0 > 0)
355     return(st0);
356     return(st1);
357     }
358    
359     /* exit with status */
360     void
361     quit(int status)
362     {
363     int rtstat;
364    
365     if (rt0.next != NULL) /* terminate persistent rtrace */
366     killpersist();
367     /* clean up rtrace process(es) */
368     rtstat = done_rprocs(&rt0);
369     if (status == 0)
370     status = rtstat;
371     exit(status); /* flushes all output streams */
372     }
373    
374 greg 1.5 /* start rtrace processes and initialize */
375 greg 1.1 void
376     init(int np)
377     {
378     struct rtproc *rtp;
379     int i;
380     int maxbytes;
381 greg 1.2 /* make sure we have something to do */
382     if (!nmods)
383     error(USER, "No modifiers specified");
384 greg 1.1 /* assign ray variables */
385     scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
386     scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
387     /* set up signal handling */
388 greg 1.3 signal(SIGINT, quit);
389     #ifdef SIGHUP
390     signal(SIGHUP, quit);
391     #endif
392     #ifdef SIGTERM
393     signal(SIGTERM, quit);
394     #endif
395     #ifdef SIGPIPE
396 greg 1.1 signal(SIGPIPE, quit);
397     #endif
398     rtp = &rt0; /* start rtrace process(es) */
399     for (i = 0; i++ < np; ) {
400     errno = 0;
401     maxbytes = open_process(&rtp->pd, rtargv);
402     if (maxbytes == 0) {
403     eputs(rtargv[0]);
404     eputs(": command not found\n");
405     exit(1);
406     }
407     if (maxbytes < 0)
408     error(SYSTEM, "cannot start rtrace process");
409     if (maxbytes > treebufsiz)
410     treebufsiz = maxbytes;
411 greg 1.2 rtp->raynum = 0;
412 greg 1.1 rtp->bsiz = 0;
413     rtp->buf = NULL;
414 greg 1.2 rtp->nbr = 0;
415 greg 1.1 if (i == np) /* last process? */
416     break;
417     if (i == 1)
418     sleep(2); /* wait for persist file */
419     rtp->next = (struct rtproc *)malloc(sizeof(struct rtproc));
420     if (rtp->next == NULL)
421     error(SYSTEM, "out of memory in init");
422     rtp = rtp->next;
423     }
424     rtp->next = NULL; /* terminate list */
425     if (yres > 0) {
426     if (xres > 0)
427 greg 1.14 raysleft = (unsigned long)xres*yres;
428 greg 1.1 else
429     raysleft = yres;
430     } else
431     raysleft = 0;
432     waitflush = xres;
433     }
434    
435     /* add modifier to our list to track */
436     MODCONT *
437     addmodifier(char *modn, char *outf, char *binv)
438     {
439     LUENT *lep = lu_find(&modconttab, modn);
440     MODCONT *mp;
441    
442     if (lep->data != NULL) {
443     sprintf(errmsg, "duplicate modifier '%s'", modn);
444     error(USER, errmsg);
445     }
446     if (nmods >= MAXMODLIST)
447     error(USER, "too many modifiers");
448     modname[nmods++] = modn; /* XXX assumes static string */
449     lep->key = modn; /* XXX assumes static string */
450     mp = (MODCONT *)malloc(sizeof(MODCONT));
451     if (mp == NULL)
452     error(SYSTEM, "out of memory in addmodifier");
453     lep->data = (char *)mp;
454     mp->outspec = outf; /* XXX assumes static string */
455     mp->modname = modn; /* XXX assumes static string */
456     if (binv != NULL)
457     mp->binv = eparse(binv);
458     else
459     mp->binv = eparse("0");
460     mp->nbins = 1;
461     setcolor(mp->cbin[0], 0., 0., 0.);
462     return mp;
463     }
464    
465 greg 1.17 /* add modifiers from a file list */
466     void
467     addmodfile(char *fname, char *outf, char *binv)
468     {
469     char *mname[MAXMODLIST];
470     int i;
471 greg 1.20 /* find the file & store strings */
472     if (wordfile(mname, getpath(fname, getrlibpath(), R_OK)) < 0) {
473     sprintf(errmsg, "cannot find modifier file '%s'", fname);
474     error(SYSTEM, errmsg);
475     }
476 greg 1.17 for (i = 0; mname[i]; i++) /* add each one */
477     addmodifier(mname[i], outf, binv);
478     }
479    
480 greg 1.1 /* put string to stderr */
481     void
482     eputs(char *s)
483     {
484     static int midline = 0;
485    
486     if (!*s) return;
487     if (!midline) {
488     fputs(progname, stderr);
489     fputs(": ", stderr);
490     }
491     fputs(s, stderr);
492     midline = s[strlen(s)-1] != '\n';
493     }
494    
495 greg 1.14 /* construct output file name and return flags whether modifier/bin present */
496     int
497     ofname(char *oname, const char *ospec, const char *mname, int bn)
498     {
499     const char *mnp = NULL;
500     const char *bnp = NULL;
501     const char *cp;
502    
503     if (ospec == NULL)
504     return -1;
505     for (cp = ospec; *cp; cp++) /* check format position(s) */
506     if (*cp == '%') {
507     do
508     ++cp;
509     while (isdigit(*cp));
510     switch (*cp) {
511     case '%':
512     break;
513     case 's':
514     if (mnp != NULL)
515     return -1;
516     mnp = cp;
517     break;
518     case 'd':
519     if (bnp != NULL)
520     return -1;
521     bnp = cp;
522     break;
523     default:
524     return -1;
525     }
526     }
527     if (mnp != NULL) { /* create file name */
528     if (bnp != NULL) {
529     if (bnp > mnp)
530     sprintf(oname, ospec, mname, bn);
531     else
532     sprintf(oname, ospec, bn, mname);
533     return OF_MODIFIER|OF_BIN;
534     }
535     sprintf(oname, ospec, mname);
536     return OF_MODIFIER;
537     }
538     if (bnp != NULL) {
539     sprintf(oname, ospec, bn);
540     return OF_BIN;
541     }
542     strcpy(oname, ospec);
543     return 0;
544     }
545    
546 greg 1.1 /* write header to the given output stream */
547     void
548 greg 1.14 printheader(FILE *fout, const char *info)
549 greg 1.1 {
550     extern char VersionID[];
551     FILE *fin = fopen(octree, "r");
552    
553     if (fin == NULL)
554     quit(1);
555 greg 1.2 checkheader(fin, "ignore", fout); /* copy octree header */
556 greg 1.1 fclose(fin);
557     printargs(gargc-1, gargv, fout); /* add our command */
558     fprintf(fout, "SOFTWARE= %s\n", VersionID);
559     fputnow(fout);
560 greg 1.14 if (info != NULL) /* add extra info if given */
561     fputs(info, fout);
562 greg 1.1 switch (outfmt) { /* add output format */
563     case 'a':
564     fputformat("ascii", fout);
565     break;
566     case 'f':
567     fputformat("float", fout);
568     break;
569     case 'd':
570     fputformat("double", fout);
571     break;
572     case 'c':
573     fputformat(COLRFMT, fout);
574     break;
575     }
576     fputc('\n', fout);
577     if (xres > 0) {
578     if (yres > 0) /* resolution string */
579     fprtresolu(xres, yres, fout);
580     fflush(fout);
581     }
582     }
583    
584     /* Get output file pointer (open and write header if new) */
585     FILE *
586     getofile(const char *ospec, const char *mname, int bn)
587     {
588 greg 1.14 int ofl;
589     char oname[1024];
590 greg 1.1 LUENT *lep;
591    
592     if (ospec == NULL) { /* use stdout? */
593 greg 1.10 if (!using_stdout) {
594     if (outfmt != 'a')
595     SET_FILE_BINARY(stdout);
596     if (header)
597 greg 1.14 printheader(stdout, NULL);
598 greg 1.10 }
599 greg 1.1 using_stdout = 1;
600     return stdout;
601     }
602 greg 1.14 ofl = ofname(oname, ospec, mname, bn); /* get output name */
603     if (ofl < 0) {
604     sprintf(errmsg, "bad output format '%s'", ospec);
605     error(USER, errmsg);
606     }
607     lep = lu_find(&ofiletab, oname); /* look it up */
608 greg 1.1 if (lep->key == NULL) /* new entry */
609 greg 1.14 lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
610 greg 1.1 if (lep->data == NULL) { /* open output file */
611 greg 1.10 FILE *fp;
612 greg 1.2 int i;
613 greg 1.14 if (oname[0] == '!') /* output to command */
614     fp = popen(oname+1, "w");
615 greg 1.10 else
616 greg 1.14 fp = fopen(oname, "w");
617 greg 1.2 if (fp == NULL) {
618 greg 1.14 sprintf(errmsg, "cannot open '%s' for writing", oname);
619 greg 1.1 error(SYSTEM, errmsg);
620     }
621 greg 1.10 if (outfmt != 'a')
622     SET_FILE_BINARY(fp);
623 greg 1.14 if (header) {
624     char info[512];
625     char *cp = info;
626 greg 1.22 sprintf(cp, "MODIFIER=%s\n", mname);
627     while (*cp) ++cp;
628 greg 1.14 if (ofl & OF_BIN) {
629     sprintf(cp, "BIN=%d\n", bn);
630     while (*cp) ++cp;
631     }
632     *cp = '\0';
633     printheader(fp, info);
634     }
635 greg 1.2 /* play catch-up */
636     for (i = 0; i < lastdone; i++) {
637     static const DCOLOR nocontrib = BLKCOLOR;
638 greg 1.14 put_contrib(nocontrib, fp);
639 greg 1.2 if (outfmt == 'a')
640     putc('\n', fp);
641     }
642     if (xres > 0)
643     fflush(fp);
644     lep->data = (char *)fp;
645 greg 1.1 }
646     return (FILE *)lep->data; /* return open file pointer */
647     }
648    
649     /* read input ray into buffer */
650     int
651     getinp(char *buf, FILE *fp)
652     {
653 greg 1.4 char *cp;
654     int i;
655    
656 greg 1.1 switch (inpfmt) {
657     case 'a':
658 greg 1.4 cp = buf; /* make sure we get 6 floats */
659     for (i = 0; i < 6; i++) {
660     if (fgetword(cp, buf+127-cp, fp) == NULL)
661     return 0;
662     if ((cp = fskip(cp)) == NULL || *cp)
663     return 0;
664     *cp++ = ' ';
665     }
666     getc(fp); /* get/put eol */
667     *cp-- = '\0'; *cp = '\n';
668 greg 1.1 return strlen(buf);
669     case 'f':
670     if (fread(buf, sizeof(float), 6, fp) < 6)
671     return 0;
672     return sizeof(float)*6;
673     case 'd':
674     if (fread(buf, sizeof(double), 6, fp) < 6)
675     return 0;
676     return sizeof(double)*6;
677     }
678     error(INTERNAL, "botched input format");
679     return 0; /* pro forma return */
680     }
681    
682 greg 1.2 static float rparams[9]; /* traced ray parameters */
683 greg 1.1
684     /* return channel (ray) value */
685     double
686     chanvalue(int n)
687     {
688     if (--n < 0 || n >= 6)
689     error(USER, "illegal channel number ($N)");
690 greg 1.2 return rparams[n+3];
691 greg 1.1 }
692    
693 greg 1.2 /* add current ray contribution to the appropriate modifier bin */
694 greg 1.1 void
695 greg 1.2 add_contrib(const char *modn)
696 greg 1.1 {
697     LUENT *le = lu_find(&modconttab, modn);
698     MODCONT *mp = (MODCONT *)le->data;
699     int bn;
700    
701     if (mp == NULL) {
702     sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
703     error(USER, errmsg);
704     }
705 greg 1.2 eclock++; /* get bin number */
706 greg 1.1 bn = (int)(evalue(mp->binv) + .5);
707     if (bn <= 0)
708     bn = 0;
709     else if (bn > mp->nbins) { /* new bin */
710     mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
711 greg 1.2 bn*sizeof(DCOLOR));
712 greg 1.1 if (mp == NULL)
713     error(SYSTEM, "out of memory in add_contrib");
714 greg 1.2 memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(bn+1-mp->nbins));
715 greg 1.1 mp->nbins = bn+1;
716     le->data = (char *)mp;
717     }
718 greg 1.2 addcolor(mp->cbin[bn], rparams);
719 greg 1.1 }
720    
721     /* output newline to ASCII file and/or flush as requested */
722     static int
723     puteol(const LUENT *e, void *p)
724     {
725     FILE *fp = (FILE *)e->data;
726    
727     if (outfmt == 'a')
728     putc('\n', fp);
729     if (!waitflush)
730     fflush(fp);
731     if (ferror(fp)) {
732     sprintf(errmsg, "write error on file '%s'", e->key);
733     error(SYSTEM, errmsg);
734     }
735     return 0;
736     }
737    
738 greg 1.2 /* put out ray contribution to file */
739     void
740 greg 1.14 put_contrib(const DCOLOR cnt, FILE *fout)
741 greg 1.2 {
742     float fv[3];
743     COLR cv;
744    
745     switch (outfmt) {
746     case 'a':
747     fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
748     break;
749     case 'f':
750     fv[0] = cnt[0];
751     fv[1] = cnt[1];
752     fv[2] = cnt[2];
753     fwrite(fv, sizeof(float), 3, fout);
754     break;
755     case 'd':
756     fwrite(cnt, sizeof(double), 3, fout);
757     break;
758     case 'c':
759     setcolr(cv, cnt[0], cnt[1], cnt[2]);
760     fwrite(cv, sizeof(cv), 1, fout);
761     break;
762     default:
763     error(INTERNAL, "botched output format");
764     }
765     }
766    
767 greg 1.1 /* output ray tallies and clear for next primary */
768     void
769     done_contrib(void)
770     {
771     int i, j;
772     MODCONT *mp;
773 greg 1.14 FILE *fp;
774 greg 1.1 /* output modifiers in order */
775     for (i = 0; i < nmods; i++) {
776     mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
777 greg 1.12 fp = getofile(mp->outspec, mp->modname, 0);
778 greg 1.14 put_contrib(mp->cbin[0], fp);
779 greg 1.12 if (mp->nbins > 3 && /* minor optimization */
780     fp == getofile(mp->outspec, mp->modname, 1))
781     for (j = 1; j < mp->nbins; j++)
782 greg 1.14 put_contrib(mp->cbin[j], fp);
783 greg 1.12 else
784     for (j = 1; j < mp->nbins; j++)
785 greg 1.14 put_contrib(mp->cbin[j],
786 greg 1.2 getofile(mp->outspec, mp->modname, j));
787 greg 1.1 /* clear for next ray tree */
788 greg 1.2 memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
789 greg 1.1 }
790     --waitflush; /* terminate records */
791     lu_doall(&ofiletab, puteol, NULL);
792 greg 1.2 if (using_stdout & (outfmt == 'a'))
793     putc('\n', stdout);
794     if (!waitflush) {
795 greg 1.1 waitflush = xres;
796 greg 1.2 if (using_stdout)
797     fflush(stdout);
798     }
799 greg 1.1 }
800    
801 greg 1.3 /* queue completed ray tree produced by rtrace process */
802     void
803     queue_raytree(struct rtproc *rtp)
804     {
805     struct rtproc *rtu, *rtl = NULL;
806     /* insert following ray order */
807     for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
808     if (rtp->raynum < rtu->raynum)
809     break;
810     rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
811     if (rtu == NULL)
812     error(SYSTEM, "out of memory in queue_raytree");
813     *rtu = *rtp;
814     if (rtl == NULL) {
815     rtu->next = rt_unproc;
816     rt_unproc = rtu;
817     } else {
818     rtu->next = rtl->next;
819     rtl->next = rtu;
820     }
821     rtp->raynum = 0; /* clear path for next ray tree */
822     rtp->bsiz = 0;
823     rtp->buf = NULL;
824     rtp->nbr = 0;
825     }
826    
827     /* process completed ray trees from our queue */
828 greg 1.1 void
829 greg 1.3 process_queue(void)
830 greg 1.1 {
831 greg 1.3 char modname[128];
832     /* ray-ordered queue */
833     while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
834     struct rtproc *rtp = rt_unproc;
835 greg 1.2 int n = rtp->nbr;
836 greg 1.1 const char *cp = rtp->buf;
837     while (n > 0) { /* process rays */
838 greg 1.2 register char *mnp = modname;
839 greg 1.1 /* skip leading tabs */
840     while (n > 0 && *cp == '\t') {
841     cp++; n--;
842     }
843 greg 1.2 if (!n || !(isalpha(*cp) | (*cp == '_')))
844     error(USER, "bad modifier name from rtrace");
845     /* get modifier name */
846 greg 1.1 while (n > 0 && *cp != '\t') {
847     *mnp++ = *cp++; n--;
848     }
849     *mnp = '\0';
850 greg 1.2 cp++; n--; /* eat following tab */
851 greg 1.1 if (n < (int)(sizeof(float)*9))
852     error(USER, "incomplete ray value from rtrace");
853     /* add ray contribution */
854 greg 1.2 memcpy(rparams, cp, sizeof(float)*9);
855 greg 1.1 cp += sizeof(float)*9; n -= sizeof(float)*9;
856 greg 1.2 add_contrib(modname);
857 greg 1.1 }
858     done_contrib(); /* sum up contributions & output */
859     lastdone = rtp->raynum;
860 greg 1.3 free(rtp->buf); /* free up buffer space */
861     rt_unproc = rtp->next;
862     free(rtp); /* done with this ray tree */
863 greg 1.1 }
864     }
865    
866     /* wait for rtrace process to finish with ray tree */
867     struct rtproc *
868     wait_rproc(void)
869     {
870     struct rtproc *rtfree = NULL;
871     fd_set readset, errset;
872     int nr;
873     struct rtproc *rt;
874     int n;
875    
876     do {
877     nr = 0; /* prepare select call */
878     FD_ZERO(&readset); FD_ZERO(&errset); n = 0;
879     for (rt = &rt0; rt != NULL; rt = rt->next) {
880     if (rt->raynum) {
881     FD_SET(rt->pd.r, &readset);
882     ++nr;
883     }
884     FD_SET(rt->pd.r, &errset);
885     if (rt->pd.r >= n)
886     n = rt->pd.r + 1;
887     }
888     if (!nr) /* no rays pending */
889     break;
890     if (nr > 1) { /* call select for multiple proc's */
891     errno = 0;
892     if (select(n, &readset, NULL, &errset, NULL) < 0)
893     error(SYSTEM, "select call error in wait_rproc()");
894     } else
895     FD_ZERO(&errset);
896     nr = 0;
897     for (rt = &rt0; rt != NULL; rt = rt->next) {
898     if (!FD_ISSET(rt->pd.r, &readset) &&
899     !FD_ISSET(rt->pd.r, &errset))
900     continue;
901     if (rt->buf == NULL) {
902     rt->bsiz = treebufsiz;
903     rt->buf = (char *)malloc(treebufsiz);
904 greg 1.2 } else if (rt->nbr + BUFSIZ > rt->bsiz) {
905 greg 1.1 if (rt->bsiz + BUFSIZ <= treebufsiz)
906     rt->bsiz = treebufsiz;
907     else
908     rt->bsiz = treebufsiz += BUFSIZ;
909     rt->buf = (char *)realloc(rt->buf, rt->bsiz);
910     }
911     if (rt->buf == NULL)
912     error(SYSTEM, "out of memory in wait_rproc");
913 greg 1.2 nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
914     if (nr <= 0)
915 greg 1.1 error(USER, "rtrace process died");
916 greg 1.2 rt->nbr += nr; /* advance & check */
917     if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
918     "~\t~\t", 4)) {
919     rt->nbr -= 4; /* elide terminator */
920 greg 1.3 queue_raytree(rt);
921 greg 1.1 rtfree = rt; /* ready for next ray */
922     }
923     }
924     } while ((rtfree == NULL) & (nr > 0)); /* repeat until ready or out */
925     return rtfree;
926     }
927    
928     /* return next available rtrace process */
929     struct rtproc *
930     get_rproc(void)
931     {
932     struct rtproc *rtp;
933     /* check for idle rtrace */
934     for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
935     if (!rtp->raynum)
936     return rtp;
937     return wait_rproc(); /* need to wait for one */
938     }
939    
940     /* trace ray contributions (main loop) */
941     void
942 greg 1.5 trace_contribs(FILE *fin)
943 greg 1.1 {
944     char inpbuf[128];
945     int iblen;
946     struct rtproc *rtp;
947     /* loop over input */
948     while ((iblen = getinp(inpbuf, fin)) > 0) {
949     if (lastray+1 < lastray) { /* counter rollover? */
950     while (wait_rproc() != NULL)
951 greg 1.3 process_queue();
952 greg 1.1 lastdone = lastray = 0;
953     }
954     rtp = get_rproc(); /* get avail. rtrace process */
955 greg 1.3 rtp->raynum = ++lastray; /* assign ray to it */
956 greg 1.1 writebuf(rtp->pd.w, inpbuf, iblen);
957 greg 1.14 if (raysleft && !--raysleft)
958 greg 1.3 break;
959     process_queue(); /* catch up with results */
960 greg 1.1 }
961     while (wait_rproc() != NULL) /* process outstanding rays */
962 greg 1.3 process_queue();
963 greg 1.14 if (raysleft)
964 greg 1.2 error(USER, "unexpected EOF on input");
965 greg 1.14 lu_done(&ofiletab); /* close output files */
966     }
967    
968     /* seek on the given output file */
969     static int
970     myseeko(const LUENT *e, void *p)
971     {
972     if (fseeko((FILE *)e->data, *(off_t *)p, SEEK_CUR) < 0) {
973     sprintf(errmsg, "seek error on file '%s'", e->key);
974     error(SYSTEM, errmsg);
975     }
976     }
977    
978     /* recover output if possible */
979     void
980     recover_output(FILE *fin)
981     {
982     off_t lastout = -1;
983     int outvsiz;
984     char *outvfmt;
985     int i, j;
986     MODCONT *mp;
987     int ofl;
988     char oname[1024];
989     LUENT *ment, *oent;
990     FILE *fp;
991     off_t nvals;
992    
993     switch (outfmt) {
994     case 'a':
995     error(USER, "cannot recover ASCII output");
996     return;
997     case 'f':
998     outvsiz = sizeof(float)*3;
999     outvfmt = "float";
1000     break;
1001     case 'd':
1002     outvsiz = sizeof(double)*3;
1003     outvfmt = "double";
1004     break;
1005     case 'c':
1006     outvsiz = sizeof(COLR);
1007     outvfmt = COLRFMT;
1008     break;
1009     default:
1010     error(INTERNAL, "botched output format");
1011     return;
1012     }
1013     /* check modifier outputs */
1014     for (i = 0; i < nmods; i++) {
1015     ment = lu_find(&modconttab,modname[i]);
1016     mp = (MODCONT *)ment->data;
1017     if (mp->outspec == NULL)
1018     error(USER, "cannot recover from stdout");
1019     for (j = 0; ; j++) { /* check each bin's file */
1020     ofl = ofname(oname, mp->outspec, mp->modname, j);
1021     if (ofl < 0)
1022     error(USER, "bad output file specification");
1023     oent = lu_find(&ofiletab, oname);
1024     if (oent->data != NULL) { /* saw this one already */
1025     if (ofl & OF_BIN)
1026     continue;
1027     break;
1028     }
1029     if (oname[0] == '!')
1030     error(USER, "cannot recover from command");
1031     /* open output */
1032     fp = fopen(oname, "rb+");
1033 greg 1.23 if (fp == NULL) {
1034     if (j)
1035     break; /* assume end of modifier */
1036     sprintf(errmsg, "missing recover file '%s'",
1037     oname);
1038     error(USER, errmsg);
1039     }
1040 greg 1.14 nvals = lseek(fileno(fp), 0, SEEK_END);
1041     if (nvals <= 0) {
1042     lastout = 0; /* empty output, quit here */
1043     fclose(fp);
1044     break;
1045     }
1046     lseek(fileno(fp), 0, SEEK_SET);
1047     if (header) {
1048     int xr, yr;
1049     if (checkheader(fp, outvfmt, NULL) != 1) {
1050     sprintf(errmsg,
1051     "format mismatch for '%s'",
1052     oname);
1053     error(USER, errmsg);
1054     }
1055     if (xres > 0 && yres > 0 &&
1056     (!fscnresolu(&xr, &yr, fp) ||
1057     xr != xres ||
1058     yr != yres)) {
1059     sprintf(errmsg,
1060     "resolution mismatch for '%s'",
1061     oname);
1062     error(USER, errmsg);
1063     }
1064     }
1065     nvals = (nvals - (off_t)ftell(fp)) / outvsiz;
1066     if (lastout < 0 || nvals < lastout)
1067     lastout = nvals;
1068     if (oent->key == NULL) /* new entry */
1069     oent->key = strcpy((char *)
1070     malloc(strlen(oname)+1), oname);
1071     oent->data = (char *)fp;
1072     if (!(ofl & OF_BIN))
1073     break; /* no bin separation */
1074     }
1075     if (!lastout) { /* empty output */
1076 greg 1.16 error(WARNING, "no previous data to recover");
1077 greg 1.14 lu_done(&ofiletab); /* reclose all outputs */
1078     return;
1079     }
1080     if (j > mp->nbins) { /* preallocate modifier bins */
1081     mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
1082     (j-1)*sizeof(DCOLOR));
1083     if (mp == NULL)
1084     error(SYSTEM, "out of memory in recover_output");
1085     memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
1086     mp->nbins = j;
1087     ment->data = (char *)mp;
1088     }
1089     }
1090 greg 1.15 if (lastout < 0) {
1091 greg 1.16 error(WARNING, "no output files to recover");
1092 greg 1.15 return;
1093     }
1094 greg 1.24 if (raysleft && lastout >= raysleft) {
1095     error(WARNING, "output appears to be complete");
1096     /* XXX should read & discard input? */
1097     quit(0);
1098     }
1099 greg 1.14 /* seek on all files */
1100     nvals = lastout * outvsiz;
1101     lu_doall(&ofiletab, myseeko, &nvals);
1102     /* discard input */
1103     for (nvals = 0; nvals < lastout; nvals++)
1104     if (getinp(oname, fin) <= 0)
1105     error(USER, "unexpected EOF on input");
1106     lastray = lastdone = (unsigned long)lastout;
1107     if (raysleft)
1108     raysleft -= lastray;
1109 greg 1.1 }