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.44 by greg, Thu Nov 15 18:32:34 2007 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", "350", };
105 >
106   int  rtargc = 9;
107                                          /* overriding rtrace options */
108 < char            *myrtopts[] = { "-o-TmWdp", "-h-",
109 <                                "-x", "1", "-y", "0", NULL };
108 > char            *myrtopts[] = { "-h-", "-x", "1", "-y", "0",
109 >                                "-dt", "0", "-as", "0", "-aa", "0", NULL };
110  
111 + #define RTCOEFF         "-o~~TmWdp"     /* compute coefficients only */
112 + #define RTCONTRIB       "-o~~TmVdp"     /* compute ray contributions */
113 +
114   struct rtproc   rt0;                    /* head of rtrace process list */
115  
116   struct rtproc   *rt_unproc = NULL;      /* unprocessed ray trees */
117  
118 < char    persistfn[] = "pfXXXXXX";       /* persist file name */
119 < char    fmt[8];                         /* rtrace i/o format */
118 > #define PERSIST_NONE    0               /* no persist file */
119 > #define PERSIST_SINGLE  1               /* user set -P persist */
120 > #define PERSIST_PARALL  2               /* user set -PP persist */
121 > #define PERSIST_OURS    3               /* -PP persist belongs to us */
122 > int     persist_state = PERSIST_NONE;   /* persist file state */
123 > char    persistfn[] = "pfXXXXXX";       /* our persist file name, if set */
124  
125   int             gargc;                  /* global argc */
126   char            **gargv;                /* global argv */
# Line 97 | Line 132 | int            inpfmt = 'a';           /* input format */
132   int             outfmt = 'a';           /* output format */
133  
134   int             header = 1;             /* output header? */
135 + int             force_open = 0;         /* truncate existing output? */
136   int             xres = 0;               /* horiz. output resolution */
137   int             yres = 0;               /* vert. output resolution */
138  
139 < long            raysleft;               /* number of rays left to trace */
139 > unsigned long   raysleft;               /* number of rays left to trace */
140   long            waitflush;              /* how long until next flush */
141  
142   unsigned long   lastray = 0;            /* last ray number sent */
143   unsigned long   lastdone = 0;           /* last ray processed */
144  
145 + int             using_stdout = 0;       /* are we using stdout? */
146 +
147   const char      *modname[MAXMODLIST];   /* ordered modifier name list */
148   int             nmods = 0;              /* number of modifiers */
149  
150 < MODCONT *addmodifier(char *modn, char *outf, char *binv);
150 > #define queue_length()          (lastray - lastdone)
151  
152 < int done_rprocs(struct rtproc *rtp);
152 > MODCONT *growmodifier(MODCONT *mp, int nb);
153 > MODCONT *addmodifier(char *modn, char *outf, char *binv, int bincnt);
154 > void addmodfile(char *fname, char *outf, char *binv, int bincnt);
155 >
156   void init(int np);
157 < void tracecontribs(FILE *fp);
157 > int done_rprocs(struct rtproc *rtp);
158 > void recover_output(FILE *fin);
159 > void trace_contribs(FILE *fin);
160   struct rtproc *wait_rproc(void);
161   struct rtproc *get_rproc(void);
162 < void process_rays(struct rtproc *rtp);
162 > void queue_raytree(struct rtproc *rtp);
163 > void process_queue(void);
164  
165 < void add_contrib(const char *modn, float rayval[7]);
165 > void put_contrib(const DCOLOR cnt, FILE *fout);
166 > void add_contrib(const char *modn);
167   void done_contrib(void);
168  
169 + /* return number of open rtrace processes */
170 + static int
171 + nrtprocs(void)
172 + {
173 +        int     nrtp = 0;
174 +        struct rtproc   *rtp;
175 +
176 +        for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
177 +                nrtp += rtp->pd.running;
178 +        return(nrtp);
179 + }
180 +
181   /* set input/output format */
182   static void
183   setformat(const char *fmt)
184   {
185          switch (fmt[0]) {
129        case 'a':
186          case 'f':
187          case 'd':
188 +                SET_FILE_BINARY(stdin);
189 +                /* fall through */
190 +        case 'a':
191                  inpfmt = fmt[0];
192                  break;
193          default:
# Line 158 | Line 217 | fmterr:
217   int
218   main(int argc, char *argv[])
219   {
220 +        int     contrib = 0;
221          int     nprocs = 1;
222 +        int     recover = 0;
223          char    *curout = NULL;
224          char    *binval = NULL;
225 <        int     i;
226 <                                /* set global argument list */
227 <        gargc = argc;
225 >        int     bincnt = 0;
226 >        char    fmt[8];
227 >        int     i, j;
228 >                                /* need at least one argument */
229 >        if (argc < 2) {
230 >                fprintf(stderr,
231 > "Usage: %s [-n nprocs][-V][-r][-e expr][-f source][-o ospec][-b binv] {-m mod | -M file} [rtrace options] octree\n",
232 >                        argv[0]);
233 >                exit(1);
234 >        }
235 >                                /* global program name */
236          gargv = argv;
237 <                                /* set up calcomp functions */
237 >                                /* initialize calcomp routines */
238          esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
239          esupport &= ~(E_OUTCHAN);
240 +        varset("PI", ':', PI);
241                                  /* get our options */
242 <        for (i = 1; i < argc && argv[i][0] == '-'; i++) {
243 <                switch (argv[i][1]) {
244 <                case 'n':                       /* number of processes */
245 <                        if (argv[i][2] || i >= argc-1) break;
246 <                        nprocs = atoi(argv[++i]);
247 <                        if (nprocs <= 0)
248 <                                error(USER, "illegal number of processes");
249 <                        continue;
250 <                case 'h':                       /* output header? */
251 <                        switch (argv[i][2]) {
252 <                        case '\0':
253 <                                header = !header;
242 >        for (i = 1; i < argc-1; i++) {
243 >                                                /* expand arguments */
244 >                while ((j = expandarg(&argc, &argv, i)) > 0)
245 >                        ;
246 >                if (j < 0) {
247 >                        fprintf(stderr, "%s: cannot expand '%s'",
248 >                                        argv[0], argv[i]);
249 >                        exit(1);
250 >                }
251 >                if (argv[i][0] == '-')
252 >                        switch (argv[i][1]) {
253 >                        case 'n':               /* number of processes */
254 >                                if (argv[i][2] || i >= argc-2) break;
255 >                                nprocs = atoi(argv[++i]);
256 >                                if (nprocs <= 0)
257 >                                        error(USER, "illegal number of processes");
258                                  continue;
259 <                        case '+': case '1': case 'T': case 't':
260 <                                header = 1;
259 >                        case 'V':               /* output contributions */
260 >                                switch (argv[i][2]) {
261 >                                case '\0':
262 >                                        contrib = !contrib;
263 >                                        continue;
264 >                                case '+': case '1':
265 >                                case 'T': case 't':
266 >                                case 'Y': case 'y':
267 >                                        contrib = 1;
268 >                                        continue;
269 >                                case '-': case '0':
270 >                                case 'F': case 'f':
271 >                                case 'N': case 'n':
272 >                                        contrib = 0;
273 >                                        continue;
274 >                                }
275 >                                break;
276 >                        case 'r':               /* recover output */
277 >                                if (argv[i][2]) break;
278 >                                recover++;
279                                  continue;
280 <                        case '-': case '0': case 'F': case 'f':
281 <                                header = 0;
280 >                        case 'h':               /* output header? */
281 >                                switch (argv[i][2]) {
282 >                                case '\0':
283 >                                        header = !header;
284 >                                        continue;
285 >                                case '+': case '1':
286 >                                case 'T': case 't':
287 >                                case 'Y': case 'y':
288 >                                        header = 1;
289 >                                        continue;
290 >                                case '-': case '0':
291 >                                case 'F': case 'f':
292 >                                case 'N': case 'n':
293 >                                        header = 0;
294 >                                        continue;
295 >                                }
296 >                                break;
297 >                        case 'f':               /* file or force or format */
298 >                                if (!argv[i][2]) {
299 >                                        char    *fpath;
300 >                                        if (i >= argc-2) break;
301 >                                        fpath = getpath(argv[++i],
302 >                                                        getrlibpath(), R_OK);
303 >                                        if (fpath == NULL) {
304 >                                                sprintf(errmsg,
305 >                                                        "cannot find file '%s'",
306 >                                                                argv[i]);
307 >                                                error(USER, errmsg);
308 >                                        }
309 >                                        fcompile(fpath);
310 >                                        continue;
311 >                                }
312 >                                if (argv[i][2] == 'o') {
313 >                                        force_open++;
314 >                                        continue;
315 >                                }
316 >                                setformat(argv[i]+2);
317                                  continue;
318 <                        }
319 <                        break;
320 <                case 'f':                       /* file or i/o format */
194 <                        if (!argv[i][2]) {
195 <                                if (i >= argc-1) break;
196 <                                fcompile(argv[++i]);
318 >                        case 'e':               /* expression */
319 >                                if (argv[i][2] || i >= argc-2) break;
320 >                                scompile(argv[++i], NULL, 0);
321                                  continue;
322 +                        case 'o':               /* output file spec. */
323 +                                if (argv[i][2] || i >= argc-2) break;
324 +                                curout = argv[++i];
325 +                                continue;
326 +                        case 'x':               /* horiz. output resolution */
327 +                                if (argv[i][2] || i >= argc-2) break;
328 +                                xres = atoi(argv[++i]);
329 +                                continue;
330 +                        case 'y':               /* vert. output resolution */
331 +                                if (argv[i][2] || i >= argc-2) break;
332 +                                yres = atoi(argv[++i]);
333 +                                continue;
334 +                        case 'b':               /* bin expression/count */
335 +                                if (i >= argc-2) break;
336 +                                if (argv[i][2] == 'n') {
337 +                                        bincnt = atoi(argv[++i]);
338 +                                        continue;
339 +                                }
340 +                                if (argv[i][2]) break;
341 +                                binval = argv[++i];
342 +                                continue;
343 +                        case 'm':               /* modifier name */
344 +                                if (argv[i][2] || i >= argc-2) break;
345 +                                rtargv[rtargc++] = "-ti";
346 +                                rtargv[rtargc++] = argv[++i];
347 +                                addmodifier(argv[i], curout, binval, bincnt);
348 +                                continue;
349 +                        case 'M':               /* modifier file */
350 +                                if (argv[i][2] || i >= argc-2) break;
351 +                                rtargv[rtargc++] = "-tI";
352 +                                rtargv[rtargc++] = argv[++i];
353 +                                addmodfile(argv[i], curout, binval, bincnt);
354 +                                continue;
355 +                        case 'P':               /* persist file */
356 +                                if (i >= argc-2) break;
357 +                                persist_state = (argv[i][2] == 'P') ?
358 +                                                PERSIST_PARALL : PERSIST_SINGLE;
359 +                                rtargv[rtargc++] = argv[i];
360 +                                rtargv[rtargc++] = argv[++i];
361 +                                continue;
362                          }
363 <                        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 */
363 >                rtargv[rtargc++] = argv[i];     /* assume rtrace option */
364          }
365 <        for ( ; i < argc; i++)  /* transfer rtrace-specific options */
366 <                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 <        }
365 >                                /* set global argument list */
366 >        gargc = argc; gargv = argv;
367                                  /* add "mandatory" rtrace settings */
368 <        for (i = 0; myrtopts[i] != NULL; i++)
369 <                rtargv[rtargc++] = myrtopts[i];
370 <        if (!nprocs) {          /* just asking for defaults? */
368 >        for (j = 0; myrtopts[j] != NULL; j++)
369 >                rtargv[rtargc++] = myrtopts[j];
370 >        rtargv[rtargc++] = contrib ? RTCONTRIB : RTCOEFF;
371 >                                /* just asking for defaults? */
372 >        if (!strcmp(argv[i], "-defaults")) {
373                  char    sxres[16], syres[16];
374                  char    *rtpath;
375 <                printf("-n  1\t\t\t\t# number of processes\n", nprocs);
375 >                printf("-n  %-2d\t\t\t\t# number of processes\n", nprocs);
376 >                printf("-V%c\t\t\t\t# output %s\n", contrib ? '+' : '-',
377 >                                contrib ? "contributions" : "coefficients");
378                  fflush(stdout);                 /* report OUR options */
379                  rtargv[rtargc++] = header ? "-h+" : "-h-";
380                  sprintf(fmt, "-f%c%c", inpfmt, outfmt);
# Line 256 | Line 385 | main(int argc, char *argv[])
385                  rtargv[rtargc++] = "-y";
386                  sprintf(syres, "%d", yres);
387                  rtargv[rtargc++] = syres;
259                rtargv[rtargc++] = "-oW";
388                  rtargv[rtargc++] = "-defaults";
389                  rtargv[rtargc] = NULL;
390                  rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
# Line 269 | Line 397 | main(int argc, char *argv[])
397                  perror(rtpath); /* execv() should not return */
398                  exit(1);
399          }
400 <        if (!nmods)
401 <                error(USER, "No modifiers specified");
402 <        if (argc < 2 || argv[argc-1][0] == '-')
403 <                error(USER, "missing octree argument");
400 >        if (nprocs > 1) {       /* add persist file if parallel */
401 >                if (persist_state == PERSIST_SINGLE)
402 >                        error(USER, "use -PP option for multiple processes");
403 >                if (persist_state == PERSIST_NONE) {
404 >                        rtargv[rtargc++] = "-PP";
405 >                        rtargv[rtargc++] = mktemp(persistfn);
406 >                        persist_state = PERSIST_OURS;
407 >                }
408 >        }
409                                  /* add format string */
410          sprintf(fmt, "-f%cf", inpfmt);
411          rtargv[rtargc++] = fmt;
412                                  /* octree argument is last */
413 <        rtargv[rtargc++] = octree = argv[argc-1];
413 >        if (i <= 0 || i != argc-1 || argv[i][0] == '-')
414 >                error(USER, "missing octree argument");
415 >        rtargv[rtargc++] = octree = argv[i];
416          rtargv[rtargc] = NULL;
417 <                                /* start rtrace & sum contributions */
417 >                                /* start rtrace */
418          init(nprocs);
419 <        tracecontribs(stdin);
419 >        if (recover)            /* perform recovery if requested */
420 >                recover_output(stdin);
421 >        trace_contribs(stdin);  /* compute contributions */
422          quit(0);
423   }
424  
425 + #ifndef SIGALRM
426 + #define SIGALRM SIGTERM
427 + #endif
428   /* kill persistent rtrace process */
429   static void
430   killpersist(void)
431   {
432          FILE    *fp = fopen(persistfn, "r");
433 <        int     pid;
433 >        RT_PID  pid;
434  
435          if (fp == NULL)
436                  return;
# Line 324 | Line 464 | quit(int status)
464   {
465          int     rtstat;
466  
467 <        if (rt0.next != NULL)           /* terminate persistent rtrace */
467 >        if (persist_state == PERSIST_OURS)  /* terminate persistent rtrace */
468                  killpersist();
469                                          /* clean up rtrace process(es) */
470          rtstat = done_rprocs(&rt0);
# Line 333 | Line 473 | quit(int status)
473          exit(status);                   /* flushes all output streams */
474   }
475  
476 < /* start rtrace and initialize buffers */
476 > /* start rtrace processes and initialize */
477   void
478   init(int np)
479   {
480          struct rtproc   *rtp;
481          int     i;
482          int     maxbytes;
483 +                                        /* make sure we have something to do */
484 +        if (!nmods)
485 +                error(USER, "No modifiers specified");
486                                          /* assign ray variables */
487          scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
488          scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
489                                          /* set up signal handling */
490 < #ifdef SIGPIPE /* not present on Windows */
490 >        signal(SIGINT, quit);
491 > #ifdef SIGHUP
492 >        signal(SIGHUP, quit);
493 > #endif
494 > #ifdef SIGTERM
495 >        signal(SIGTERM, quit);
496 > #endif
497 > #ifdef SIGPIPE
498          signal(SIGPIPE, quit);
499   #endif
500          rtp = &rt0;                     /* start rtrace process(es) */
# Line 360 | Line 510 | init(int np)
510                          error(SYSTEM, "cannot start rtrace process");
511                  if (maxbytes > treebufsiz)
512                          treebufsiz = maxbytes;
513 +                rtp->raynum = 0;
514                  rtp->bsiz = 0;
515                  rtp->buf = NULL;
516 <                rtp->raynum = 0;
516 >                rtp->nbr = 0;
517                  if (i == np)            /* last process? */
518                          break;
519                  if (i == 1)
# Line 375 | Line 526 | init(int np)
526          rtp->next = NULL;               /* terminate list */
527          if (yres > 0) {
528                  if (xres > 0)
529 <                        raysleft = xres*yres;
529 >                        raysleft = (unsigned long)xres*yres;
530                  else
531                          raysleft = yres;
532          } else
# Line 383 | Line 534 | init(int np)
534          waitflush = xres;
535   }
536  
537 + /* grow modifier to accommodate more bins */
538 + MODCONT *
539 + growmodifier(MODCONT *mp, int nb)
540 + {
541 +        if (nb <= mp->nbins)
542 +                return mp;
543 +        mp = (MODCONT *)realloc(mp, sizeof(MODCONT) + sizeof(DCOLOR)*(nb-1));
544 +        if (mp == NULL)
545 +                error(SYSTEM, "out of memory in growmodifier");
546 +        memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(nb-mp->nbins));
547 +        mp->nbins = nb;
548 +        return mp;
549 + }
550 +
551   /* add modifier to our list to track */
552   MODCONT *
553 < addmodifier(char *modn, char *outf, char *binv)
553 > addmodifier(char *modn, char *outf, char *binv, int bincnt)
554   {
555          LUENT   *lep = lu_find(&modconttab, modn);
556          MODCONT *mp;
557 +        int     i;
558          
559          if (lep->data != NULL) {
560                  sprintf(errmsg, "duplicate modifier '%s'", modn);
# Line 401 | Line 567 | addmodifier(char *modn, char *outf, char *binv)
567          mp = (MODCONT *)malloc(sizeof(MODCONT));
568          if (mp == NULL)
569                  error(SYSTEM, "out of memory in addmodifier");
404        lep->data = (char *)mp;
570          mp->outspec = outf;             /* XXX assumes static string */
571          mp->modname = modn;             /* XXX assumes static string */
572          if (binv != NULL)
# Line 410 | Line 575 | addmodifier(char *modn, char *outf, char *binv)
575                  mp->binv = eparse("0");
576          mp->nbins = 1;
577          setcolor(mp->cbin[0], 0., 0., 0.);
578 +        if (mp->binv->type == NUM)      /* assume one bin if constant */
579 +                bincnt = 1;
580 +        else if (bincnt > 1)
581 +                mp = growmodifier(mp, bincnt);
582 +        lep->data = (char *)mp;
583 +                                        /* allocate output streams */
584 +        for (i = outf==NULL || outf[0]=='!' ? 0 : bincnt; i-- > 0; )
585 +                getostream(mp->outspec, mp->modname, i, 1);
586          return mp;
587   }
588  
589 + /* add modifiers from a file list */
590 + void
591 + addmodfile(char *fname, char *outf, char *binv, int bincnt)
592 + {
593 +        char    *mname[MAXMODLIST];
594 +        int     i;
595 +                                        /* find the file & store strings */
596 +        if (wordfile(mname, getpath(fname, getrlibpath(), R_OK)) < 0) {
597 +                sprintf(errmsg, "cannot find modifier file '%s'", fname);
598 +                error(SYSTEM, errmsg);
599 +        }
600 +        for (i = 0; mname[i]; i++)      /* add each one */
601 +                addmodifier(mname[i], outf, binv, bincnt);
602 + }
603 +
604   /* put string to stderr */
605   void
606   eputs(char  *s)
# Line 428 | Line 616 | eputs(char  *s)
616          midline = s[strlen(s)-1] != '\n';
617   }
618  
619 + /* construct output file name and return flags whether modifier/bin present */
620 + int
621 + ofname(char *oname, const char *ospec, const char *mname, int bn)
622 + {
623 +        const char      *mnp = NULL;
624 +        const char      *bnp = NULL;
625 +        const char      *cp;
626 +        
627 +        if (ospec == NULL)
628 +                return -1;
629 +        for (cp = ospec; *cp; cp++)             /* check format position(s) */
630 +                if (*cp == '%') {
631 +                        do
632 +                                ++cp;
633 +                        while (isdigit(*cp));
634 +                        switch (*cp) {
635 +                        case '%':
636 +                                break;
637 +                        case 's':
638 +                                if (mnp != NULL)
639 +                                        return -1;
640 +                                mnp = cp;
641 +                                break;
642 +                        case 'd':
643 +                                if (bnp != NULL)
644 +                                        return -1;
645 +                                bnp = cp;
646 +                                break;
647 +                        default:
648 +                                return -1;
649 +                        }
650 +                }
651 +        if (mnp != NULL) {                      /* create file name */
652 +                if (bnp != NULL) {
653 +                        if (bnp > mnp)
654 +                                sprintf(oname, ospec, mname, bn);
655 +                        else
656 +                                sprintf(oname, ospec, bn, mname);
657 +                        return OF_MODIFIER|OF_BIN;
658 +                }
659 +                sprintf(oname, ospec, mname);
660 +                return OF_MODIFIER;
661 +        }
662 +        if (bnp != NULL) {
663 +                sprintf(oname, ospec, bn);
664 +                return OF_BIN;
665 +        }
666 +        strcpy(oname, ospec);
667 +        return 0;
668 + }
669 +
670   /* write header to the given output stream */
671   void
672 < printheader(FILE *fout)
672 > printheader(FILE *fout, const char *info)
673   {
674          extern char     VersionID[];
675          FILE            *fin = fopen(octree, "r");
676          
677          if (fin == NULL)
678                  quit(1);
679 <        getheader(fin, (gethfunc *)fputs, fout);        /* copy octree header */
679 >        checkheader(fin, "ignore", fout);       /* copy octree header */
680          fclose(fin);
681          printargs(gargc-1, gargv, fout);        /* add our command */
682          fprintf(fout, "SOFTWARE= %s\n", VersionID);
683          fputnow(fout);
684 +        if (info != NULL)                       /* add extra info if given */
685 +                fputs(info, fout);
686          switch (outfmt) {                       /* add output format */
687          case 'a':
688                  fputformat("ascii", fout);
# Line 457 | Line 698 | printheader(FILE *fout)
698                  break;
699          }
700          fputc('\n', fout);
701 + }
702 +
703 + /* write resolution string to given output stream */
704 + void
705 + printresolu(FILE *fout)
706 + {
707          if (xres > 0) {
708                  if (yres > 0)                   /* resolution string */
709                          fprtresolu(xres, yres, fout);
# Line 464 | Line 711 | printheader(FILE *fout)
711          }
712   }
713  
714 < /* Get output file pointer (open and write header if new) */
715 < FILE *
716 < getofile(const char *ospec, const char *mname, int bn)
714 > /* Get output stream pointer (open and write header if new and noopen==0) */
715 > STREAMOUT *
716 > getostream(const char *ospec, const char *mname, int bn, int noopen)
717   {
718 <        static int      using_stdout = 0;
719 <        const char      *mnp = NULL;
720 <        const char      *bnp = NULL;
721 <        const char      *cp;
722 <        char            ofname[1024];
476 <        LUENT           *lep;
718 >        static STREAMOUT        stdos;
719 >        int                     ofl;
720 >        char                    oname[1024];
721 >        LUENT                   *lep;
722 >        STREAMOUT               *sop;
723          
724          if (ospec == NULL) {                    /* use stdout? */
725 <                if (!using_stdout && header)
726 <                        printheader(stdout);
727 <                using_stdout = 1;
728 <                return stdout;
729 <        }
730 <        for (cp = ospec; *cp; cp++)             /* check format position(s) */
731 <                if (*cp == '%') {
732 <                        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 <                        }
725 >                if (!noopen && !using_stdout) {
726 >                        stdos.reclen = 0;
727 >                        if (outfmt != 'a')
728 >                                SET_FILE_BINARY(stdout);
729 >                        if (header)
730 >                                printheader(stdout, NULL);
731 >                        printresolu(stdout);
732 >                        using_stdout = 1;
733                  }
734 <        if (mnp != NULL) {                      /* create file name */
735 <                if (bnp != NULL) {
736 <                        if (bnp > mnp)
737 <                                sprintf(ofname, ospec, mname, bn);
738 <                        else
739 <                                sprintf(ofname, ospec, bn, mname);
740 <                } else
741 <                        sprintf(ofname, ospec, mname);
742 <        } else if (bnp != NULL)
743 <                sprintf(ofname, ospec, bn);
516 <        else
517 <                strcpy(ofname, ospec);
518 <        lep = lu_find(&ofiletab, ofname);       /* look it up */
734 >                stdos.ofp = stdout;
735 >                stdos.reclen += noopen;
736 >                return &stdos;
737 >        }
738 >        ofl = ofname(oname, ospec, mname, bn);  /* get output name */
739 >        if (ofl < 0) {
740 >                sprintf(errmsg, "bad output format '%s'", ospec);
741 >                error(USER, errmsg);
742 >        }
743 >        lep = lu_find(&ofiletab, oname);        /* look it up */
744          if (lep->key == NULL)                   /* new entry */
745 <                lep->key = strcpy((char *)malloc(strlen(ofname)+1), ofname);
746 <        if (lep->data == NULL) {                /* open output file */
747 <                lep->data = (char *)fopen(ofname, "w");
748 <                if (lep->data == NULL) {
749 <                        sprintf(errmsg, "cannot open '%s' for writing", ofname);
745 >                lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
746 >        sop = (STREAMOUT *)lep->data;
747 >        if (sop == NULL) {                      /* allocate stream */
748 >                sop = (STREAMOUT *)malloc(sizeof(STREAMOUT));
749 >                if (sop == NULL)
750 >                        error(SYSTEM, "out of memory in getostream");
751 >                sop->reclen = oname[0] == '!' ? CNT_PIPE : CNT_UNKNOWN;
752 >                sop->ofp = NULL;                /* open iff noopen==0 */
753 >                lep->data = (char *)sop;
754 >        }
755 >        if (!noopen && sop->ofp == NULL) {      /* open output stream */
756 >                long            i;
757 >                if (oname[0] == '!')            /* output to command */
758 >                        sop->ofp = popen(oname+1, "w");
759 >                else if (!force_open && access(oname, F_OK) == 0)
760 >                        errno = EEXIST;         /* file exists */
761 >                else                            /* else open it */
762 >                        sop->ofp = fopen(oname, "w");
763 >                if (sop->ofp == NULL) {
764 >                        sprintf(errmsg, "cannot open '%s' for writing", oname);
765                          error(SYSTEM, errmsg);
766                  }
767 <                if (header)
768 <                        printheader((FILE *)lep->data);
767 >                if (outfmt != 'a')
768 >                        SET_FILE_BINARY(sop->ofp);
769 >                if (header) {
770 >                        char    info[512];
771 >                        char    *cp = info;
772 >                        if (ofl & OF_MODIFIER || sop->reclen == 1) {
773 >                                sprintf(cp, "MODIFIER=%s\n", mname);
774 >                                while (*cp) ++cp;
775 >                        }
776 >                        if (ofl & OF_BIN) {
777 >                                sprintf(cp, "BIN=%d\n", bn);
778 >                                while (*cp) ++cp;
779 >                        }
780 >                        *cp = '\0';
781 >                        printheader(sop->ofp, info);
782 >                }
783 >                printresolu(sop->ofp);
784 >                                                /* play catch-up */
785 >                for (i = sop->reclen > 1 ? sop->reclen*lastdone : lastdone;
786 >                                                                i--; ) {
787 >                        static const DCOLOR     nocontrib = BLKCOLOR;
788 >                        put_contrib(nocontrib, sop->ofp);
789 >                        if (outfmt == 'a')
790 >                                putc('\n', sop->ofp);
791 >                }
792 >                if (xres > 0)
793 >                        fflush(sop->ofp);
794          }
795 <        return (FILE *)lep->data;               /* return open file pointer */
796 < badspec:
797 <        sprintf(errmsg, "bad output format '%s'", ospec);
533 <        error(USER, errmsg);
534 <        return NULL;            /* pro forma return */
795 >        if (sop->reclen != CNT_PIPE)            /* add to length if noopen */
796 >                sop->reclen += noopen;
797 >        return sop;                             /* return open stream */
798   }
799  
800   /* read input ray into buffer */
801   int
802   getinp(char *buf, FILE *fp)
803   {
804 +        double  dv[3];
805 +        float   fv[3];
806 +        char    *cp;
807 +        int     i;
808 +
809          switch (inpfmt) {
810          case 'a':
811 <                if (fgets(buf, 128, fp) == NULL)
812 <                        return 0;
811 >                cp = buf;               /* make sure we get 6 floats */
812 >                for (i = 0; i < 6; i++) {
813 >                        if (fgetword(cp, buf+127-cp, fp) == NULL)
814 >                                return -1;
815 >                        if (i >= 3)
816 >                                dv[i-3] = atof(cp);
817 >                        if ((cp = fskip(cp)) == NULL || *cp)
818 >                                return -1;
819 >                        *cp++ = ' ';
820 >                }
821 >                getc(fp);               /* get/put eol */
822 >                *cp-- = '\0'; *cp = '\n';
823 >                if (DOT(dv,dv) <= FTINY*FTINY)
824 >                        return 0;       /* dummy ray */
825                  return strlen(buf);
826          case 'f':
827                  if (fread(buf, sizeof(float), 6, fp) < 6)
828 <                        return 0;
828 >                        return -1;
829 >                memcpy(fv, buf+3*sizeof(float), 3*sizeof(float));
830 >                if (DOT(fv,fv) <= FTINY*FTINY)
831 >                        return 0;       /* dummy ray */
832                  return sizeof(float)*6;
833          case 'd':
834                  if (fread(buf, sizeof(double), 6, fp) < 6)
835 <                        return 0;
835 >                        return -1;
836 >                memcpy(dv, buf+3*sizeof(double), 3*sizeof(double));
837 >                if (DOT(dv,dv) <= FTINY*FTINY)
838 >                        return 0;       /* dummy ray */
839                  return sizeof(double)*6;
840          }
841          error(INTERNAL, "botched input format");
842 <        return 0;       /* pro forma return */
842 >        return -1;      /* pro forma return */
843   }
844  
845 < static const float      *rparams = NULL;        /* ray parameter pointer */
845 > static float    rparams[9];             /* traced ray parameters */
846  
847   /* return channel (ray) value */
848   double
# Line 564 | Line 850 | chanvalue(int n)
850   {
851          if (--n < 0 || n >= 6)
852                  error(USER, "illegal channel number ($N)");
853 <        if (rparams == NULL)
568 <                error(USER, "illegal use of $N in constant expression");
569 <        return rparams[n];
853 >        return rparams[n+3];
854   }
855  
856 < /* add ray contribution to the appropriate modifier bin */
856 > /* add current ray contribution to the appropriate modifier bin */
857   void
858 < add_contrib(const char *modn, float rayval[9])
858 > add_contrib(const char *modn)
859   {
860          LUENT   *le = lu_find(&modconttab, modn);
861          MODCONT *mp = (MODCONT *)le->data;
# Line 581 | Line 865 | add_contrib(const char *modn, float rayval[9])
865                  sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
866                  error(USER, errmsg);
867          }
868 <        rparams = rayval + 3;           /* for chanvalue */
585 <        eclock++;
868 >        eclock++;                       /* get bin number */
869          bn = (int)(evalue(mp->binv) + .5);
870          if (bn <= 0)
871                  bn = 0;
872 <        else if (bn > mp->nbins) {      /* new bin */
873 <                mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
874 <                                                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;
872 >        else if (bn >= mp->nbins)       /* new bin */
873 >                le->data = (char *)(mp = growmodifier(mp, bn+1));
874 >        addcolor(mp->cbin[bn], rparams);
875   }
876  
877   /* output newline to ASCII file and/or flush as requested */
878   static int
879   puteol(const LUENT *e, void *p)
880   {
881 <        FILE    *fp = (FILE *)e->data;
881 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
882  
883          if (outfmt == 'a')
884 <                putc('\n', fp);
884 >                putc('\n', sop->ofp);
885          if (!waitflush)
886 <                fflush(fp);
887 <        if (ferror(fp)) {
886 >                fflush(sop->ofp);
887 >        if (ferror(sop->ofp)) {
888                  sprintf(errmsg, "write error on file '%s'", e->key);
889                  error(SYSTEM, errmsg);
890          }
891          return 0;
892   }
893  
894 + /* put out ray contribution to file */
895 + void
896 + put_contrib(const DCOLOR cnt, FILE *fout)
897 + {
898 +        float   fv[3];
899 +        COLR    cv;
900 +
901 +        switch (outfmt) {
902 +        case 'a':
903 +                fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
904 +                break;
905 +        case 'f':
906 +                fv[0] = cnt[0];
907 +                fv[1] = cnt[1];
908 +                fv[2] = cnt[2];
909 +                fwrite(fv, sizeof(float), 3, fout);
910 +                break;
911 +        case 'd':
912 +                fwrite(cnt, sizeof(double), 3, fout);
913 +                break;
914 +        case 'c':
915 +                setcolr(cv, cnt[0], cnt[1], cnt[2]);
916 +                fwrite(cv, sizeof(cv), 1, fout);
917 +                break;
918 +        default:
919 +                error(INTERNAL, "botched output format");
920 +        }
921 + }
922 +
923   /* output ray tallies and clear for next primary */
924   void
925   done_contrib(void)
926   {
927 <        int     i, j;
928 <        MODCONT *mp;
929 <        FILE    *fout;
626 <        double  dv[3];
627 <        COLR    cv;
927 >        int             i, j;
928 >        MODCONT         *mp;
929 >        STREAMOUT       *sop;
930                                                  /* output modifiers in order */
931          for (i = 0; i < nmods; i++) {
932                  mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
933 <                for (j = 0; j < mp->nbins; j++) {
934 <                        fout = getofile(mp->outspec, mp->modname, j);
935 <                        switch (outfmt) {
936 <                        case 'a':
937 <                                fprintf(fout, "%.6e\t%.6e\t%.6e\t",
938 <                                                mp->cbin[j][RED],
939 <                                                mp->cbin[j][GRN],
940 <                                                mp->cbin[j][BLU]);
941 <                                break;
942 <                        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 <                }
933 >                sop = getostream(mp->outspec, mp->modname, 0,0);
934 >                put_contrib(mp->cbin[0], sop->ofp);
935 >                if (mp->nbins > 3 &&            /* minor optimization */
936 >                                sop == getostream(mp->outspec, mp->modname, 1,0))
937 >                        for (j = 1; j < mp->nbins; j++)
938 >                                put_contrib(mp->cbin[j], sop->ofp);
939 >                else
940 >                        for (j = 1; j < mp->nbins; j++)
941 >                                put_contrib(mp->cbin[j],
942 >                                    getostream(mp->outspec,mp->modname,j,0)->ofp);
943                                                  /* clear for next ray tree */
944 <                memset(mp->cbin, 0, sizeof(COLOR)*mp->nbins);
944 >                memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
945          }
946          --waitflush;                            /* terminate records */
947          lu_doall(&ofiletab, puteol, NULL);
948 <        if (!waitflush)
948 >        if (using_stdout & (outfmt == 'a'))
949 >                putc('\n', stdout);
950 >        if (!waitflush) {
951                  waitflush = xres;
952 +                if (using_stdout)
953 +                        fflush(stdout);
954 +        }
955   }
956  
957 < /* process (or save) ray tree produced by rtrace process */
957 > /* queue completed ray tree produced by rtrace process */
958   void
959 < process_rays(struct rtproc *rtp)
959 > queue_raytree(struct rtproc *rtp)
960   {
961 <        struct rtproc   *rtu;
962 <                                        /* check if time to process it */
963 <        if (rtp->raynum == lastdone+1) {
964 <                int             n = rtp->bpos - rtp->buf;
961 >        struct rtproc   *rtu, *rtl = NULL;
962 >                                        /* insert following ray order */
963 >        for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
964 >                if (rtp->raynum < rtu->raynum)
965 >                        break;
966 >        rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
967 >        if (rtu == NULL)
968 >                error(SYSTEM, "out of memory in queue_raytree");
969 >        *rtu = *rtp;
970 >        if (rtl == NULL) {
971 >                rtu->next = rt_unproc;
972 >                rt_unproc = rtu;
973 >        } else {
974 >                rtu->next = rtl->next;
975 >                rtl->next = rtu;
976 >        }
977 >        rtp->raynum = 0;                /* clear path for next ray tree */
978 >        rtp->bsiz = 0;
979 >        rtp->buf = NULL;
980 >        rtp->nbr = 0;
981 > }
982 >
983 > /* process completed ray trees from our queue */
984 > void
985 > process_queue(void)
986 > {
987 >        char    modname[128];
988 >                                        /* ray-ordered queue */
989 >        while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
990 >                struct rtproc   *rtp = rt_unproc;
991 >                int             n = rtp->nbr;
992                  const char      *cp = rtp->buf;
993                  while (n > 0) {         /* process rays */
994 <                        char    matname[128];
678 <                        char    *mnp = matname;
994 >                        register char   *mnp = modname;
995                                          /* skip leading tabs */
996                          while (n > 0 && *cp == '\t') {
997                                  cp++; n--;
998                          }
999 <                                        /* get material name */
1000 <                        while (n > 0 && *cp != '\t') {
999 >                        if (!n || !(isalpha(*cp) | (*cp == '_')))
1000 >                                error(USER, "bad modifier name from rtrace");
1001 >                                        /* get modifier name */
1002 >                        while (n > 1 && *cp != '\t') {
1003 >                                if (mnp - modname >= sizeof(modname)-2)
1004 >                                        error(INTERNAL, "modifier name too long");
1005                                  *mnp++ = *cp++; n--;
1006                          }
687                        if (!n)
688                                error(USER, "botched modifer name from rtrace");
1007                          *mnp = '\0';
1008 <                        cp++; n--;      /* skip terminating tab */
1008 >                        cp++; n--;      /* eat following tab */
1009                          if (n < (int)(sizeof(float)*9))
1010                                  error(USER, "incomplete ray value from rtrace");
1011                                          /* add ray contribution */
1012 <                        add_contrib(matname, (float *)cp);
1012 >                        memcpy(rparams, cp, sizeof(float)*9);
1013                          cp += sizeof(float)*9; n -= sizeof(float)*9;
1014 +                        add_contrib(modname);
1015                  }
1016                  done_contrib();         /* sum up contributions & output */
1017                  lastdone = rtp->raynum;
1018 <                free(rtp->buf);
1019 <                                        /* catch up with unprocessed list */
1020 <                while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
1021 <                        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 <                }
1018 >                if (rtp->buf != NULL)   /* free up buffer space */
1019 >                        free(rtp->buf);
1020 >                rt_unproc = rtp->next;
1021 >                free(rtp);              /* done with this ray tree */
1022          }
723        rtp->raynum = 0;                /* clear path for next ray tree */
724        rtp->bsiz = 0;
725        rtp->buf = NULL;
1023   }
1024  
1025   /* wait for rtrace process to finish with ray tree */
# Line 763 | Line 1060 | wait_rproc(void)
1060                          if (rt->buf == NULL) {
1061                                  rt->bsiz = treebufsiz;
1062                                  rt->buf = (char *)malloc(treebufsiz);
1063 <                        } else if (rt->bpos + BUFSIZ > rt->buf + rt->bsiz) {
1063 >                        } else if (rt->nbr + BUFSIZ > rt->bsiz) {
1064                                  if (rt->bsiz + BUFSIZ <= treebufsiz)
1065                                          rt->bsiz = treebufsiz;
1066                                  else
1067 <                                        rt->bsiz = treebufsiz += BUFSIZ;
1067 >                                        treebufsiz = rt->bsiz += BUFSIZ;
1068                                  rt->buf = (char *)realloc(rt->buf, rt->bsiz);
1069                          }
1070                          if (rt->buf == NULL)
1071                                  error(SYSTEM, "out of memory in wait_rproc");
1072 <                        nr = read(rt->pd.r, rt->bpos,
1073 <                                        rt->buf + rt->bsiz - rt->bpos);
777 <                        if (!nr)
1072 >                        nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
1073 >                        if (nr <= 0)
1074                                  error(USER, "rtrace process died");
1075 <                        rt->bpos += nr;         /* advance buffer & check */
1076 <                        if (rt->bpos[-1] == '\t' && rt->bpos[-2] == '-') {
1077 <                                rt->bpos -= 2;  /* elide terminator */
1078 <                                process_rays(rt);
1075 >                        rt->nbr += nr;          /* advance & check */
1076 >                        if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
1077 >                                                        "~\t~\t", 4)) {
1078 >                                rt->nbr -= 4;   /* elide terminator */
1079 >                                queue_raytree(rt);
1080                                  rtfree = rt;    /* ready for next ray */
1081                          }
1082                  }
# Line 801 | Line 1098 | get_rproc(void)
1098  
1099   /* trace ray contributions (main loop) */
1100   void
1101 < tracecontribs(FILE *fin)
1101 > trace_contribs(FILE *fin)
1102   {
1103          char            inpbuf[128];
1104          int             iblen;
1105          struct rtproc   *rtp;
1106                                                  /* loop over input */
1107 <        while ((iblen = getinp(inpbuf, fin)) > 0) {
1108 <                if (lastray+1 < lastray) {      /* counter rollover? */
1107 >        while ((iblen = getinp(inpbuf, fin)) >= 0) {
1108 >                if (!iblen ||                   /* need reset? */
1109 >                                queue_length() > 10*nrtprocs() ||
1110 >                                lastray+1 < lastray) {
1111                          while (wait_rproc() != NULL)
1112 <                                ;
1113 <                        lastdone = lastray = 0;
1112 >                                process_queue();
1113 >                        if (lastray+1 < lastray)
1114 >                                lastdone = lastray = 0;
1115                  }
1116                  rtp = get_rproc();              /* get avail. rtrace process */
1117 <                rtp->raynum = ++lastray;        /* assign this ray to it */
1118 <                writebuf(rtp->pd.w, inpbuf, iblen);
1119 <                if (!--raysleft)
1120 <                        break;                  /* explicit EOF */
1117 >                rtp->raynum = ++lastray;        /* assign ray */
1118 >                if (iblen) {                    /* trace ray if valid */
1119 >                        writebuf(rtp->pd.w, inpbuf, iblen);
1120 >                } else {                        /* else bypass dummy ray */
1121 >                        queue_raytree(rtp);     /* empty tree */
1122 >                        if ((yres <= 0) | (waitflush > 1))
1123 >                                waitflush = 1;  /* flush after this */
1124 >                }
1125 >                process_queue();                /* catch up with results */
1126 >                if (raysleft && !--raysleft)
1127 >                        break;                  /* preemptive EOI */
1128          }
1129          while (wait_rproc() != NULL)            /* process outstanding rays */
1130 <                ;
1130 >                process_queue();
1131 >        if (raysleft)
1132 >                error(USER, "unexpected EOF on input");
1133 >        lu_done(&ofiletab);                     /* close output files */
1134 > }
1135 >
1136 > /* seek on the given output file */
1137 > static int
1138 > myseeko(const LUENT *e, void *p)
1139 > {
1140 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1141 >        off_t           nbytes = *(off_t *)p;
1142 >        
1143 >        if (sop->reclen > 1)
1144 >                nbytes = nbytes * sop->reclen;
1145 >        if (fseeko(sop->ofp, nbytes, SEEK_CUR) < 0) {
1146 >                sprintf(errmsg, "seek error on file '%s'", e->key);
1147 >                error(SYSTEM, errmsg);
1148 >        }
1149 >        return 0;
1150 > }
1151 >
1152 > /* recover output if possible */
1153 > void
1154 > recover_output(FILE *fin)
1155 > {
1156 >        off_t           lastout = -1;
1157 >        int             outvsiz, recsiz;
1158 >        char            *outvfmt;
1159 >        int             i, j;
1160 >        MODCONT         *mp;
1161 >        int             ofl;
1162 >        char            oname[1024];
1163 >        LUENT           *ment, *oent;
1164 >        STREAMOUT       sout;
1165 >        off_t           nvals;
1166 >        int             xr, yr;
1167 >
1168 >        switch (outfmt) {
1169 >        case 'a':
1170 >                error(USER, "cannot recover ASCII output");
1171 >                return;
1172 >        case 'f':
1173 >                outvsiz = sizeof(float)*3;
1174 >                outvfmt = "float";
1175 >                break;
1176 >        case 'd':
1177 >                outvsiz = sizeof(double)*3;
1178 >                outvfmt = "double";
1179 >                break;
1180 >        case 'c':
1181 >                outvsiz = sizeof(COLR);
1182 >                outvfmt = COLRFMT;
1183 >                break;
1184 >        default:
1185 >                error(INTERNAL, "botched output format");
1186 >                return;
1187 >        }
1188 >                                                /* check modifier outputs */
1189 >        for (i = 0; i < nmods; i++) {
1190 >                ment = lu_find(&modconttab,modname[i]);
1191 >                mp = (MODCONT *)ment->data;
1192 >                if (mp->outspec == NULL)
1193 >                        error(USER, "cannot recover from stdout");
1194 >                if (mp->outspec[0] == '!')
1195 >                        error(USER, "cannot recover from command");
1196 >                for (j = 0; ; j++) {            /* check each bin's file */
1197 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1198 >                        if (ofl < 0)
1199 >                                error(USER, "bad output file specification");
1200 >                        oent = lu_find(&ofiletab, oname);
1201 >                        if (oent->data != NULL) {
1202 >                                sout = *(STREAMOUT *)oent->data;
1203 >                        } else {
1204 >                                sout.reclen = CNT_UNKNOWN;
1205 >                                sout.ofp = NULL;
1206 >                        }
1207 >                        if (sout.ofp != NULL) { /* already open? */
1208 >                                if (ofl & OF_BIN)
1209 >                                        continue;
1210 >                                break;
1211 >                        }
1212 >                                                /* open output */
1213 >                        sout.ofp = fopen(oname, "rb+");
1214 >                        if (sout.ofp == NULL) {
1215 >                                if (j)
1216 >                                        break;  /* assume end of modifier */
1217 >                                sprintf(errmsg, "missing recover file '%s'",
1218 >                                                oname);
1219 >                                error(USER, errmsg);
1220 >                        }
1221 >                        nvals = lseek(fileno(sout.ofp), 0, SEEK_END);
1222 >                        if (nvals <= 0) {
1223 >                                lastout = 0;    /* empty output, quit here */
1224 >                                fclose(sout.ofp);
1225 >                                break;
1226 >                        }
1227 >                        if (sout.reclen == CNT_UNKNOWN) {
1228 >                                if (!(ofl & OF_BIN)) {
1229 >                                        sprintf(errmsg,
1230 >                                                "need -bn to recover file '%s'",
1231 >                                                        oname);
1232 >                                        error(USER, errmsg);
1233 >                                }
1234 >                                recsiz = outvsiz;
1235 >                        } else
1236 >                                recsiz = outvsiz * sout.reclen;
1237 >
1238 >                        lseek(fileno(sout.ofp), 0, SEEK_SET);
1239 >                        if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1240 >                                sprintf(errmsg, "format mismatch for '%s'",
1241 >                                                oname);
1242 >                                error(USER, errmsg);
1243 >                        }
1244 >                        if ((xres > 0) & (yres > 0) &&
1245 >                                        (!fscnresolu(&xr, &yr, sout.ofp) ||
1246 >                                                xr != xres ||
1247 >                                                yr != yres)) {
1248 >                                sprintf(errmsg, "resolution mismatch for '%s'",
1249 >                                                oname);
1250 >                                error(USER, errmsg);
1251 >                        }
1252 >                        nvals = (nvals - (off_t)ftell(sout.ofp)) / recsiz;
1253 >                        if ((lastout < 0) | (nvals < lastout))
1254 >                                lastout = nvals;
1255 >                        if (oent->key == NULL)  /* new entry */
1256 >                                oent->key = strcpy((char *)
1257 >                                                malloc(strlen(oname)+1), oname);
1258 >                        if (oent->data == NULL)
1259 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1260 >                        *(STREAMOUT *)oent->data = sout;
1261 >                        if (!(ofl & OF_BIN))
1262 >                                break;          /* no bin separation */
1263 >                }
1264 >                if (!lastout) {                 /* empty output */
1265 >                        error(WARNING, "no previous data to recover");
1266 >                        lu_done(&ofiletab);     /* reclose all outputs */
1267 >                        return;
1268 >                }
1269 >                if (j > mp->nbins)              /* reallocate modifier bins */
1270 >                        ment->data = (char *)(mp = growmodifier(mp, j));
1271 >        }
1272 >        if (lastout < 0) {
1273 >                error(WARNING, "no output files to recover");
1274 >                return;
1275 >        }
1276 >        if (raysleft && lastout >= raysleft) {
1277 >                error(WARNING, "output appears to be complete");
1278 >                /* XXX should read & discard input? */
1279 >                quit(0);
1280 >        }
1281 >                                                /* seek on all files */
1282 >        nvals = lastout * outvsiz;
1283 >        lu_doall(&ofiletab, myseeko, &nvals);
1284 >                                                /* skip repeated input */
1285 >        for (nvals = 0; nvals < lastout; nvals++)
1286 >                if (getinp(oname, fin) < 0)
1287 >                        error(USER, "unexpected EOF on input");
1288 >        lastray = lastdone = (unsigned long)lastout;
1289 >        if (raysleft)
1290 >                raysleft -= lastray;
1291   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines