ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.20
Committed: Fri Jun 10 20:53:55 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.19: +6 -3 lines
Log Message:
Fixed it so rtcontrib -M option searches RAYPATH directories

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: rtcontrib.c,v 1.19 2005/06/10 20:44:00 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 #ifndef MAXMODLIST
20 #define MAXMODLIST 1024 /* maximum modifiers we'll track */
21 #endif
22
23 int treebufsiz = BUFSIZ; /* current tree buffer size */
24
25 typedef double DCOLOR[3]; /* double-precision color */
26
27 /*
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 DCOLOR cbin[1]; /* contribution bins (extends struct) */
43 } 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 #define OF_MODIFIER 01
55 #define OF_BIN 02
56
57 FILE *getofile(const char *ospec, const char *mname, int bn);
58 int ofname(char *oname, const char *ospec, const char *mname, int bn);
59 void printheader(FILE *fout, const char *info);
60
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 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 }; /* rtrace process buffer */
75
76 /* rtrace command and defaults */
77 char *rtargv[256+2*MAXMODLIST] = { "rtrace",
78 "-dj", ".5", "-dr", "3",
79 "-ab", "1", "-ad", "128", };
80 int rtargc = 9;
81 /* overriding rtrace options */
82 char *myrtopts[] = { "-o~~TmWdp", "-h-", "-x", "1", "-y", "0",
83 "-dt", "0", "-as", "0", "-aa", "0", NULL };
84
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 unsigned long raysleft; /* number of rays left to trace */
105 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 int using_stdout = 0; /* are we using stdout? */
111
112 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 void addmodfile(char *fname, char *outf, char *binv);
117
118 void init(int np);
119 int done_rprocs(struct rtproc *rtp);
120 void recover_output(FILE *fin);
121 void trace_contribs(FILE *fin);
122 struct rtproc *wait_rproc(void);
123 struct rtproc *get_rproc(void);
124 void queue_raytree(struct rtproc *rtp);
125 void process_queue(void);
126
127 void put_contrib(const DCOLOR cnt, FILE *fout);
128 void add_contrib(const char *modn);
129 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 SET_FILE_BINARY(stdin);
139 /* fall through */
140 case 'a':
141 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 int recover = 0;
172 char *curout = NULL;
173 char *binval = NULL;
174 char fmt[8];
175 int i, j;
176 /* global program name */
177 gargv = argv;
178 /* initialize calcomp routines */
179 esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
180 esupport &= ~(E_OUTCHAN);
181 varset("PI", ':', PI);
182 /* get our options */
183 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 case 'r': /* recover output */
195 if (argv[i][2]) break;
196 recover++;
197 continue;
198 case 'n': /* number of processes */
199 if (argv[i][2] || i >= argc-1) break;
200 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 case '+': case '1':
210 case 'T': case 't':
211 case 'Y': case 'y':
212 header = 1;
213 continue;
214 case '-': case '0':
215 case 'F': case 'f':
216 case 'N': case 'n':
217 header = 0;
218 continue;
219 }
220 break;
221 case 'f': /* file or i/o format */
222 if (!argv[i][2]) {
223 char *fpath;
224 if (i >= argc-1) break;
225 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 continue;
235 }
236 setformat(argv[i]+2);
237 continue;
238 case 'e': /* expression */
239 if (argv[i][2] || i >= argc-1) break;
240 scompile(argv[++i], NULL, 0);
241 continue;
242 case 'o': /* output file spec. */
243 if (argv[i][2] || i >= argc-1) break;
244 curout = argv[++i];
245 continue;
246 case 'x': /* horiz. output resolution */
247 if (argv[i][2] || i >= argc-1) break;
248 xres = atoi(argv[++i]);
249 continue;
250 case 'y': /* vert. output resolution */
251 if (argv[i][2] || i >= argc-1) break;
252 yres = atoi(argv[++i]);
253 continue;
254 case 'b': /* bin expression */
255 if (argv[i][2] || i >= argc-1) break;
256 binval = argv[++i];
257 continue;
258 case 'm': /* modifier name */
259 if (argv[i][2] || i >= argc-1) break;
260 rtargv[rtargc++] = "-ti";
261 rtargv[rtargc++] = argv[++i];
262 addmodifier(argv[i], curout, binval);
263 continue;
264 case 'M': /* modifier file */
265 if (argv[i][2] || i >= argc-1) break;
266 rtargv[rtargc++] = "-tI";
267 rtargv[rtargc++] = argv[++i];
268 addmodfile(argv[i], curout, binval);
269 continue;
270 }
271 rtargv[rtargc++] = argv[i]; /* assume rtrace option */
272 }
273 /* set global argument list */
274 gargc = argc; gargv = argv;
275 /* add "mandatory" rtrace settings */
276 for (j = 0; myrtopts[j] != NULL; j++)
277 rtargv[rtargc++] = myrtopts[j];
278 /* just asking for defaults? */
279 if (!strcmp(argv[i], "-defaults")) {
280 char sxres[16], syres[16];
281 char *rtpath;
282 printf("-n %-2d\t\t\t\t# number of processes\n", nprocs);
283 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 rtargv[rtargc++] = "-oTW";
294 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 }
306 if (nprocs > 1) { /* add persist file if parallel */
307 rtargv[rtargc++] = "-PP";
308 rtargv[rtargc++] = mktemp(persistfn);
309 }
310 /* add format string */
311 sprintf(fmt, "-f%cf", inpfmt);
312 rtargv[rtargc++] = fmt;
313 /* octree argument is last */
314 if (i <= 0 || i != argc-1 || argv[i][0] == '-')
315 error(USER, "missing octree argument");
316 rtargv[rtargc++] = octree = argv[i];
317 rtargv[rtargc] = NULL;
318 /* start rtrace & compute contributions */
319 init(nprocs);
320 if (recover) /* perform recovery if requested */
321 recover_output(stdin);
322 trace_contribs(stdin);
323 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 /* start rtrace processes and initialize */
375 void
376 init(int np)
377 {
378 struct rtproc *rtp;
379 int i;
380 int maxbytes;
381 /* make sure we have something to do */
382 if (!nmods)
383 error(USER, "No modifiers specified");
384 /* 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 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 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 rtp->raynum = 0;
412 rtp->bsiz = 0;
413 rtp->buf = NULL;
414 rtp->nbr = 0;
415 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 raysleft = (unsigned long)xres*yres;
428 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 /* 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 /* 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 for (i = 0; mname[i]; i++) /* add each one */
477 addmodifier(mname[i], outf, binv);
478 }
479
480 /* 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 /* 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 /* write header to the given output stream */
547 void
548 printheader(FILE *fout, const char *info)
549 {
550 extern char VersionID[];
551 FILE *fin = fopen(octree, "r");
552
553 if (fin == NULL)
554 quit(1);
555 checkheader(fin, "ignore", fout); /* copy octree header */
556 fclose(fin);
557 printargs(gargc-1, gargv, fout); /* add our command */
558 fprintf(fout, "SOFTWARE= %s\n", VersionID);
559 fputnow(fout);
560 if (info != NULL) /* add extra info if given */
561 fputs(info, fout);
562 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 int ofl;
589 char oname[1024];
590 LUENT *lep;
591
592 if (ospec == NULL) { /* use stdout? */
593 if (!using_stdout) {
594 if (outfmt != 'a')
595 SET_FILE_BINARY(stdout);
596 if (header)
597 printheader(stdout, NULL);
598 }
599 using_stdout = 1;
600 return stdout;
601 }
602 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 if (lep->key == NULL) /* new entry */
609 lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
610 if (lep->data == NULL) { /* open output file */
611 FILE *fp;
612 int i;
613 if (oname[0] == '!') /* output to command */
614 fp = popen(oname+1, "w");
615 else
616 fp = fopen(oname, "w");
617 if (fp == NULL) {
618 sprintf(errmsg, "cannot open '%s' for writing", oname);
619 error(SYSTEM, errmsg);
620 }
621 if (outfmt != 'a')
622 SET_FILE_BINARY(fp);
623 if (header) {
624 char info[512];
625 char *cp = info;
626 if (ofl & OF_MODIFIER) {
627 sprintf(cp, "MODIFIER=%s\n", mname);
628 while (*cp) ++cp;
629 }
630 if (ofl & OF_BIN) {
631 sprintf(cp, "BIN=%d\n", bn);
632 while (*cp) ++cp;
633 }
634 *cp = '\0';
635 printheader(fp, info);
636 }
637 /* play catch-up */
638 for (i = 0; i < lastdone; i++) {
639 static const DCOLOR nocontrib = BLKCOLOR;
640 put_contrib(nocontrib, fp);
641 if (outfmt == 'a')
642 putc('\n', fp);
643 }
644 if (xres > 0)
645 fflush(fp);
646 lep->data = (char *)fp;
647 }
648 return (FILE *)lep->data; /* return open file pointer */
649 }
650
651 /* read input ray into buffer */
652 int
653 getinp(char *buf, FILE *fp)
654 {
655 char *cp;
656 int i;
657
658 switch (inpfmt) {
659 case 'a':
660 cp = buf; /* make sure we get 6 floats */
661 for (i = 0; i < 6; i++) {
662 if (fgetword(cp, buf+127-cp, fp) == NULL)
663 return 0;
664 if ((cp = fskip(cp)) == NULL || *cp)
665 return 0;
666 *cp++ = ' ';
667 }
668 getc(fp); /* get/put eol */
669 *cp-- = '\0'; *cp = '\n';
670 return strlen(buf);
671 case 'f':
672 if (fread(buf, sizeof(float), 6, fp) < 6)
673 return 0;
674 return sizeof(float)*6;
675 case 'd':
676 if (fread(buf, sizeof(double), 6, fp) < 6)
677 return 0;
678 return sizeof(double)*6;
679 }
680 error(INTERNAL, "botched input format");
681 return 0; /* pro forma return */
682 }
683
684 static float rparams[9]; /* traced ray parameters */
685
686 /* return channel (ray) value */
687 double
688 chanvalue(int n)
689 {
690 if (--n < 0 || n >= 6)
691 error(USER, "illegal channel number ($N)");
692 return rparams[n+3];
693 }
694
695 /* add current ray contribution to the appropriate modifier bin */
696 void
697 add_contrib(const char *modn)
698 {
699 LUENT *le = lu_find(&modconttab, modn);
700 MODCONT *mp = (MODCONT *)le->data;
701 int bn;
702
703 if (mp == NULL) {
704 sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
705 error(USER, errmsg);
706 }
707 eclock++; /* get bin number */
708 bn = (int)(evalue(mp->binv) + .5);
709 if (bn <= 0)
710 bn = 0;
711 else if (bn > mp->nbins) { /* new bin */
712 mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
713 bn*sizeof(DCOLOR));
714 if (mp == NULL)
715 error(SYSTEM, "out of memory in add_contrib");
716 memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(bn+1-mp->nbins));
717 mp->nbins = bn+1;
718 le->data = (char *)mp;
719 }
720 addcolor(mp->cbin[bn], rparams);
721 }
722
723 /* output newline to ASCII file and/or flush as requested */
724 static int
725 puteol(const LUENT *e, void *p)
726 {
727 FILE *fp = (FILE *)e->data;
728
729 if (outfmt == 'a')
730 putc('\n', fp);
731 if (!waitflush)
732 fflush(fp);
733 if (ferror(fp)) {
734 sprintf(errmsg, "write error on file '%s'", e->key);
735 error(SYSTEM, errmsg);
736 }
737 return 0;
738 }
739
740 /* put out ray contribution to file */
741 void
742 put_contrib(const DCOLOR cnt, FILE *fout)
743 {
744 float fv[3];
745 COLR cv;
746
747 switch (outfmt) {
748 case 'a':
749 fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
750 break;
751 case 'f':
752 fv[0] = cnt[0];
753 fv[1] = cnt[1];
754 fv[2] = cnt[2];
755 fwrite(fv, sizeof(float), 3, fout);
756 break;
757 case 'd':
758 fwrite(cnt, sizeof(double), 3, fout);
759 break;
760 case 'c':
761 setcolr(cv, cnt[0], cnt[1], cnt[2]);
762 fwrite(cv, sizeof(cv), 1, fout);
763 break;
764 default:
765 error(INTERNAL, "botched output format");
766 }
767 }
768
769 /* output ray tallies and clear for next primary */
770 void
771 done_contrib(void)
772 {
773 int i, j;
774 MODCONT *mp;
775 FILE *fp;
776 /* output modifiers in order */
777 for (i = 0; i < nmods; i++) {
778 mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
779 fp = getofile(mp->outspec, mp->modname, 0);
780 put_contrib(mp->cbin[0], fp);
781 if (mp->nbins > 3 && /* minor optimization */
782 fp == getofile(mp->outspec, mp->modname, 1))
783 for (j = 1; j < mp->nbins; j++)
784 put_contrib(mp->cbin[j], fp);
785 else
786 for (j = 1; j < mp->nbins; j++)
787 put_contrib(mp->cbin[j],
788 getofile(mp->outspec, mp->modname, j));
789 /* clear for next ray tree */
790 memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
791 }
792 --waitflush; /* terminate records */
793 lu_doall(&ofiletab, puteol, NULL);
794 if (using_stdout & (outfmt == 'a'))
795 putc('\n', stdout);
796 if (!waitflush) {
797 waitflush = xres;
798 if (using_stdout)
799 fflush(stdout);
800 }
801 }
802
803 /* queue completed ray tree produced by rtrace process */
804 void
805 queue_raytree(struct rtproc *rtp)
806 {
807 struct rtproc *rtu, *rtl = NULL;
808 /* insert following ray order */
809 for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
810 if (rtp->raynum < rtu->raynum)
811 break;
812 rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
813 if (rtu == NULL)
814 error(SYSTEM, "out of memory in queue_raytree");
815 *rtu = *rtp;
816 if (rtl == NULL) {
817 rtu->next = rt_unproc;
818 rt_unproc = rtu;
819 } else {
820 rtu->next = rtl->next;
821 rtl->next = rtu;
822 }
823 rtp->raynum = 0; /* clear path for next ray tree */
824 rtp->bsiz = 0;
825 rtp->buf = NULL;
826 rtp->nbr = 0;
827 }
828
829 /* process completed ray trees from our queue */
830 void
831 process_queue(void)
832 {
833 char modname[128];
834 /* ray-ordered queue */
835 while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
836 struct rtproc *rtp = rt_unproc;
837 int n = rtp->nbr;
838 const char *cp = rtp->buf;
839 while (n > 0) { /* process rays */
840 register char *mnp = modname;
841 /* skip leading tabs */
842 while (n > 0 && *cp == '\t') {
843 cp++; n--;
844 }
845 if (!n || !(isalpha(*cp) | (*cp == '_')))
846 error(USER, "bad modifier name from rtrace");
847 /* get modifier name */
848 while (n > 0 && *cp != '\t') {
849 *mnp++ = *cp++; n--;
850 }
851 *mnp = '\0';
852 cp++; n--; /* eat following tab */
853 if (n < (int)(sizeof(float)*9))
854 error(USER, "incomplete ray value from rtrace");
855 /* add ray contribution */
856 memcpy(rparams, cp, sizeof(float)*9);
857 cp += sizeof(float)*9; n -= sizeof(float)*9;
858 add_contrib(modname);
859 }
860 done_contrib(); /* sum up contributions & output */
861 lastdone = rtp->raynum;
862 free(rtp->buf); /* free up buffer space */
863 rt_unproc = rtp->next;
864 free(rtp); /* done with this ray tree */
865 }
866 }
867
868 /* wait for rtrace process to finish with ray tree */
869 struct rtproc *
870 wait_rproc(void)
871 {
872 struct rtproc *rtfree = NULL;
873 fd_set readset, errset;
874 int nr;
875 struct rtproc *rt;
876 int n;
877
878 do {
879 nr = 0; /* prepare select call */
880 FD_ZERO(&readset); FD_ZERO(&errset); n = 0;
881 for (rt = &rt0; rt != NULL; rt = rt->next) {
882 if (rt->raynum) {
883 FD_SET(rt->pd.r, &readset);
884 ++nr;
885 }
886 FD_SET(rt->pd.r, &errset);
887 if (rt->pd.r >= n)
888 n = rt->pd.r + 1;
889 }
890 if (!nr) /* no rays pending */
891 break;
892 if (nr > 1) { /* call select for multiple proc's */
893 errno = 0;
894 if (select(n, &readset, NULL, &errset, NULL) < 0)
895 error(SYSTEM, "select call error in wait_rproc()");
896 } else
897 FD_ZERO(&errset);
898 nr = 0;
899 for (rt = &rt0; rt != NULL; rt = rt->next) {
900 if (!FD_ISSET(rt->pd.r, &readset) &&
901 !FD_ISSET(rt->pd.r, &errset))
902 continue;
903 if (rt->buf == NULL) {
904 rt->bsiz = treebufsiz;
905 rt->buf = (char *)malloc(treebufsiz);
906 } else if (rt->nbr + BUFSIZ > rt->bsiz) {
907 if (rt->bsiz + BUFSIZ <= treebufsiz)
908 rt->bsiz = treebufsiz;
909 else
910 rt->bsiz = treebufsiz += BUFSIZ;
911 rt->buf = (char *)realloc(rt->buf, rt->bsiz);
912 }
913 if (rt->buf == NULL)
914 error(SYSTEM, "out of memory in wait_rproc");
915 nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
916 if (nr <= 0)
917 error(USER, "rtrace process died");
918 rt->nbr += nr; /* advance & check */
919 if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
920 "~\t~\t", 4)) {
921 rt->nbr -= 4; /* elide terminator */
922 queue_raytree(rt);
923 rtfree = rt; /* ready for next ray */
924 }
925 }
926 } while ((rtfree == NULL) & (nr > 0)); /* repeat until ready or out */
927 return rtfree;
928 }
929
930 /* return next available rtrace process */
931 struct rtproc *
932 get_rproc(void)
933 {
934 struct rtproc *rtp;
935 /* check for idle rtrace */
936 for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
937 if (!rtp->raynum)
938 return rtp;
939 return wait_rproc(); /* need to wait for one */
940 }
941
942 /* trace ray contributions (main loop) */
943 void
944 trace_contribs(FILE *fin)
945 {
946 char inpbuf[128];
947 int iblen;
948 struct rtproc *rtp;
949 /* loop over input */
950 while ((iblen = getinp(inpbuf, fin)) > 0) {
951 if (lastray+1 < lastray) { /* counter rollover? */
952 while (wait_rproc() != NULL)
953 process_queue();
954 lastdone = lastray = 0;
955 }
956 rtp = get_rproc(); /* get avail. rtrace process */
957 rtp->raynum = ++lastray; /* assign ray to it */
958 writebuf(rtp->pd.w, inpbuf, iblen);
959 if (raysleft && !--raysleft)
960 break;
961 process_queue(); /* catch up with results */
962 }
963 while (wait_rproc() != NULL) /* process outstanding rays */
964 process_queue();
965 if (raysleft)
966 error(USER, "unexpected EOF on input");
967 lu_done(&ofiletab); /* close output files */
968 }
969
970 /* seek on the given output file */
971 static int
972 myseeko(const LUENT *e, void *p)
973 {
974 if (fseeko((FILE *)e->data, *(off_t *)p, SEEK_CUR) < 0) {
975 sprintf(errmsg, "seek error on file '%s'", e->key);
976 error(SYSTEM, errmsg);
977 }
978 }
979
980 /* recover output if possible */
981 void
982 recover_output(FILE *fin)
983 {
984 off_t lastout = -1;
985 int outvsiz;
986 char *outvfmt;
987 int i, j;
988 MODCONT *mp;
989 int ofl;
990 char oname[1024];
991 LUENT *ment, *oent;
992 FILE *fp;
993 off_t nvals;
994
995 switch (outfmt) {
996 case 'a':
997 error(USER, "cannot recover ASCII output");
998 return;
999 case 'f':
1000 outvsiz = sizeof(float)*3;
1001 outvfmt = "float";
1002 break;
1003 case 'd':
1004 outvsiz = sizeof(double)*3;
1005 outvfmt = "double";
1006 break;
1007 case 'c':
1008 outvsiz = sizeof(COLR);
1009 outvfmt = COLRFMT;
1010 break;
1011 default:
1012 error(INTERNAL, "botched output format");
1013 return;
1014 }
1015 /* check modifier outputs */
1016 for (i = 0; i < nmods; i++) {
1017 ment = lu_find(&modconttab,modname[i]);
1018 mp = (MODCONT *)ment->data;
1019 if (mp->outspec == NULL)
1020 error(USER, "cannot recover from stdout");
1021 for (j = 0; ; j++) { /* check each bin's file */
1022 ofl = ofname(oname, mp->outspec, mp->modname, j);
1023 if (ofl < 0)
1024 error(USER, "bad output file specification");
1025 oent = lu_find(&ofiletab, oname);
1026 if (oent->data != NULL) { /* saw this one already */
1027 if (ofl & OF_BIN)
1028 continue;
1029 break;
1030 }
1031 if (oname[0] == '!')
1032 error(USER, "cannot recover from command");
1033 /* open output */
1034 fp = fopen(oname, "rb+");
1035 if (fp == NULL)
1036 break; /* must be end of modifier */
1037 nvals = lseek(fileno(fp), 0, SEEK_END);
1038 if (nvals <= 0) {
1039 lastout = 0; /* empty output, quit here */
1040 fclose(fp);
1041 break;
1042 }
1043 lseek(fileno(fp), 0, SEEK_SET);
1044 if (header) {
1045 int xr, yr;
1046 if (checkheader(fp, outvfmt, NULL) != 1) {
1047 sprintf(errmsg,
1048 "format mismatch for '%s'",
1049 oname);
1050 error(USER, errmsg);
1051 }
1052 if (xres > 0 && yres > 0 &&
1053 (!fscnresolu(&xr, &yr, fp) ||
1054 xr != xres ||
1055 yr != yres)) {
1056 sprintf(errmsg,
1057 "resolution mismatch for '%s'",
1058 oname);
1059 error(USER, errmsg);
1060 }
1061 }
1062 nvals = (nvals - (off_t)ftell(fp)) / outvsiz;
1063 if (lastout < 0 || nvals < lastout)
1064 lastout = nvals;
1065 if (oent->key == NULL) /* new entry */
1066 oent->key = strcpy((char *)
1067 malloc(strlen(oname)+1), oname);
1068 oent->data = (char *)fp;
1069 if (!(ofl & OF_BIN))
1070 break; /* no bin separation */
1071 }
1072 if (!lastout) { /* empty output */
1073 error(WARNING, "no previous data to recover");
1074 lu_done(&ofiletab); /* reclose all outputs */
1075 return;
1076 }
1077 if (j > mp->nbins) { /* preallocate modifier bins */
1078 mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
1079 (j-1)*sizeof(DCOLOR));
1080 if (mp == NULL)
1081 error(SYSTEM, "out of memory in recover_output");
1082 memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
1083 mp->nbins = j;
1084 ment->data = (char *)mp;
1085 }
1086 }
1087 if (lastout < 0) {
1088 error(WARNING, "no output files to recover");
1089 return;
1090 }
1091 /* seek on all files */
1092 nvals = lastout * outvsiz;
1093 lu_doall(&ofiletab, myseeko, &nvals);
1094 /* discard input */
1095 for (nvals = 0; nvals < lastout; nvals++)
1096 if (getinp(oname, fin) <= 0)
1097 error(USER, "unexpected EOF on input");
1098 lastray = lastdone = (unsigned long)lastout;
1099 if (raysleft)
1100 raysleft -= lastray;
1101 }