ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.17
Committed: Fri Jun 10 16:42:11 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.16: +18 -1 lines
Log Message:
Added rtcontrib -M option to read modifier list from a file

File Contents

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