ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.14
Committed: Thu Jun 9 17:27:28 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.13: +238 -65 lines
Log Message:
Implementaed rtcontrib -r (recover) option, added MODIFIER= + BIN= to header

File Contents

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