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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines