ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.3
Committed: Thu May 26 15:14:42 2005 UTC (18 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.2: +59 -44 lines
Log Message:
Improved efficiency of queuing behavior to avoid idle process time

File Contents

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