ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
(Generate patch)

Comparing ray/src/util/rtcontrib.c (file contents):
Revision 1.1 by greg, Wed May 25 04:45:22 2005 UTC vs.
Revision 1.39 by greg, Fri Oct 21 01:12:59 2005 UTC

# Line 5 | Line 5 | static const char RCSid[] = "$Id$";
5   * Gather rtrace output to compute contributions from particular sources
6   */
7  
8 + #include  "standard.h"
9   #include  <ctype.h>
10 < #include  "rtio.h"
10 < #include  "rterror.h"
10 > #include  <signal.h>
11   #include  "platform.h"
12   #include  "rtprocess.h"
13   #include  "selcall.h"
# Line 16 | Line 16 | static const char RCSid[] = "$Id$";
16   #include  "lookup.h"
17   #include  "calcomp.h"
18  
19 < #ifdef getc_unlocked            /* avoid horrendous overhead of flockfile */
20 < #undef getc
21 < #undef putc
22 < #define getc    getc_unlocked
23 < #define putc    putc_unlocked
24 < #define ferror  ferror_unlocked
19 > #ifndef MAXMODLIST
20 > #define MAXMODLIST      1024            /* maximum modifiers we'll track */
21   #endif
22  
27 #define MAXMODLIST      1024            /* maximum modifiers we'll track */
28
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
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
30 > * if binv is non-zero.  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
# Line 43 | Line 39 | typedef struct {
39          const char      *modname;       /* modifier name */
40          EPNODE          *binv;          /* bin value expression */
41          int             nbins;          /* number of accumulation bins */
42 <        COLOR           cbin[1];        /* contribution bins (extends struct) */
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); }
49 > #define CNT_UNKNOWN     0               /* unknown record length */
50 > #define CNT_PIPE        (-1)            /* output to a pipe */
51 > /*
52 > * The STREAMOUT structure holds an open FILE pointer and a count of
53 > * the number of RGB triplets per record, or CNT_UNKNOWN (0) if
54 > * unknown or CNT_PIPE (-1) if writing to a command.
55 > */
56 > typedef struct {
57 >        FILE            *ofp;           /* output file pointer */
58 >        int             reclen;         /* triplets/record */
59 > } STREAMOUT;
60  
61 < LUTAB   ofiletab = LU_SINIT(free,closefile);    /* output file table */
61 > /* close output stream and free record */
62 > static void
63 > closestream(void *p)
64 > {
65 >        STREAMOUT       *sop = (STREAMOUT *)p;
66 >        int             status;
67 >        if (sop->reclen == CNT_PIPE)
68 >                status = pclose(sop->ofp);
69 >        else
70 >                status = fclose(sop->ofp);
71 >        if (status)
72 >                error(SYSTEM, "error closing output stream");
73 >        free(p);
74 > }
75  
76 < FILE *getofile(const char *ospec, const char *mname, int bn);
76 > LUTAB   ofiletab = LU_SINIT(free,closestream);  /* output file table */
77  
78 + #define OF_MODIFIER     01
79 + #define OF_BIN          02
80 +
81 + STREAMOUT *getostream(const char *ospec, const char *mname, int bn, int noopen);
82 + int ofname(char *oname, const char *ospec, const char *mname, int bn);
83 + void printheader(FILE *fout, const char *info);
84 + void printresolu(FILE *fout);
85 +
86   /*
87   * The rcont structure is used to manage i/o with a particular
88   * rtrace child process.  Input is passed unchanged from stdin,
# Line 66 | Line 92 | FILE *getofile(const char *ospec, const char *mname, i
92   struct rtproc {
93          struct rtproc   *next;          /* next in list of processes */
94          SUBPROC         pd;             /* rtrace pipe descriptors */
95 <        unsigned long   raynum;         /* ray number for this buffer */
96 <        int             bsiz;           /* rtrace buffer length */
97 <        char            *buf;           /* rtrace i/o buffer */
98 <        char            *bpos;          /* current buffer position */
99 < };                              /* rtrace process */
95 >        unsigned long   raynum;         /* ray number for this tree */
96 >        int             bsiz;           /* ray tree buffer length */
97 >        char            *buf;           /* ray tree buffer */
98 >        int             nbr;            /* number of bytes from rtrace */
99 > };                              /* rtrace process buffer */
100  
101                                          /* rtrace command and defaults */
102 < char            *rtargv[256] = { "rtrace", "-dj", ".5", "-dr", "3",
103 <                                "-ab", "1", "-ad", "512", };
102 > char            *rtargv[256+2*MAXMODLIST] = { "rtrace",
103 >                                "-dj", ".5", "-dr", "3",
104 >                                "-ab", "1", "-ad", "128", };
105   int  rtargc = 9;
106                                          /* overriding rtrace options */
107 < char            *myrtopts[] = { "-o-TmWdp", "-h-",
108 <                                "-x", "1", "-y", "0", NULL };
107 > char            *myrtopts[] = { "-o~~TmWdp", "-h-", "-x", "1", "-y", "0",
108 >                                "-dt", "0", "-as", "0", "-aa", "0", NULL };
109  
110   struct rtproc   rt0;                    /* head of rtrace process list */
111  
112   struct rtproc   *rt_unproc = NULL;      /* unprocessed ray trees */
113  
114   char    persistfn[] = "pfXXXXXX";       /* persist file name */
88 char    fmt[8];                         /* rtrace i/o format */
115  
116   int             gargc;                  /* global argc */
117   char            **gargv;                /* global argv */
# Line 97 | Line 123 | int            inpfmt = 'a';           /* input format */
123   int             outfmt = 'a';           /* output format */
124  
125   int             header = 1;             /* output header? */
126 + int             force_open = 0;         /* truncate existing output? */
127   int             xres = 0;               /* horiz. output resolution */
128   int             yres = 0;               /* vert. output resolution */
129  
130 < long            raysleft;               /* number of rays left to trace */
130 > unsigned long   raysleft;               /* number of rays left to trace */
131   long            waitflush;              /* how long until next flush */
132  
133   unsigned long   lastray = 0;            /* last ray number sent */
134   unsigned long   lastdone = 0;           /* last ray processed */
135  
136 + int             using_stdout = 0;       /* are we using stdout? */
137 +
138   const char      *modname[MAXMODLIST];   /* ordered modifier name list */
139   int             nmods = 0;              /* number of modifiers */
140  
141 < MODCONT *addmodifier(char *modn, char *outf, char *binv);
141 > #define queue_length()          (lastray - lastdone)
142  
143 < int done_rprocs(struct rtproc *rtp);
143 > MODCONT *growmodifier(MODCONT *mp, int nb);
144 > MODCONT *addmodifier(char *modn, char *outf, char *binv, int bincnt);
145 > void addmodfile(char *fname, char *outf, char *binv, int bincnt);
146 >
147   void init(int np);
148 < void tracecontribs(FILE *fp);
148 > int done_rprocs(struct rtproc *rtp);
149 > void recover_output(FILE *fin);
150 > void trace_contribs(FILE *fin);
151   struct rtproc *wait_rproc(void);
152   struct rtproc *get_rproc(void);
153 < void process_rays(struct rtproc *rtp);
153 > void queue_raytree(struct rtproc *rtp);
154 > void process_queue(void);
155  
156 < void add_contrib(const char *modn, float rayval[7]);
156 > void put_contrib(const DCOLOR cnt, FILE *fout);
157 > void add_contrib(const char *modn);
158   void done_contrib(void);
159  
160 + /* return number of open rtrace processes */
161 + static int
162 + nrtprocs(void)
163 + {
164 +        int     nrtp = 0;
165 +        struct rtproc   *rtp;
166 +
167 +        for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
168 +                nrtp += rtp->pd.running;
169 +        return(nrtp);
170 + }
171 +
172   /* set input/output format */
173   static void
174   setformat(const char *fmt)
175   {
176          switch (fmt[0]) {
129        case 'a':
177          case 'f':
178          case 'd':
179 +                SET_FILE_BINARY(stdin);
180 +                /* fall through */
181 +        case 'a':
182                  inpfmt = fmt[0];
183                  break;
184          default:
# Line 159 | Line 209 | int
209   main(int argc, char *argv[])
210   {
211          int     nprocs = 1;
212 +        int     recover = 0;
213          char    *curout = NULL;
214          char    *binval = NULL;
215 <        int     i;
216 <                                /* set global argument list */
217 <        gargc = argc;
215 >        int     bincnt = 0;
216 >        char    fmt[8];
217 >        int     i, j;
218 >                                /* need at least one argument */
219 >        if (argc < 2) {
220 >                fprintf(stderr,
221 > "Usage: %s [-n nprocs][-r][-e expr][-f source][-o ospec][-b binv] {-m mod | -M file} [rtrace options] octree\n",
222 >                        argv[0]);
223 >                exit(1);
224 >        }
225 >                                /* global program name */
226          gargv = argv;
227 <                                /* set up calcomp functions */
227 >                                /* initialize calcomp routines */
228          esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
229          esupport &= ~(E_OUTCHAN);
230 +        varset("PI", ':', PI);
231                                  /* get our options */
232 <        for (i = 1; i < argc && argv[i][0] == '-'; i++) {
233 <                switch (argv[i][1]) {
234 <                case 'n':                       /* number of processes */
235 <                        if (argv[i][2] || i >= argc-1) break;
236 <                        nprocs = atoi(argv[++i]);
237 <                        if (nprocs <= 0)
238 <                                error(USER, "illegal number of processes");
239 <                        continue;
240 <                case 'h':                       /* output header? */
241 <                        switch (argv[i][2]) {
242 <                        case '\0':
243 <                                header = !header;
232 >        for (i = 1; i < argc-1; i++) {
233 >                                                /* expand arguments */
234 >                while ((j = expandarg(&argc, &argv, i)) > 0)
235 >                        ;
236 >                if (j < 0) {
237 >                        fprintf(stderr, "%s: cannot expand '%s'",
238 >                                        argv[0], argv[i]);
239 >                        exit(1);
240 >                }
241 >                if (argv[i][0] == '-')
242 >                        switch (argv[i][1]) {
243 >                        case 'r':               /* recover output */
244 >                                if (argv[i][2]) break;
245 >                                recover++;
246                                  continue;
247 <                        case '+': case '1': case 'T': case 't':
248 <                                header = 1;
247 >                        case 'n':               /* number of processes */
248 >                                if (argv[i][2] || i >= argc-2) break;
249 >                                nprocs = atoi(argv[++i]);
250 >                                if (nprocs <= 0)
251 >                                        error(USER, "illegal number of processes");
252                                  continue;
253 <                        case '-': case '0': case 'F': case 'f':
254 <                                header = 0;
253 >                        case 'h':               /* output header? */
254 >                                switch (argv[i][2]) {
255 >                                case '\0':
256 >                                        header = !header;
257 >                                        continue;
258 >                                case '+': case '1':
259 >                                case 'T': case 't':
260 >                                case 'Y': case 'y':
261 >                                        header = 1;
262 >                                        continue;
263 >                                case '-': case '0':
264 >                                case 'F': case 'f':
265 >                                case 'N': case 'n':
266 >                                        header = 0;
267 >                                        continue;
268 >                                }
269 >                                break;
270 >                        case 'f':               /* file or force or format */
271 >                                if (!argv[i][2]) {
272 >                                        char    *fpath;
273 >                                        if (i >= argc-2) break;
274 >                                        fpath = getpath(argv[++i],
275 >                                                        getrlibpath(), R_OK);
276 >                                        if (fpath == NULL) {
277 >                                                sprintf(errmsg,
278 >                                                        "cannot find file '%s'",
279 >                                                                argv[i]);
280 >                                                error(USER, errmsg);
281 >                                        }
282 >                                        fcompile(fpath);
283 >                                        continue;
284 >                                }
285 >                                if (argv[i][2] == 'o') {
286 >                                        force_open++;
287 >                                        continue;
288 >                                }
289 >                                setformat(argv[i]+2);
290                                  continue;
291 <                        }
292 <                        break;
293 <                case 'f':                       /* file or i/o format */
194 <                        if (!argv[i][2]) {
195 <                                if (i >= argc-1) break;
196 <                                fcompile(argv[++i]);
291 >                        case 'e':               /* expression */
292 >                                if (argv[i][2] || i >= argc-2) break;
293 >                                scompile(argv[++i], NULL, 0);
294                                  continue;
295 +                        case 'o':               /* output file spec. */
296 +                                if (argv[i][2] || i >= argc-2) break;
297 +                                curout = argv[++i];
298 +                                continue;
299 +                        case 'x':               /* horiz. output resolution */
300 +                                if (argv[i][2] || i >= argc-2) break;
301 +                                xres = atoi(argv[++i]);
302 +                                continue;
303 +                        case 'y':               /* vert. output resolution */
304 +                                if (argv[i][2] || i >= argc-2) break;
305 +                                yres = atoi(argv[++i]);
306 +                                continue;
307 +                        case 'b':               /* bin expression/count */
308 +                                if (i >= argc-2) break;
309 +                                if (argv[i][2] == 'n') {
310 +                                        bincnt = atoi(argv[++i]);
311 +                                        continue;
312 +                                }
313 +                                if (argv[i][2]) break;
314 +                                binval = argv[++i];
315 +                                continue;
316 +                        case 'm':               /* modifier name */
317 +                                if (argv[i][2] || i >= argc-2) break;
318 +                                rtargv[rtargc++] = "-ti";
319 +                                rtargv[rtargc++] = argv[++i];
320 +                                addmodifier(argv[i], curout, binval, bincnt);
321 +                                continue;
322 +                        case 'M':               /* modifier file */
323 +                                if (argv[i][2] || i >= argc-2) break;
324 +                                rtargv[rtargc++] = "-tI";
325 +                                rtargv[rtargc++] = argv[++i];
326 +                                addmodfile(argv[i], curout, binval, bincnt);
327 +                                continue;
328 +                        case 'P':               /* persist file */
329 +                                error(USER, "persist file is automatic");
330 +                                break;
331                          }
332 <                        setformat(argv[i]+2);
200 <                        continue;
201 <                case 'e':                       /* expression */
202 <                        if (argv[i][2] || i >= argc-1) break;
203 <                        scompile(argv[++i], NULL, 0);
204 <                        continue;
205 <                case 'o':                       /* output file spec. */
206 <                        if (argv[i][2] || i >= argc-1) break;
207 <                        curout = argv[++i];
208 <                        continue;
209 <                case 'x':                       /* horiz. output resolution */
210 <                        if (argv[i][2] || i >= argc-1) break;
211 <                        xres = atoi(argv[++i]);
212 <                        continue;
213 <                case 'y':                       /* vert. output resolution */
214 <                        if (argv[i][2] || i >= argc-1) break;
215 <                        yres = atoi(argv[++i]);
216 <                        continue;
217 <                case 'l':                       /* limit distance? */
218 <                        if (argv[i][2] != 'd') break;
219 <                        rtargv[rtargc++] = argv[i];
220 <                        continue;
221 <                case 'b':                       /* bin expression */
222 <                        if (argv[i][2] || i >= argc-1) break;
223 <                        binval = argv[++i];
224 <                        continue;
225 <                case 'm':                       /* modifier name */
226 <                        if (argv[i][2] || i >= argc-1) break;
227 <                        rtargv[rtargc++] = "-ti";
228 <                        rtargv[rtargc++] = argv[++i];
229 <                        addmodifier(argv[i], curout, binval);
230 <                        continue;
231 <                }
232 <                break;          /* break into rtrace options */
332 >                rtargv[rtargc++] = argv[i];     /* assume rtrace option */
333          }
334 <        for ( ; i < argc; i++)  /* transfer rtrace-specific options */
335 <                rtargv[rtargc++] = argv[i];
236 <        if (!strcmp(rtargv[--rtargc], "-defaults"))
237 <                nprocs = 0;
238 <        if (nprocs > 1) {       /* add persist file if parallel invocation */
239 <                rtargv[rtargc++] = "-PP";
240 <                rtargv[rtargc++] = mktemp(persistfn);
241 <        }
334 >                                /* set global argument list */
335 >        gargc = argc; gargv = argv;
336                                  /* add "mandatory" rtrace settings */
337 <        for (i = 0; myrtopts[i] != NULL; i++)
338 <                rtargv[rtargc++] = myrtopts[i];
339 <        if (!nprocs) {          /* just asking for defaults? */
337 >        for (j = 0; myrtopts[j] != NULL; j++)
338 >                rtargv[rtargc++] = myrtopts[j];
339 >                                /* just asking for defaults? */
340 >        if (!strcmp(argv[i], "-defaults")) {
341                  char    sxres[16], syres[16];
342                  char    *rtpath;
343 <                printf("-n  1\t\t\t\t# number of processes\n", nprocs);
343 >                printf("-n  %-2d\t\t\t\t# number of processes\n", nprocs);
344                  fflush(stdout);                 /* report OUR options */
345                  rtargv[rtargc++] = header ? "-h+" : "-h-";
346                  sprintf(fmt, "-f%c%c", inpfmt, outfmt);
# Line 256 | Line 351 | main(int argc, char *argv[])
351                  rtargv[rtargc++] = "-y";
352                  sprintf(syres, "%d", yres);
353                  rtargv[rtargc++] = syres;
354 <                rtargv[rtargc++] = "-oW";
354 >                rtargv[rtargc++] = "-oTW";
355                  rtargv[rtargc++] = "-defaults";
356                  rtargv[rtargc] = NULL;
357                  rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
# Line 269 | Line 364 | main(int argc, char *argv[])
364                  perror(rtpath); /* execv() should not return */
365                  exit(1);
366          }
367 <        if (!nmods)
368 <                error(USER, "No modifiers specified");
369 <        if (argc < 2 || argv[argc-1][0] == '-')
370 <                error(USER, "missing octree argument");
367 >        if (nprocs > 1) {       /* add persist file if parallel */
368 >                rtargv[rtargc++] = "-PP";
369 >                rtargv[rtargc++] = mktemp(persistfn);
370 >        }
371                                  /* add format string */
372          sprintf(fmt, "-f%cf", inpfmt);
373          rtargv[rtargc++] = fmt;
374                                  /* octree argument is last */
375 <        rtargv[rtargc++] = octree = argv[argc-1];
375 >        if (i <= 0 || i != argc-1 || argv[i][0] == '-')
376 >                error(USER, "missing octree argument");
377 >        rtargv[rtargc++] = octree = argv[i];
378          rtargv[rtargc] = NULL;
379 <                                /* start rtrace & sum contributions */
379 >                                /* start rtrace */
380          init(nprocs);
381 <        tracecontribs(stdin);
381 >        if (recover)            /* perform recovery if requested */
382 >                recover_output(stdin);
383 >        trace_contribs(stdin);  /* compute contributions */
384          quit(0);
385   }
386  
387 + #ifndef SIGALRM
388 + #define SIGALRM SIGTERM
389 + #endif
390   /* kill persistent rtrace process */
391   static void
392   killpersist(void)
393   {
394          FILE    *fp = fopen(persistfn, "r");
395 <        int     pid;
395 >        RT_PID  pid;
396  
397          if (fp == NULL)
398                  return;
# Line 333 | Line 435 | quit(int status)
435          exit(status);                   /* flushes all output streams */
436   }
437  
438 < /* start rtrace and initialize buffers */
438 > /* start rtrace processes and initialize */
439   void
440   init(int np)
441   {
442          struct rtproc   *rtp;
443          int     i;
444          int     maxbytes;
445 +                                        /* make sure we have something to do */
446 +        if (!nmods)
447 +                error(USER, "No modifiers specified");
448                                          /* assign ray variables */
449          scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
450          scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
451                                          /* set up signal handling */
452 < #ifdef SIGPIPE /* not present on Windows */
452 >        signal(SIGINT, quit);
453 > #ifdef SIGHUP
454 >        signal(SIGHUP, quit);
455 > #endif
456 > #ifdef SIGTERM
457 >        signal(SIGTERM, quit);
458 > #endif
459 > #ifdef SIGPIPE
460          signal(SIGPIPE, quit);
461   #endif
462          rtp = &rt0;                     /* start rtrace process(es) */
# Line 360 | Line 472 | init(int np)
472                          error(SYSTEM, "cannot start rtrace process");
473                  if (maxbytes > treebufsiz)
474                          treebufsiz = maxbytes;
475 +                rtp->raynum = 0;
476                  rtp->bsiz = 0;
477                  rtp->buf = NULL;
478 <                rtp->raynum = 0;
478 >                rtp->nbr = 0;
479                  if (i == np)            /* last process? */
480                          break;
481                  if (i == 1)
# Line 375 | Line 488 | init(int np)
488          rtp->next = NULL;               /* terminate list */
489          if (yres > 0) {
490                  if (xres > 0)
491 <                        raysleft = xres*yres;
491 >                        raysleft = (unsigned long)xres*yres;
492                  else
493                          raysleft = yres;
494          } else
# Line 383 | Line 496 | init(int np)
496          waitflush = xres;
497   }
498  
499 + /* grow modifier to accommodate more bins */
500 + MODCONT *
501 + growmodifier(MODCONT *mp, int nb)
502 + {
503 +        if (nb <= mp->nbins)
504 +                return mp;
505 +        mp = (MODCONT *)realloc(mp, sizeof(MODCONT) + sizeof(DCOLOR)*(nb-1));
506 +        if (mp == NULL)
507 +                error(SYSTEM, "out of memory in growmodifier");
508 +        memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(nb-mp->nbins));
509 +        mp->nbins = nb;
510 +        return mp;
511 + }
512 +
513   /* add modifier to our list to track */
514   MODCONT *
515 < addmodifier(char *modn, char *outf, char *binv)
515 > addmodifier(char *modn, char *outf, char *binv, int bincnt)
516   {
517          LUENT   *lep = lu_find(&modconttab, modn);
518          MODCONT *mp;
519 +        int     i;
520          
521          if (lep->data != NULL) {
522                  sprintf(errmsg, "duplicate modifier '%s'", modn);
# Line 401 | Line 529 | addmodifier(char *modn, char *outf, char *binv)
529          mp = (MODCONT *)malloc(sizeof(MODCONT));
530          if (mp == NULL)
531                  error(SYSTEM, "out of memory in addmodifier");
404        lep->data = (char *)mp;
532          mp->outspec = outf;             /* XXX assumes static string */
533          mp->modname = modn;             /* XXX assumes static string */
534          if (binv != NULL)
# Line 410 | Line 537 | addmodifier(char *modn, char *outf, char *binv)
537                  mp->binv = eparse("0");
538          mp->nbins = 1;
539          setcolor(mp->cbin[0], 0., 0., 0.);
540 +        if (mp->binv->type == NUM)      /* assume one bin if constant */
541 +                bincnt = 1;
542 +        else if (bincnt > 1)
543 +                mp = growmodifier(mp, bincnt);
544 +        lep->data = (char *)mp;
545 +                                        /* allocate output streams */
546 +        for (i = outf==NULL || outf[0]=='!' ? 0 : bincnt; i--; )
547 +                getostream(mp->outspec, mp->modname, i, 1);
548          return mp;
549   }
550  
551 + /* add modifiers from a file list */
552 + void
553 + addmodfile(char *fname, char *outf, char *binv, int bincnt)
554 + {
555 +        char    *mname[MAXMODLIST];
556 +        int     i;
557 +                                        /* find the file & store strings */
558 +        if (wordfile(mname, getpath(fname, getrlibpath(), R_OK)) < 0) {
559 +                sprintf(errmsg, "cannot find modifier file '%s'", fname);
560 +                error(SYSTEM, errmsg);
561 +        }
562 +        for (i = 0; mname[i]; i++)      /* add each one */
563 +                addmodifier(mname[i], outf, binv, bincnt);
564 + }
565 +
566   /* put string to stderr */
567   void
568   eputs(char  *s)
# Line 428 | Line 578 | eputs(char  *s)
578          midline = s[strlen(s)-1] != '\n';
579   }
580  
581 + /* construct output file name and return flags whether modifier/bin present */
582 + int
583 + ofname(char *oname, const char *ospec, const char *mname, int bn)
584 + {
585 +        const char      *mnp = NULL;
586 +        const char      *bnp = NULL;
587 +        const char      *cp;
588 +        
589 +        if (ospec == NULL)
590 +                return -1;
591 +        for (cp = ospec; *cp; cp++)             /* check format position(s) */
592 +                if (*cp == '%') {
593 +                        do
594 +                                ++cp;
595 +                        while (isdigit(*cp));
596 +                        switch (*cp) {
597 +                        case '%':
598 +                                break;
599 +                        case 's':
600 +                                if (mnp != NULL)
601 +                                        return -1;
602 +                                mnp = cp;
603 +                                break;
604 +                        case 'd':
605 +                                if (bnp != NULL)
606 +                                        return -1;
607 +                                bnp = cp;
608 +                                break;
609 +                        default:
610 +                                return -1;
611 +                        }
612 +                }
613 +        if (mnp != NULL) {                      /* create file name */
614 +                if (bnp != NULL) {
615 +                        if (bnp > mnp)
616 +                                sprintf(oname, ospec, mname, bn);
617 +                        else
618 +                                sprintf(oname, ospec, bn, mname);
619 +                        return OF_MODIFIER|OF_BIN;
620 +                }
621 +                sprintf(oname, ospec, mname);
622 +                return OF_MODIFIER;
623 +        }
624 +        if (bnp != NULL) {
625 +                sprintf(oname, ospec, bn);
626 +                return OF_BIN;
627 +        }
628 +        strcpy(oname, ospec);
629 +        return 0;
630 + }
631 +
632   /* write header to the given output stream */
633   void
634 < printheader(FILE *fout)
634 > printheader(FILE *fout, const char *info)
635   {
636          extern char     VersionID[];
637          FILE            *fin = fopen(octree, "r");
638          
639          if (fin == NULL)
640                  quit(1);
641 <        getheader(fin, (gethfunc *)fputs, fout);        /* copy octree header */
641 >        checkheader(fin, "ignore", fout);       /* copy octree header */
642          fclose(fin);
643          printargs(gargc-1, gargv, fout);        /* add our command */
644          fprintf(fout, "SOFTWARE= %s\n", VersionID);
645          fputnow(fout);
646 +        if (info != NULL)                       /* add extra info if given */
647 +                fputs(info, fout);
648          switch (outfmt) {                       /* add output format */
649          case 'a':
650                  fputformat("ascii", fout);
# Line 457 | Line 660 | printheader(FILE *fout)
660                  break;
661          }
662          fputc('\n', fout);
663 + }
664 +
665 + /* write resolution string to given output stream */
666 + void
667 + printresolu(FILE *fout)
668 + {
669          if (xres > 0) {
670                  if (yres > 0)                   /* resolution string */
671                          fprtresolu(xres, yres, fout);
# Line 464 | Line 673 | printheader(FILE *fout)
673          }
674   }
675  
676 < /* Get output file pointer (open and write header if new) */
677 < FILE *
678 < getofile(const char *ospec, const char *mname, int bn)
676 > /* Get output stream pointer (open and write header if new and noopen==0) */
677 > STREAMOUT *
678 > getostream(const char *ospec, const char *mname, int bn, int noopen)
679   {
680 <        static int      using_stdout = 0;
681 <        const char      *mnp = NULL;
682 <        const char      *bnp = NULL;
683 <        const char      *cp;
684 <        char            ofname[1024];
476 <        LUENT           *lep;
680 >        static STREAMOUT        stdos;
681 >        int                     ofl;
682 >        char                    oname[1024];
683 >        LUENT                   *lep;
684 >        STREAMOUT               *sop;
685          
686          if (ospec == NULL) {                    /* use stdout? */
687 <                if (!using_stdout && header)
688 <                        printheader(stdout);
689 <                using_stdout = 1;
690 <                return stdout;
691 <        }
692 <        for (cp = ospec; *cp; cp++)             /* check format position(s) */
693 <                if (*cp == '%') {
694 <                        do
487 <                                ++cp;
488 <                        while (isdigit(*cp));
489 <                        switch (*cp) {
490 <                        case '%':
491 <                                break;
492 <                        case 's':
493 <                                if (mnp != NULL)
494 <                                        goto badspec;
495 <                                mnp = cp;
496 <                                break;
497 <                        case 'd':
498 <                                if (bnp != NULL)
499 <                                        goto badspec;
500 <                                bnp = cp;
501 <                                break;
502 <                        default:
503 <                                goto badspec;
504 <                        }
687 >                if (!noopen && !using_stdout) {
688 >                        stdos.reclen = 0;
689 >                        if (outfmt != 'a')
690 >                                SET_FILE_BINARY(stdout);
691 >                        if (header)
692 >                                printheader(stdout, NULL);
693 >                        printresolu(stdout);
694 >                        using_stdout = 1;
695                  }
696 <        if (mnp != NULL) {                      /* create file name */
697 <                if (bnp != NULL) {
698 <                        if (bnp > mnp)
699 <                                sprintf(ofname, ospec, mname, bn);
700 <                        else
701 <                                sprintf(ofname, ospec, bn, mname);
702 <                } else
703 <                        sprintf(ofname, ospec, mname);
704 <        } else if (bnp != NULL)
705 <                sprintf(ofname, ospec, bn);
516 <        else
517 <                strcpy(ofname, ospec);
518 <        lep = lu_find(&ofiletab, ofname);       /* look it up */
696 >                stdos.ofp = stdout;
697 >                stdos.reclen += noopen;
698 >                return &stdos;
699 >        }
700 >        ofl = ofname(oname, ospec, mname, bn);  /* get output name */
701 >        if (ofl < 0) {
702 >                sprintf(errmsg, "bad output format '%s'", ospec);
703 >                error(USER, errmsg);
704 >        }
705 >        lep = lu_find(&ofiletab, oname);        /* look it up */
706          if (lep->key == NULL)                   /* new entry */
707 <                lep->key = strcpy((char *)malloc(strlen(ofname)+1), ofname);
708 <        if (lep->data == NULL) {                /* open output file */
709 <                lep->data = (char *)fopen(ofname, "w");
710 <                if (lep->data == NULL) {
711 <                        sprintf(errmsg, "cannot open '%s' for writing", ofname);
707 >                lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
708 >        sop = (STREAMOUT *)lep->data;
709 >        if (sop == NULL) {                      /* allocate stream */
710 >                sop = (STREAMOUT *)malloc(sizeof(STREAMOUT));
711 >                if (sop == NULL)
712 >                        error(SYSTEM, "out of memory in getostream");
713 >                sop->reclen = oname[0] == '!' ? CNT_PIPE : CNT_UNKNOWN;
714 >                sop->ofp = NULL;                /* open iff noopen==0 */
715 >                lep->data = (char *)sop;
716 >        }
717 >        if (!noopen && sop->ofp == NULL) {      /* open output stream */
718 >                long            i;
719 >                if (oname[0] == '!')            /* output to command */
720 >                        sop->ofp = popen(oname+1, "w");
721 >                else if (!force_open && access(oname, F_OK) == 0)
722 >                        errno = EEXIST;         /* file exists */
723 >                else                            /* else open it */
724 >                        sop->ofp = fopen(oname, "w");
725 >                if (sop->ofp == NULL) {
726 >                        sprintf(errmsg, "cannot open '%s' for writing", oname);
727                          error(SYSTEM, errmsg);
728                  }
729 <                if (header)
730 <                        printheader((FILE *)lep->data);
729 >                if (outfmt != 'a')
730 >                        SET_FILE_BINARY(sop->ofp);
731 >                if (header) {
732 >                        char    info[512];
733 >                        char    *cp = info;
734 >                        if (ofl & OF_MODIFIER || sop->reclen == 1) {
735 >                                sprintf(cp, "MODIFIER=%s\n", mname);
736 >                                while (*cp) ++cp;
737 >                        }
738 >                        if (ofl & OF_BIN) {
739 >                                sprintf(cp, "BIN=%d\n", bn);
740 >                                while (*cp) ++cp;
741 >                        }
742 >                        *cp = '\0';
743 >                        printheader(sop->ofp, info);
744 >                }
745 >                printresolu(sop->ofp);
746 >                                                /* play catch-up */
747 >                for (i = sop->reclen > 1 ? sop->reclen*lastdone : lastdone;
748 >                                                                i--; ) {
749 >                        static const DCOLOR     nocontrib = BLKCOLOR;
750 >                        put_contrib(nocontrib, sop->ofp);
751 >                        if (outfmt == 'a')
752 >                                putc('\n', sop->ofp);
753 >                }
754 >                if (xres > 0)
755 >                        fflush(sop->ofp);
756          }
757 <        return (FILE *)lep->data;               /* return open file pointer */
758 < badspec:
759 <        sprintf(errmsg, "bad output format '%s'", ospec);
533 <        error(USER, errmsg);
534 <        return NULL;            /* pro forma return */
757 >        if (sop->reclen != CNT_PIPE)            /* add to length if noopen */
758 >                sop->reclen += noopen;
759 >        return sop;                             /* return open stream */
760   }
761  
762   /* read input ray into buffer */
763   int
764   getinp(char *buf, FILE *fp)
765   {
766 +        double  dv[3];
767 +        float   fv[3];
768 +        char    *cp;
769 +        int     i;
770 +
771          switch (inpfmt) {
772          case 'a':
773 <                if (fgets(buf, 128, fp) == NULL)
774 <                        return 0;
773 >                cp = buf;               /* make sure we get 6 floats */
774 >                for (i = 0; i < 6; i++) {
775 >                        if (fgetword(cp, buf+127-cp, fp) == NULL)
776 >                                return -1;
777 >                        if (i >= 3)
778 >                                dv[i-3] = atof(cp);
779 >                        if ((cp = fskip(cp)) == NULL || *cp)
780 >                                return -1;
781 >                        *cp++ = ' ';
782 >                }
783 >                getc(fp);               /* get/put eol */
784 >                *cp-- = '\0'; *cp = '\n';
785 >                if (DOT(dv,dv) <= FTINY*FTINY)
786 >                        return 0;       /* dummy ray */
787                  return strlen(buf);
788          case 'f':
789                  if (fread(buf, sizeof(float), 6, fp) < 6)
790 <                        return 0;
790 >                        return -1;
791 >                memcpy(fv, buf+3*sizeof(float), 3*sizeof(float));
792 >                if (DOT(fv,fv) <= FTINY*FTINY)
793 >                        return 0;       /* dummy ray */
794                  return sizeof(float)*6;
795          case 'd':
796                  if (fread(buf, sizeof(double), 6, fp) < 6)
797 <                        return 0;
797 >                        return -1;
798 >                memcpy(dv, buf+3*sizeof(double), 3*sizeof(double));
799 >                if (DOT(dv,dv) <= FTINY*FTINY)
800 >                        return 0;       /* dummy ray */
801                  return sizeof(double)*6;
802          }
803          error(INTERNAL, "botched input format");
804 <        return 0;       /* pro forma return */
804 >        return -1;      /* pro forma return */
805   }
806  
807 < static const float      *rparams = NULL;        /* ray parameter pointer */
807 > static float    rparams[9];             /* traced ray parameters */
808  
809   /* return channel (ray) value */
810   double
# Line 564 | Line 812 | chanvalue(int n)
812   {
813          if (--n < 0 || n >= 6)
814                  error(USER, "illegal channel number ($N)");
815 <        if (rparams == NULL)
568 <                error(USER, "illegal use of $N in constant expression");
569 <        return rparams[n];
815 >        return rparams[n+3];
816   }
817  
818 < /* add ray contribution to the appropriate modifier bin */
818 > /* add current ray contribution to the appropriate modifier bin */
819   void
820 < add_contrib(const char *modn, float rayval[9])
820 > add_contrib(const char *modn)
821   {
822          LUENT   *le = lu_find(&modconttab, modn);
823          MODCONT *mp = (MODCONT *)le->data;
# Line 581 | Line 827 | add_contrib(const char *modn, float rayval[9])
827                  sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
828                  error(USER, errmsg);
829          }
830 <        rparams = rayval + 3;           /* for chanvalue */
585 <        eclock++;
830 >        eclock++;                       /* get bin number */
831          bn = (int)(evalue(mp->binv) + .5);
832          if (bn <= 0)
833                  bn = 0;
834 <        else if (bn > mp->nbins) {      /* new bin */
835 <                mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
836 <                                                bn*sizeof(COLOR));
592 <                if (mp == NULL)
593 <                        error(SYSTEM, "out of memory in add_contrib");
594 <                memset(mp->cbin+mp->nbins, 0, sizeof(COLOR)*(bn+1-mp->nbins));
595 <                mp->nbins = bn+1;
596 <                le->data = (char *)mp;
597 <        }
598 <        addcolor(mp->cbin[bn], rayval);
599 <        rparams = NULL;
834 >        else if (bn >= mp->nbins)       /* new bin */
835 >                le->data = (char *)(mp = growmodifier(mp, bn+1));
836 >        addcolor(mp->cbin[bn], rparams);
837   }
838  
839   /* output newline to ASCII file and/or flush as requested */
840   static int
841   puteol(const LUENT *e, void *p)
842   {
843 <        FILE    *fp = (FILE *)e->data;
843 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
844  
845          if (outfmt == 'a')
846 <                putc('\n', fp);
846 >                putc('\n', sop->ofp);
847          if (!waitflush)
848 <                fflush(fp);
849 <        if (ferror(fp)) {
848 >                fflush(sop->ofp);
849 >        if (ferror(sop->ofp)) {
850                  sprintf(errmsg, "write error on file '%s'", e->key);
851                  error(SYSTEM, errmsg);
852          }
853          return 0;
854   }
855  
856 + /* put out ray contribution to file */
857 + void
858 + put_contrib(const DCOLOR cnt, FILE *fout)
859 + {
860 +        float   fv[3];
861 +        COLR    cv;
862 +
863 +        switch (outfmt) {
864 +        case 'a':
865 +                fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
866 +                break;
867 +        case 'f':
868 +                fv[0] = cnt[0];
869 +                fv[1] = cnt[1];
870 +                fv[2] = cnt[2];
871 +                fwrite(fv, sizeof(float), 3, fout);
872 +                break;
873 +        case 'd':
874 +                fwrite(cnt, sizeof(double), 3, fout);
875 +                break;
876 +        case 'c':
877 +                setcolr(cv, cnt[0], cnt[1], cnt[2]);
878 +                fwrite(cv, sizeof(cv), 1, fout);
879 +                break;
880 +        default:
881 +                error(INTERNAL, "botched output format");
882 +        }
883 + }
884 +
885   /* output ray tallies and clear for next primary */
886   void
887   done_contrib(void)
888   {
889 <        int     i, j;
890 <        MODCONT *mp;
891 <        FILE    *fout;
626 <        double  dv[3];
627 <        COLR    cv;
889 >        int             i, j;
890 >        MODCONT         *mp;
891 >        STREAMOUT       *sop;
892                                                  /* output modifiers in order */
893          for (i = 0; i < nmods; i++) {
894                  mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
895 <                for (j = 0; j < mp->nbins; j++) {
896 <                        fout = getofile(mp->outspec, mp->modname, j);
897 <                        switch (outfmt) {
898 <                        case 'a':
899 <                                fprintf(fout, "%.6e\t%.6e\t%.6e\t",
900 <                                                mp->cbin[j][RED],
901 <                                                mp->cbin[j][GRN],
902 <                                                mp->cbin[j][BLU]);
903 <                                break;
904 <                        case 'f':
641 <                                fwrite(mp->cbin[j], sizeof(float), 3, fout);
642 <                                break;
643 <                        case 'd':
644 <                                dv[0] = mp->cbin[j][0];
645 <                                dv[1] = mp->cbin[j][1];
646 <                                dv[2] = mp->cbin[j][2];
647 <                                fwrite(dv, sizeof(double), 3, fout);
648 <                                break;
649 <                        case 'c':
650 <                                setcolr(cv, mp->cbin[j][RED],
651 <                                        mp->cbin[j][GRN], mp->cbin[j][BLU]);
652 <                                fwrite(cv, sizeof(COLR), 1, fout);
653 <                                break;
654 <                        default:
655 <                                error(INTERNAL, "botched output format");
656 <                        }
657 <                }
895 >                sop = getostream(mp->outspec, mp->modname, 0,0);
896 >                put_contrib(mp->cbin[0], sop->ofp);
897 >                if (mp->nbins > 3 &&            /* minor optimization */
898 >                                sop == getostream(mp->outspec, mp->modname, 1,0))
899 >                        for (j = 1; j < mp->nbins; j++)
900 >                                put_contrib(mp->cbin[j], sop->ofp);
901 >                else
902 >                        for (j = 1; j < mp->nbins; j++)
903 >                                put_contrib(mp->cbin[j],
904 >                                    getostream(mp->outspec,mp->modname,j,0)->ofp);
905                                                  /* clear for next ray tree */
906 <                memset(mp->cbin, 0, sizeof(COLOR)*mp->nbins);
906 >                memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
907          }
908          --waitflush;                            /* terminate records */
909          lu_doall(&ofiletab, puteol, NULL);
910 <        if (!waitflush)
910 >        if (using_stdout & (outfmt == 'a'))
911 >                putc('\n', stdout);
912 >        if (!waitflush) {
913                  waitflush = xres;
914 +                if (using_stdout)
915 +                        fflush(stdout);
916 +        }
917   }
918  
919 < /* process (or save) ray tree produced by rtrace process */
919 > /* queue completed ray tree produced by rtrace process */
920   void
921 < process_rays(struct rtproc *rtp)
921 > queue_raytree(struct rtproc *rtp)
922   {
923 <        struct rtproc   *rtu;
924 <                                        /* check if time to process it */
925 <        if (rtp->raynum == lastdone+1) {
926 <                int             n = rtp->bpos - rtp->buf;
923 >        struct rtproc   *rtu, *rtl = NULL;
924 >                                        /* insert following ray order */
925 >        for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
926 >                if (rtp->raynum < rtu->raynum)
927 >                        break;
928 >        rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
929 >        if (rtu == NULL)
930 >                error(SYSTEM, "out of memory in queue_raytree");
931 >        *rtu = *rtp;
932 >        if (rtl == NULL) {
933 >                rtu->next = rt_unproc;
934 >                rt_unproc = rtu;
935 >        } else {
936 >                rtu->next = rtl->next;
937 >                rtl->next = rtu;
938 >        }
939 >        rtp->raynum = 0;                /* clear path for next ray tree */
940 >        rtp->bsiz = 0;
941 >        rtp->buf = NULL;
942 >        rtp->nbr = 0;
943 > }
944 >
945 > /* process completed ray trees from our queue */
946 > void
947 > process_queue(void)
948 > {
949 >        char    modname[128];
950 >                                        /* ray-ordered queue */
951 >        while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
952 >                struct rtproc   *rtp = rt_unproc;
953 >                int             n = rtp->nbr;
954                  const char      *cp = rtp->buf;
955                  while (n > 0) {         /* process rays */
956 <                        char    matname[128];
678 <                        char    *mnp = matname;
956 >                        register char   *mnp = modname;
957                                          /* skip leading tabs */
958                          while (n > 0 && *cp == '\t') {
959                                  cp++; n--;
960                          }
961 <                                        /* get material name */
961 >                        if (!n || !(isalpha(*cp) | (*cp == '_')))
962 >                                error(USER, "bad modifier name from rtrace");
963 >                                        /* get modifier name */
964                          while (n > 0 && *cp != '\t') {
965                                  *mnp++ = *cp++; n--;
966                          }
687                        if (!n)
688                                error(USER, "botched modifer name from rtrace");
967                          *mnp = '\0';
968 <                        cp++; n--;      /* skip terminating tab */
968 >                        cp++; n--;      /* eat following tab */
969                          if (n < (int)(sizeof(float)*9))
970                                  error(USER, "incomplete ray value from rtrace");
971                                          /* add ray contribution */
972 <                        add_contrib(matname, (float *)cp);
972 >                        memcpy(rparams, cp, sizeof(float)*9);
973                          cp += sizeof(float)*9; n -= sizeof(float)*9;
974 +                        add_contrib(modname);
975                  }
976                  done_contrib();         /* sum up contributions & output */
977                  lastdone = rtp->raynum;
978 <                free(rtp->buf);
979 <                                        /* catch up with unprocessed list */
980 <                while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
981 <                        process_rays(rt_unproc);
703 <                        rt_unproc = (rtu=rt_unproc)->next;
704 <                        free(rtu);
705 <                }
706 <        } else {                        /* else insert in unprocessed list */
707 <                struct rtproc   *rtl = NULL;
708 <                for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
709 <                        if (rtp->raynum < rtu->raynum)
710 <                                break;
711 <                rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
712 <                if (rtu == NULL)
713 <                        error(SYSTEM, "out of memory in process_rays");
714 <                *rtu = *rtp;
715 <                if (rtl == NULL) {
716 <                        rtu->next = rt_unproc;
717 <                        rt_unproc = rtu;
718 <                } else {
719 <                        rtu->next = rtl->next;
720 <                        rtl->next = rtu;
721 <                }
978 >                if (rtp->buf != NULL)   /* free up buffer space */
979 >                        free(rtp->buf);
980 >                rt_unproc = rtp->next;
981 >                free(rtp);              /* done with this ray tree */
982          }
723        rtp->raynum = 0;                /* clear path for next ray tree */
724        rtp->bsiz = 0;
725        rtp->buf = NULL;
983   }
984  
985   /* wait for rtrace process to finish with ray tree */
# Line 763 | Line 1020 | wait_rproc(void)
1020                          if (rt->buf == NULL) {
1021                                  rt->bsiz = treebufsiz;
1022                                  rt->buf = (char *)malloc(treebufsiz);
1023 <                        } else if (rt->bpos + BUFSIZ > rt->buf + rt->bsiz) {
1023 >                        } else if (rt->nbr + BUFSIZ > rt->bsiz) {
1024                                  if (rt->bsiz + BUFSIZ <= treebufsiz)
1025                                          rt->bsiz = treebufsiz;
1026                                  else
1027 <                                        rt->bsiz = treebufsiz += BUFSIZ;
1027 >                                        treebufsiz = rt->bsiz += BUFSIZ;
1028                                  rt->buf = (char *)realloc(rt->buf, rt->bsiz);
1029                          }
1030                          if (rt->buf == NULL)
1031                                  error(SYSTEM, "out of memory in wait_rproc");
1032 <                        nr = read(rt->pd.r, rt->bpos,
1033 <                                        rt->buf + rt->bsiz - rt->bpos);
777 <                        if (!nr)
1032 >                        nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
1033 >                        if (nr <= 0)
1034                                  error(USER, "rtrace process died");
1035 <                        rt->bpos += nr;         /* advance buffer & check */
1036 <                        if (rt->bpos[-1] == '\t' && rt->bpos[-2] == '-') {
1037 <                                rt->bpos -= 2;  /* elide terminator */
1038 <                                process_rays(rt);
1035 >                        rt->nbr += nr;          /* advance & check */
1036 >                        if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
1037 >                                                        "~\t~\t", 4)) {
1038 >                                rt->nbr -= 4;   /* elide terminator */
1039 >                                queue_raytree(rt);
1040                                  rtfree = rt;    /* ready for next ray */
1041                          }
1042                  }
# Line 801 | Line 1058 | get_rproc(void)
1058  
1059   /* trace ray contributions (main loop) */
1060   void
1061 < tracecontribs(FILE *fin)
1061 > trace_contribs(FILE *fin)
1062   {
1063          char            inpbuf[128];
1064          int             iblen;
1065          struct rtproc   *rtp;
1066                                                  /* loop over input */
1067 <        while ((iblen = getinp(inpbuf, fin)) > 0) {
1068 <                if (lastray+1 < lastray) {      /* counter rollover? */
1067 >        while ((iblen = getinp(inpbuf, fin)) >= 0) {
1068 >                if (!iblen ||                   /* need reset? */
1069 >                                queue_length() > 10*nrtprocs() ||
1070 >                                lastray+1 < lastray) {
1071                          while (wait_rproc() != NULL)
1072 <                                ;
1073 <                        lastdone = lastray = 0;
1072 >                                process_queue();
1073 >                        if (lastray+1 < lastray)
1074 >                                lastdone = lastray = 0;
1075                  }
1076                  rtp = get_rproc();              /* get avail. rtrace process */
1077 <                rtp->raynum = ++lastray;        /* assign this ray to it */
1078 <                writebuf(rtp->pd.w, inpbuf, iblen);
1079 <                if (!--raysleft)
1080 <                        break;                  /* explicit EOF */
1077 >                rtp->raynum = ++lastray;        /* assign ray */
1078 >                if (iblen) {                    /* trace ray if valid */
1079 >                        writebuf(rtp->pd.w, inpbuf, iblen);
1080 >                } else {                        /* else bypass dummy ray */
1081 >                        queue_raytree(rtp);     /* empty tree */
1082 >                        if ((yres <= 0) | (waitflush > 1))
1083 >                                waitflush = 1;  /* flush after this */
1084 >                }
1085 >                process_queue();                /* catch up with results */
1086 >                if (raysleft && !--raysleft)
1087 >                        break;                  /* preemptive EOI */
1088          }
1089          while (wait_rproc() != NULL)            /* process outstanding rays */
1090 <                ;
1090 >                process_queue();
1091 >        if (raysleft)
1092 >                error(USER, "unexpected EOF on input");
1093 >        lu_done(&ofiletab);                     /* close output files */
1094 > }
1095 >
1096 > /* seek on the given output file */
1097 > static int
1098 > myseeko(const LUENT *e, void *p)
1099 > {
1100 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1101 >        off_t           nbytes = *(off_t *)p;
1102 >        
1103 >        if (sop->reclen > 1)
1104 >                nbytes = nbytes * sop->reclen;
1105 >        if (fseeko(sop->ofp, nbytes, SEEK_CUR) < 0) {
1106 >                sprintf(errmsg, "seek error on file '%s'", e->key);
1107 >                error(SYSTEM, errmsg);
1108 >        }
1109 > }
1110 >
1111 > /* recover output if possible */
1112 > void
1113 > recover_output(FILE *fin)
1114 > {
1115 >        off_t           lastout = -1;
1116 >        int             outvsiz, recsiz;
1117 >        char            *outvfmt;
1118 >        int             i, j;
1119 >        MODCONT         *mp;
1120 >        int             ofl;
1121 >        char            oname[1024];
1122 >        LUENT           *ment, *oent;
1123 >        STREAMOUT       sout;
1124 >        off_t           nvals;
1125 >        int             xr, yr;
1126 >
1127 >        switch (outfmt) {
1128 >        case 'a':
1129 >                error(USER, "cannot recover ASCII output");
1130 >                return;
1131 >        case 'f':
1132 >                outvsiz = sizeof(float)*3;
1133 >                outvfmt = "float";
1134 >                break;
1135 >        case 'd':
1136 >                outvsiz = sizeof(double)*3;
1137 >                outvfmt = "double";
1138 >                break;
1139 >        case 'c':
1140 >                outvsiz = sizeof(COLR);
1141 >                outvfmt = COLRFMT;
1142 >                break;
1143 >        default:
1144 >                error(INTERNAL, "botched output format");
1145 >                return;
1146 >        }
1147 >                                                /* check modifier outputs */
1148 >        for (i = 0; i < nmods; i++) {
1149 >                ment = lu_find(&modconttab,modname[i]);
1150 >                mp = (MODCONT *)ment->data;
1151 >                if (mp->outspec == NULL)
1152 >                        error(USER, "cannot recover from stdout");
1153 >                if (mp->outspec[0] == '!')
1154 >                        error(USER, "cannot recover from command");
1155 >                for (j = 0; ; j++) {            /* check each bin's file */
1156 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1157 >                        if (ofl < 0)
1158 >                                error(USER, "bad output file specification");
1159 >                        oent = lu_find(&ofiletab, oname);
1160 >                        if (oent->data != NULL) {
1161 >                                sout = *(STREAMOUT *)oent->data;
1162 >                        } else {
1163 >                                sout.reclen = CNT_UNKNOWN;
1164 >                                sout.ofp = NULL;
1165 >                        }
1166 >                        if (sout.ofp != NULL) { /* already open? */
1167 >                                if (ofl & OF_BIN)
1168 >                                        continue;
1169 >                                break;
1170 >                        }
1171 >                                                /* open output */
1172 >                        sout.ofp = fopen(oname, "rb+");
1173 >                        if (sout.ofp == NULL) {
1174 >                                if (j)
1175 >                                        break;  /* assume end of modifier */
1176 >                                sprintf(errmsg, "missing recover file '%s'",
1177 >                                                oname);
1178 >                                error(USER, errmsg);
1179 >                        }
1180 >                        nvals = lseek(fileno(sout.ofp), 0, SEEK_END);
1181 >                        if (nvals <= 0) {
1182 >                                lastout = 0;    /* empty output, quit here */
1183 >                                fclose(sout.ofp);
1184 >                                break;
1185 >                        }
1186 >                        if (sout.reclen == CNT_UNKNOWN) {
1187 >                                if (!(ofl & OF_BIN)) {
1188 >                                        sprintf(errmsg,
1189 >                                                "need -bn to recover file '%s'",
1190 >                                                        oname);
1191 >                                        error(USER, errmsg);
1192 >                                }
1193 >                                recsiz = outvsiz;
1194 >                        } else
1195 >                                recsiz = outvsiz * sout.reclen;
1196 >
1197 >                        lseek(fileno(sout.ofp), 0, SEEK_SET);
1198 >                        if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1199 >                                sprintf(errmsg, "format mismatch for '%s'",
1200 >                                                oname);
1201 >                                error(USER, errmsg);
1202 >                        }
1203 >                        if ((xres > 0) & (yres > 0) &&
1204 >                                        (!fscnresolu(&xr, &yr, sout.ofp) ||
1205 >                                                xr != xres ||
1206 >                                                yr != yres)) {
1207 >                                sprintf(errmsg, "resolution mismatch for '%s'",
1208 >                                                oname);
1209 >                                error(USER, errmsg);
1210 >                        }
1211 >                        nvals = (nvals - (off_t)ftell(sout.ofp)) / recsiz;
1212 >                        if ((lastout < 0) | (nvals < lastout))
1213 >                                lastout = nvals;
1214 >                        if (oent->key == NULL)  /* new entry */
1215 >                                oent->key = strcpy((char *)
1216 >                                                malloc(strlen(oname)+1), oname);
1217 >                        if (oent->data == NULL)
1218 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1219 >                        *(STREAMOUT *)oent->data = sout;
1220 >                        if (!(ofl & OF_BIN))
1221 >                                break;          /* no bin separation */
1222 >                }
1223 >                if (!lastout) {                 /* empty output */
1224 >                        error(WARNING, "no previous data to recover");
1225 >                        lu_done(&ofiletab);     /* reclose all outputs */
1226 >                        return;
1227 >                }
1228 >                if (j > mp->nbins)              /* reallocate modifier bins */
1229 >                        ment->data = (char *)(mp = growmodifier(mp, j));
1230 >        }
1231 >        if (lastout < 0) {
1232 >                error(WARNING, "no output files to recover");
1233 >                return;
1234 >        }
1235 >        if (raysleft && lastout >= raysleft) {
1236 >                error(WARNING, "output appears to be complete");
1237 >                /* XXX should read & discard input? */
1238 >                quit(0);
1239 >        }
1240 >                                                /* seek on all files */
1241 >        nvals = lastout * outvsiz;
1242 >        lu_doall(&ofiletab, myseeko, &nvals);
1243 >                                                /* skip repeated input */
1244 >        for (nvals = 0; nvals < lastout; nvals++)
1245 >                if (getinp(oname, fin) < 0)
1246 >                        error(USER, "unexpected EOF on input");
1247 >        lastray = lastdone = (unsigned long)lastout;
1248 >        if (raysleft)
1249 >                raysleft -= lastray;
1250   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines