ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.12
Committed: Fri Jun 3 14:29:42 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.11: +11 -3 lines
Log Message:
Minor optimization to reduce calls to getofile()

File Contents

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