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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines