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.48 by greg, Sat Nov 17 16:27:14 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 evaluates > 0.  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 > /*
50 > * The STREAMOUT structure holds an open FILE pointer and a count of
51 > * the number of RGB triplets per record, or 0 if unknown.
52 > */
53 > typedef struct {
54 >        FILE            *ofp;           /* output file pointer */
55 >        int             outpipe;        /* output is to a pipe */
56 >        int             reclen;         /* triplets/record */
57 >        int             xr, yr;         /* output resolution for picture */
58 > } STREAMOUT;
59  
60 < LUTAB   ofiletab = LU_SINIT(free,closefile);    /* output file table */
60 > /* close output stream and free record */
61 > static void
62 > closestream(void *p)
63 > {
64 >        STREAMOUT       *sop = (STREAMOUT *)p;
65 >        int             status;
66 >        if (sop->outpipe)
67 >                status = pclose(sop->ofp);
68 >        else
69 >                status = fclose(sop->ofp);
70 >        if (status)
71 >                error(SYSTEM, "error closing output stream");
72 >        free(p);
73 > }
74  
75 < FILE *getofile(const char *ospec, const char *mname, int bn);
75 > LUTAB   ofiletab = LU_SINIT(free,closestream);  /* output file table */
76  
77 + #define OF_MODIFIER     01
78 + #define OF_BIN          02
79 +
80 + STREAMOUT *getostream(const char *ospec, const char *mname, int bn, int noopen);
81 + int ofname(char *oname, const char *ospec, const char *mname, int bn);
82 + void printheader(FILE *fout, const char *info);
83 + void printresolu(FILE *fout, int xr, int yr);
84 +
85   /*
86   * The rcont structure is used to manage i/o with a particular
87   * rtrace child process.  Input is passed unchanged from stdin,
# Line 66 | Line 91 | FILE *getofile(const char *ospec, const char *mname, i
91   struct rtproc {
92          struct rtproc   *next;          /* next in list of processes */
93          SUBPROC         pd;             /* rtrace pipe descriptors */
94 <        unsigned long   raynum;         /* ray number for this buffer */
95 <        int             bsiz;           /* rtrace buffer length */
96 <        char            *buf;           /* rtrace i/o buffer */
97 <        char            *bpos;          /* current buffer position */
98 < };                              /* rtrace process */
94 >        unsigned long   raynum;         /* ray number for this tree */
95 >        int             bsiz;           /* ray tree buffer length */
96 >        char            *buf;           /* ray tree buffer */
97 >        int             nbr;            /* number of bytes from rtrace */
98 > };                              /* rtrace process buffer */
99  
100                                          /* rtrace command and defaults */
101 < char            *rtargv[256] = { "rtrace", "-dj", ".5", "-dr", "3",
102 <                                "-ab", "1", "-ad", "512", };
101 > char            *rtargv[256+2*MAXMODLIST] = { "rtrace",
102 >                                "-dj", ".5", "-dr", "3",
103 >                                "-ab", "1", "-ad", "350", };
104 >
105   int  rtargc = 9;
106                                          /* overriding rtrace options */
107 < char            *myrtopts[] = { "-o-TmWdp", "-h-",
108 <                                "-x", "1", "-y", "0", NULL };
107 > char            *myrtopts[] = { "-h-", "-x", "1", "-y", "0",
108 >                                "-dt", "0", "-as", "0", "-aa", "0", NULL };
109  
110 + #define RTCOEFF         "-o~~TmWdp"     /* compute coefficients only */
111 + #define RTCONTRIB       "-o~~TmVdp"     /* compute ray contributions */
112 +
113   struct rtproc   rt0;                    /* head of rtrace process list */
114  
115   struct rtproc   *rt_unproc = NULL;      /* unprocessed ray trees */
116  
117 < char    persistfn[] = "pfXXXXXX";       /* persist file name */
118 < char    fmt[8];                         /* rtrace i/o format */
117 > #define PERSIST_NONE    0               /* no persist file */
118 > #define PERSIST_SINGLE  1               /* user set -P persist */
119 > #define PERSIST_PARALL  2               /* user set -PP persist */
120 > #define PERSIST_OURS    3               /* -PP persist belongs to us */
121 > int     persist_state = PERSIST_NONE;   /* persist file state */
122 > char    persistfn[] = "pfXXXXXX";       /* our persist file name, if set */
123  
124   int             gargc;                  /* global argc */
125   char            **gargv;                /* global argv */
# Line 97 | Line 131 | int            inpfmt = 'a';           /* input format */
131   int             outfmt = 'a';           /* output format */
132  
133   int             header = 1;             /* output header? */
134 + int             accumulate = 0;         /* accumulate ray values? */
135 + int             force_open = 0;         /* truncate existing output? */
136 + int             recover = 0;            /* recover previous output? */
137   int             xres = 0;               /* horiz. output resolution */
138   int             yres = 0;               /* vert. output resolution */
139  
140 < long            raysleft;               /* number of rays left to trace */
140 > unsigned long   raysleft;               /* number of rays left to trace */
141   long            waitflush;              /* how long until next flush */
142  
143   unsigned long   lastray = 0;            /* last ray number sent */
144   unsigned long   lastdone = 0;           /* last ray processed */
145  
146 + int             using_stdout = 0;       /* are we using stdout? */
147 +
148   const char      *modname[MAXMODLIST];   /* ordered modifier name list */
149   int             nmods = 0;              /* number of modifiers */
150  
151 < MODCONT *addmodifier(char *modn, char *outf, char *binv);
151 > #define queue_length()          (lastray - lastdone)
152  
153 < int done_rprocs(struct rtproc *rtp);
153 > MODCONT *growmodifier(MODCONT *mp, int nb);
154 > MODCONT *addmodifier(char *modn, char *outf, char *binv, int bincnt);
155 > void addmodfile(char *fname, char *outf, char *binv, int bincnt);
156 >
157   void init(int np);
158 < void tracecontribs(FILE *fp);
158 > int done_rprocs(struct rtproc *rtp);
159 > void reload_output(void);
160 > void recover_output(FILE *fin);
161 > void trace_contribs(FILE *fin);
162   struct rtproc *wait_rproc(void);
163   struct rtproc *get_rproc(void);
164 < void process_rays(struct rtproc *rtp);
164 > void queue_raytree(struct rtproc *rtp);
165 > void process_queue(void);
166  
167 < void add_contrib(const char *modn, float rayval[7]);
167 > void put_contrib(const DCOLOR cnt, FILE *fout);
168 > void add_contrib(const char *modn);
169   void done_contrib(void);
170  
171 + /* return number of open rtrace processes */
172 + static int
173 + nrtprocs(void)
174 + {
175 +        int     nrtp = 0;
176 +        struct rtproc   *rtp;
177 +
178 +        for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
179 +                nrtp += rtp->pd.running;
180 +        return(nrtp);
181 + }
182 +
183   /* set input/output format */
184   static void
185   setformat(const char *fmt)
186   {
187          switch (fmt[0]) {
129        case 'a':
188          case 'f':
189          case 'd':
190 +                SET_FILE_BINARY(stdin);
191 +                /* fall through */
192 +        case 'a':
193                  inpfmt = fmt[0];
194                  break;
195          default:
# Line 158 | Line 219 | fmterr:
219   int
220   main(int argc, char *argv[])
221   {
222 +        int     contrib = 0;
223          int     nprocs = 1;
224          char    *curout = NULL;
225          char    *binval = NULL;
226 <        int     i;
227 <                                /* set global argument list */
228 <        gargc = argc;
226 >        int     bincnt = 0;
227 >        char    fmt[8];
228 >        int     i, j;
229 >                                /* need at least one argument */
230 >        if (argc < 2) {
231 >                fprintf(stderr,
232 > "Usage: %s [-n nprocs][-V][-r][-e expr][-f source][-o ospec][-b binv] {-m mod | -M file} [rtrace options] octree\n",
233 >                        argv[0]);
234 >                exit(1);
235 >        }
236 >                                /* global program name */
237          gargv = argv;
238 <                                /* set up calcomp functions */
238 >                                /* initialize calcomp routines */
239          esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
240          esupport &= ~(E_OUTCHAN);
241 +        varset("PI", ':', PI);
242                                  /* get our options */
243 <        for (i = 1; i < argc && argv[i][0] == '-'; i++) {
244 <                switch (argv[i][1]) {
245 <                case 'n':                       /* number of processes */
246 <                        if (argv[i][2] || i >= argc-1) break;
247 <                        nprocs = atoi(argv[++i]);
248 <                        if (nprocs <= 0)
249 <                                error(USER, "illegal number of processes");
250 <                        continue;
251 <                case 'h':                       /* output header? */
252 <                        switch (argv[i][2]) {
253 <                        case '\0':
254 <                                header = !header;
243 >        for (i = 1; i < argc-1; i++) {
244 >                                                /* expand arguments */
245 >                while ((j = expandarg(&argc, &argv, i)) > 0)
246 >                        ;
247 >                if (j < 0) {
248 >                        fprintf(stderr, "%s: cannot expand '%s'",
249 >                                        argv[0], argv[i]);
250 >                        exit(1);
251 >                }
252 >                if (argv[i][0] == '-')
253 >                        switch (argv[i][1]) {
254 >                        case 'n':               /* number of processes */
255 >                                if (argv[i][2] || i >= argc-2) break;
256 >                                nprocs = atoi(argv[++i]);
257 >                                if (nprocs <= 0)
258 >                                        error(USER, "illegal number of processes");
259                                  continue;
260 <                        case '+': case '1': case 'T': case 't':
261 <                                header = 1;
260 >                        case 'V':               /* output contributions */
261 >                                switch (argv[i][2]) {
262 >                                case '\0':
263 >                                        contrib = !contrib;
264 >                                        continue;
265 >                                case '+': case '1':
266 >                                case 'T': case 't':
267 >                                case 'Y': case 'y':
268 >                                        contrib = 1;
269 >                                        continue;
270 >                                case '-': case '0':
271 >                                case 'F': case 'f':
272 >                                case 'N': case 'n':
273 >                                        contrib = 0;
274 >                                        continue;
275 >                                }
276 >                                break;
277 >                        case 'c':               /* accumulate ray values */
278 >                                switch (argv[i][2]) {
279 >                                case '\0':
280 >                                        accumulate = !accumulate;
281 >                                        continue;
282 >                                case '+': case '1':
283 >                                case 'T': case 't':
284 >                                case 'Y': case 'y':
285 >                                        accumulate = 1;
286 >                                        continue;
287 >                                case '-': case '0':
288 >                                case 'F': case 'f':
289 >                                case 'N': case 'n':
290 >                                        accumulate = 0;
291 >                                        continue;
292 >                                }
293 >                                break;
294 >                        case 'r':               /* recover output */
295 >                                if (argv[i][2]) break;
296 >                                recover = 1;
297                                  continue;
298 <                        case '-': case '0': case 'F': case 'f':
299 <                                header = 0;
298 >                        case 'h':               /* output header? */
299 >                                switch (argv[i][2]) {
300 >                                case '\0':
301 >                                        header = !header;
302 >                                        continue;
303 >                                case '+': case '1':
304 >                                case 'T': case 't':
305 >                                case 'Y': case 'y':
306 >                                        header = 1;
307 >                                        continue;
308 >                                case '-': case '0':
309 >                                case 'F': case 'f':
310 >                                case 'N': case 'n':
311 >                                        header = 0;
312 >                                        continue;
313 >                                }
314 >                                break;
315 >                        case 'f':               /* file or force or format */
316 >                                if (!argv[i][2]) {
317 >                                        char    *fpath;
318 >                                        if (i >= argc-2) break;
319 >                                        fpath = getpath(argv[++i],
320 >                                                        getrlibpath(), R_OK);
321 >                                        if (fpath == NULL) {
322 >                                                sprintf(errmsg,
323 >                                                        "cannot find file '%s'",
324 >                                                                argv[i]);
325 >                                                error(USER, errmsg);
326 >                                        }
327 >                                        fcompile(fpath);
328 >                                        continue;
329 >                                }
330 >                                if (argv[i][2] == 'o') {
331 >                                        force_open = 1;
332 >                                        continue;
333 >                                }
334 >                                setformat(argv[i]+2);
335                                  continue;
336 <                        }
337 <                        break;
338 <                case 'f':                       /* file or i/o format */
194 <                        if (!argv[i][2]) {
195 <                                if (i >= argc-1) break;
196 <                                fcompile(argv[++i]);
336 >                        case 'e':               /* expression */
337 >                                if (argv[i][2] || i >= argc-2) break;
338 >                                scompile(argv[++i], NULL, 0);
339                                  continue;
340 +                        case 'o':               /* output file spec. */
341 +                                if (argv[i][2] || i >= argc-2) break;
342 +                                curout = argv[++i];
343 +                                continue;
344 +                        case 'x':               /* horiz. output resolution */
345 +                                if (argv[i][2] || i >= argc-2) break;
346 +                                xres = atoi(argv[++i]);
347 +                                continue;
348 +                        case 'y':               /* vert. output resolution */
349 +                                if (argv[i][2] || i >= argc-2) break;
350 +                                yres = atoi(argv[++i]);
351 +                                continue;
352 +                        case 'b':               /* bin expression/count */
353 +                                if (i >= argc-2) break;
354 +                                if (argv[i][2] == 'n') {
355 +                                        bincnt = atoi(argv[++i]);
356 +                                        continue;
357 +                                }
358 +                                if (argv[i][2]) break;
359 +                                binval = argv[++i];
360 +                                continue;
361 +                        case 'm':               /* modifier name */
362 +                                if (argv[i][2] || i >= argc-2) break;
363 +                                rtargv[rtargc++] = "-ti";
364 +                                rtargv[rtargc++] = argv[++i];
365 +                                addmodifier(argv[i], curout, binval, bincnt);
366 +                                continue;
367 +                        case 'M':               /* modifier file */
368 +                                if (argv[i][2] || i >= argc-2) break;
369 +                                rtargv[rtargc++] = "-tI";
370 +                                rtargv[rtargc++] = argv[++i];
371 +                                addmodfile(argv[i], curout, binval, bincnt);
372 +                                continue;
373 +                        case 'P':               /* persist file */
374 +                                if (i >= argc-2) break;
375 +                                persist_state = (argv[i][2] == 'P') ?
376 +                                                PERSIST_PARALL : PERSIST_SINGLE;
377 +                                rtargv[rtargc++] = argv[i];
378 +                                rtargv[rtargc++] = argv[++i];
379 +                                continue;
380                          }
381 <                        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 */
381 >                rtargv[rtargc++] = argv[i];     /* assume rtrace option */
382          }
383 <        for ( ; i < argc; i++)  /* transfer rtrace-specific options */
384 <                rtargv[rtargc++] = argv[i];
385 <        if (!strcmp(rtargv[--rtargc], "-defaults"))
386 <                nprocs = 0;
238 <        if (nprocs > 1) {       /* add persist file if parallel invocation */
239 <                rtargv[rtargc++] = "-PP";
240 <                rtargv[rtargc++] = mktemp(persistfn);
241 <        }
383 >        if (accumulate)         /* no output flushing for single record */
384 >                xres = yres = 0;
385 >                                /* set global argument list */
386 >        gargc = argc; gargv = argv;
387                                  /* add "mandatory" rtrace settings */
388 <        for (i = 0; myrtopts[i] != NULL; i++)
389 <                rtargv[rtargc++] = myrtopts[i];
390 <        if (!nprocs) {          /* just asking for defaults? */
388 >        for (j = 0; myrtopts[j] != NULL; j++)
389 >                rtargv[rtargc++] = myrtopts[j];
390 >        rtargv[rtargc++] = contrib ? RTCONTRIB : RTCOEFF;
391 >                                /* just asking for defaults? */
392 >        if (!strcmp(argv[i], "-defaults")) {
393                  char    sxres[16], syres[16];
394                  char    *rtpath;
395 <                printf("-n  1\t\t\t\t# number of processes\n", nprocs);
395 >                printf("-n  %-2d\t\t\t\t# number of processes\n", nprocs);
396 >                printf("-V%c\t\t\t\t# output %s\n", contrib ? '+' : '-',
397 >                                contrib ? "contributions" : "coefficients");
398 >                printf("-c%c\t\t\t\t# %s\n", accumulate ? '+' : '-',
399 >                                accumulate ? "accumulate ray values" :
400 >                                        "one output record per ray");
401                  fflush(stdout);                 /* report OUR options */
402                  rtargv[rtargc++] = header ? "-h+" : "-h-";
403                  sprintf(fmt, "-f%c%c", inpfmt, outfmt);
# Line 256 | Line 408 | main(int argc, char *argv[])
408                  rtargv[rtargc++] = "-y";
409                  sprintf(syres, "%d", yres);
410                  rtargv[rtargc++] = syres;
259                rtargv[rtargc++] = "-oW";
411                  rtargv[rtargc++] = "-defaults";
412                  rtargv[rtargc] = NULL;
413                  rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
# Line 269 | Line 420 | main(int argc, char *argv[])
420                  perror(rtpath); /* execv() should not return */
421                  exit(1);
422          }
423 <        if (!nmods)
424 <                error(USER, "No modifiers specified");
425 <        if (argc < 2 || argv[argc-1][0] == '-')
426 <                error(USER, "missing octree argument");
423 >        if (nprocs > 1) {       /* add persist file if parallel */
424 >                if (persist_state == PERSIST_SINGLE)
425 >                        error(USER, "use -PP option for multiple processes");
426 >                if (persist_state == PERSIST_NONE) {
427 >                        rtargv[rtargc++] = "-PP";
428 >                        rtargv[rtargc++] = mktemp(persistfn);
429 >                        persist_state = PERSIST_OURS;
430 >                }
431 >        }
432                                  /* add format string */
433          sprintf(fmt, "-f%cf", inpfmt);
434          rtargv[rtargc++] = fmt;
435                                  /* octree argument is last */
436 <        rtargv[rtargc++] = octree = argv[argc-1];
436 >        if (i <= 0 || i != argc-1 || argv[i][0] == '-')
437 >                error(USER, "missing octree argument");
438 >        rtargv[rtargc++] = octree = argv[i];
439          rtargv[rtargc] = NULL;
440 <                                /* start rtrace & sum contributions */
440 >                                /* start rtrace & recover if requested */
441          init(nprocs);
442 <        tracecontribs(stdin);
442 >                                /* compute contributions */
443 >        trace_contribs(stdin);
444 >                                /* clean up */
445          quit(0);
446   }
447  
448 + #ifndef SIGALRM
449 + #define SIGALRM SIGTERM
450 + #endif
451   /* kill persistent rtrace process */
452   static void
453   killpersist(void)
454   {
455          FILE    *fp = fopen(persistfn, "r");
456 <        int     pid;
456 >        RT_PID  pid;
457  
458          if (fp == NULL)
459                  return;
# Line 324 | Line 487 | quit(int status)
487   {
488          int     rtstat;
489  
490 <        if (rt0.next != NULL)           /* terminate persistent rtrace */
490 >        if (persist_state == PERSIST_OURS)  /* terminate waiting rtrace */
491                  killpersist();
492                                          /* clean up rtrace process(es) */
493          rtstat = done_rprocs(&rt0);
# Line 333 | Line 496 | quit(int status)
496          exit(status);                   /* flushes all output streams */
497   }
498  
499 < /* start rtrace and initialize buffers */
499 > /* start rtrace processes and initialize */
500   void
501   init(int np)
502   {
503          struct rtproc   *rtp;
504          int     i;
505          int     maxbytes;
506 +                                        /* make sure we have something to do */
507 +        if (!nmods)
508 +                error(USER, "No modifiers specified");
509                                          /* assign ray variables */
510          scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
511          scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
512                                          /* set up signal handling */
513 < #ifdef SIGPIPE /* not present on Windows */
513 >        signal(SIGINT, quit);
514 > #ifdef SIGHUP
515 >        signal(SIGHUP, quit);
516 > #endif
517 > #ifdef SIGTERM
518 >        signal(SIGTERM, quit);
519 > #endif
520 > #ifdef SIGPIPE
521          signal(SIGPIPE, quit);
522   #endif
523          rtp = &rt0;                     /* start rtrace process(es) */
# Line 360 | Line 533 | init(int np)
533                          error(SYSTEM, "cannot start rtrace process");
534                  if (maxbytes > treebufsiz)
535                          treebufsiz = maxbytes;
536 +                rtp->raynum = 0;
537                  rtp->bsiz = 0;
538                  rtp->buf = NULL;
539 <                rtp->raynum = 0;
539 >                rtp->nbr = 0;
540                  if (i == np)            /* last process? */
541                          break;
542                  if (i == 1)
# Line 375 | Line 549 | init(int np)
549          rtp->next = NULL;               /* terminate list */
550          if (yres > 0) {
551                  if (xres > 0)
552 <                        raysleft = xres*yres;
552 >                        raysleft = (unsigned long)xres*yres;
553                  else
554                          raysleft = yres;
555          } else
556                  raysleft = 0;
557          waitflush = xres;
558 +        if (!recover)
559 +                return;
560 +                                        /* recover previous values */
561 +        if (accumulate)
562 +                reload_output();
563 +        else
564 +                recover_output(stdin);
565   }
566  
567 + /* grow modifier to accommodate more bins */
568 + MODCONT *
569 + growmodifier(MODCONT *mp, int nb)
570 + {
571 +        if (nb <= mp->nbins)
572 +                return mp;
573 +        mp = (MODCONT *)realloc(mp, sizeof(MODCONT) + sizeof(DCOLOR)*(nb-1));
574 +        if (mp == NULL)
575 +                error(SYSTEM, "out of memory in growmodifier");
576 +        memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(nb-mp->nbins));
577 +        mp->nbins = nb;
578 +        return mp;
579 + }
580 +
581   /* add modifier to our list to track */
582   MODCONT *
583 < addmodifier(char *modn, char *outf, char *binv)
583 > addmodifier(char *modn, char *outf, char *binv, int bincnt)
584   {
585          LUENT   *lep = lu_find(&modconttab, modn);
586          MODCONT *mp;
587 +        int     i;
588          
589          if (lep->data != NULL) {
590                  sprintf(errmsg, "duplicate modifier '%s'", modn);
# Line 401 | Line 597 | addmodifier(char *modn, char *outf, char *binv)
597          mp = (MODCONT *)malloc(sizeof(MODCONT));
598          if (mp == NULL)
599                  error(SYSTEM, "out of memory in addmodifier");
404        lep->data = (char *)mp;
600          mp->outspec = outf;             /* XXX assumes static string */
601          mp->modname = modn;             /* XXX assumes static string */
602          if (binv != NULL)
# Line 410 | Line 605 | addmodifier(char *modn, char *outf, char *binv)
605                  mp->binv = eparse("0");
606          mp->nbins = 1;
607          setcolor(mp->cbin[0], 0., 0., 0.);
608 +        if (mp->binv->type == NUM)      /* assume one bin if constant */
609 +                bincnt = 1;
610 +        else if (bincnt > 1)
611 +                mp = growmodifier(mp, bincnt);
612 +        lep->data = (char *)mp;
613 +                                        /* allocate output streams */
614 +        for (i = bincnt; i-- > 0; )
615 +                getostream(mp->outspec, mp->modname, i, 1);
616          return mp;
617   }
618  
619 + /* add modifiers from a file list */
620 + void
621 + addmodfile(char *fname, char *outf, char *binv, int bincnt)
622 + {
623 +        char    *mname[MAXMODLIST];
624 +        int     i;
625 +                                        /* find the file & store strings */
626 +        if (wordfile(mname, getpath(fname, getrlibpath(), R_OK)) < 0) {
627 +                sprintf(errmsg, "cannot find modifier file '%s'", fname);
628 +                error(SYSTEM, errmsg);
629 +        }
630 +        for (i = 0; mname[i]; i++)      /* add each one */
631 +                addmodifier(mname[i], outf, binv, bincnt);
632 + }
633 +
634   /* put string to stderr */
635   void
636   eputs(char  *s)
# Line 428 | Line 646 | eputs(char  *s)
646          midline = s[strlen(s)-1] != '\n';
647   }
648  
649 + /* construct output file name and return flags whether modifier/bin present */
650 + int
651 + ofname(char *oname, const char *ospec, const char *mname, int bn)
652 + {
653 +        const char      *mnp = NULL;
654 +        const char      *bnp = NULL;
655 +        const char      *cp;
656 +        
657 +        if (ospec == NULL)
658 +                return -1;
659 +        for (cp = ospec; *cp; cp++)             /* check format position(s) */
660 +                if (*cp == '%') {
661 +                        do
662 +                                ++cp;
663 +                        while (isdigit(*cp));
664 +                        switch (*cp) {
665 +                        case '%':
666 +                                break;
667 +                        case 's':
668 +                                if (mnp != NULL)
669 +                                        return -1;
670 +                                mnp = cp;
671 +                                break;
672 +                        case 'd':
673 +                                if (bnp != NULL)
674 +                                        return -1;
675 +                                bnp = cp;
676 +                                break;
677 +                        default:
678 +                                return -1;
679 +                        }
680 +                }
681 +        if (mnp != NULL) {                      /* create file name */
682 +                if (bnp != NULL) {
683 +                        if (bnp > mnp)
684 +                                sprintf(oname, ospec, mname, bn);
685 +                        else
686 +                                sprintf(oname, ospec, bn, mname);
687 +                        return OF_MODIFIER|OF_BIN;
688 +                }
689 +                sprintf(oname, ospec, mname);
690 +                return OF_MODIFIER;
691 +        }
692 +        if (bnp != NULL) {
693 +                sprintf(oname, ospec, bn);
694 +                return OF_BIN;
695 +        }
696 +        strcpy(oname, ospec);
697 +        return 0;
698 + }
699 +
700   /* write header to the given output stream */
701   void
702 < printheader(FILE *fout)
702 > printheader(FILE *fout, const char *info)
703   {
704          extern char     VersionID[];
705          FILE            *fin = fopen(octree, "r");
706          
707          if (fin == NULL)
708                  quit(1);
709 <        getheader(fin, (gethfunc *)fputs, fout);        /* copy octree header */
709 >        checkheader(fin, "ignore", fout);       /* copy octree header */
710          fclose(fin);
711          printargs(gargc-1, gargv, fout);        /* add our command */
712          fprintf(fout, "SOFTWARE= %s\n", VersionID);
713          fputnow(fout);
714 +        if (info != NULL)                       /* add extra info if given */
715 +                fputs(info, fout);
716          switch (outfmt) {                       /* add output format */
717          case 'a':
718                  fputformat("ascii", fout);
# Line 457 | Line 728 | printheader(FILE *fout)
728                  break;
729          }
730          fputc('\n', fout);
731 <        if (xres > 0) {
732 <                if (yres > 0)                   /* resolution string */
733 <                        fprtresolu(xres, yres, fout);
731 > }
732 >
733 > /* write resolution string to given output stream */
734 > void
735 > printresolu(FILE *fout, int xr, int yr)
736 > {
737 >        if ((xr > 0) & (yr > 0))        /* resolution string */
738 >                fprtresolu(xr, yr, fout);
739 >        if (xres > 0)                   /* global flush flag */
740                  fflush(fout);
464        }
741   }
742  
743 < /* Get output file pointer (open and write header if new) */
744 < FILE *
745 < getofile(const char *ospec, const char *mname, int bn)
743 > /* Get output stream pointer (open and write header if new and noopen==0) */
744 > STREAMOUT *
745 > getostream(const char *ospec, const char *mname, int bn, int noopen)
746   {
747 <        static int      using_stdout = 0;
748 <        const char      *mnp = NULL;
749 <        const char      *bnp = NULL;
750 <        const char      *cp;
751 <        char            ofname[1024];
752 <        LUENT           *lep;
747 >        static const DCOLOR     nocontrib = BLKCOLOR;
748 >        static STREAMOUT        stdos;
749 >        int                     ofl;
750 >        char                    oname[1024];
751 >        LUENT                   *lep;
752 >        STREAMOUT               *sop;
753          
754          if (ospec == NULL) {                    /* use stdout? */
755 <                if (!using_stdout && header)
756 <                        printheader(stdout);
757 <                using_stdout = 1;
758 <                return stdout;
755 >                if (!noopen && !using_stdout) {
756 >                        if (outfmt != 'a')
757 >                                SET_FILE_BINARY(stdout);
758 >                        if (header)
759 >                                printheader(stdout, NULL);
760 >                        printresolu(stdout, xres, yres);
761 >                        stdos.xr = xres; stdos.yr = yres;
762 >                        using_stdout = 1;
763 >                }
764 >                stdos.ofp = stdout;
765 >                stdos.reclen += noopen;
766 >                return &stdos;
767          }
768 <        for (cp = ospec; *cp; cp++)             /* check format position(s) */
769 <                if (*cp == '%') {
770 <                        do
771 <                                ++cp;
772 <                        while (isdigit(*cp));
773 <                        switch (*cp) {
774 <                        case '%':
775 <                                break;
776 <                        case 's':
777 <                                if (mnp != NULL)
778 <                                        goto badspec;
779 <                                mnp = cp;
780 <                                break;
781 <                        case 'd':
782 <                                if (bnp != NULL)
783 <                                        goto badspec;
784 <                                bnp = cp;
785 <                                break;
786 <                        default:
787 <                                goto badspec;
768 >        ofl = ofname(oname, ospec, mname, bn);  /* get output name */
769 >        if (ofl < 0) {
770 >                sprintf(errmsg, "bad output format '%s'", ospec);
771 >                error(USER, errmsg);
772 >        }
773 >        lep = lu_find(&ofiletab, oname);        /* look it up */
774 >        if (lep->key == NULL)                   /* new entry */
775 >                lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
776 >        sop = (STREAMOUT *)lep->data;
777 >        if (sop == NULL) {                      /* allocate stream */
778 >                sop = (STREAMOUT *)malloc(sizeof(STREAMOUT));
779 >                if (sop == NULL)
780 >                        error(SYSTEM, "out of memory in getostream");
781 >                sop->outpipe = oname[0] == '!';
782 >                sop->reclen = 0;
783 >                sop->ofp = NULL;                /* open iff noopen==0 */
784 >                sop->xr = xres; sop->yr = yres;
785 >                lep->data = (char *)sop;
786 >                if (!sop->outpipe & !force_open & !recover &&
787 >                                access(oname, F_OK) == 0) {
788 >                        errno = EEXIST;         /* file exists */
789 >                        goto openerr;
790 >                }
791 >        }
792 >        if (!noopen && sop->ofp == NULL) {      /* open output stream */
793 >                long            i;
794 >                if (oname[0] == '!')            /* output to command */
795 >                        sop->ofp = popen(oname+1, "w");
796 >                else                            /* else open file */
797 >                        sop->ofp = fopen(oname, "w");
798 >                if (sop->ofp == NULL)
799 >                        goto openerr;
800 >                if (outfmt != 'a')
801 >                        SET_FILE_BINARY(sop->ofp);
802 >                if (header) {
803 >                        char    info[512];
804 >                        char    *cp = info;
805 >                        if (ofl & OF_MODIFIER || sop->reclen == 1) {
806 >                                sprintf(cp, "MODIFIER=%s\n", mname);
807 >                                while (*cp) ++cp;
808                          }
809 +                        if (ofl & OF_BIN) {
810 +                                sprintf(cp, "BIN=%d\n", bn);
811 +                                while (*cp) ++cp;
812 +                        }
813 +                        *cp = '\0';
814 +                        printheader(sop->ofp, info);
815                  }
816 <        if (mnp != NULL) {                      /* create file name */
817 <                if (bnp != NULL) {
508 <                        if (bnp > mnp)
509 <                                sprintf(ofname, ospec, mname, bn);
510 <                        else
511 <                                sprintf(ofname, ospec, bn, mname);
512 <                } else
513 <                        sprintf(ofname, ospec, mname);
514 <        } else if (bnp != NULL)
515 <                sprintf(ofname, ospec, bn);
516 <        else
517 <                strcpy(ofname, ospec);
518 <        lep = lu_find(&ofiletab, ofname);       /* look it up */
519 <        if (lep->key == NULL)                   /* new entry */
520 <                lep->key = strcpy((char *)malloc(strlen(ofname)+1), ofname);
521 <        if (lep->data == NULL) {                /* open output file */
522 <                lep->data = (char *)fopen(ofname, "w");
523 <                if (lep->data == NULL) {
524 <                        sprintf(errmsg, "cannot open '%s' for writing", ofname);
525 <                        error(SYSTEM, errmsg);
816 >                if (!accumulate) {              /* global res. for -c- */
817 >                        sop->xr = xres; sop->yr = yres;
818                  }
819 <                if (header)
820 <                        printheader((FILE *)lep->data);
819 >                printresolu(sop->ofp, sop->xr, sop->yr);
820 >                                                /* play catch-up */
821 >                for (i = accumulate ? 0 : lastdone; i--; ) {
822 >                        int     j = sop->reclen;
823 >                        if (j <= 0) j = 1;
824 >                        while (j--)
825 >                                put_contrib(nocontrib, sop->ofp);
826 >                        if (outfmt == 'a')
827 >                                putc('\n', sop->ofp);
828 >                }
829 >                if (xres > 0)
830 >                        fflush(sop->ofp);
831          }
832 <        return (FILE *)lep->data;               /* return open file pointer */
833 < badspec:
834 <        sprintf(errmsg, "bad output format '%s'", ospec);
835 <        error(USER, errmsg);
836 <        return NULL;            /* pro forma return */
832 >        sop->reclen += noopen;                  /* add to length if noopen */
833 >        return sop;                             /* return output stream */
834 > openerr:
835 >        sprintf(errmsg, "cannot open '%s' for writing", oname);
836 >        error(SYSTEM, errmsg);
837 >        return NULL;    /* pro forma return */
838   }
839  
840   /* read input ray into buffer */
841   int
842   getinp(char *buf, FILE *fp)
843   {
844 +        double  dv[3], *dvp;
845 +        float   *fvp;
846 +        char    *cp;
847 +        int     i;
848 +
849          switch (inpfmt) {
850          case 'a':
851 <                if (fgets(buf, 128, fp) == NULL)
852 <                        return 0;
851 >                cp = buf;               /* make sure we get 6 floats */
852 >                for (i = 0; i < 6; i++) {
853 >                        if (fgetword(cp, buf+127-cp, fp) == NULL)
854 >                                return -1;
855 >                        if (i >= 3)
856 >                                dv[i-3] = atof(cp);
857 >                        if ((cp = fskip(cp)) == NULL || *cp)
858 >                                return -1;
859 >                        *cp++ = ' ';
860 >                }
861 >                getc(fp);               /* get/put eol */
862 >                *cp-- = '\0'; *cp = '\n';
863 >                if (DOT(dv,dv) <= FTINY*FTINY)
864 >                        return 0;       /* dummy ray */
865                  return strlen(buf);
866          case 'f':
867                  if (fread(buf, sizeof(float), 6, fp) < 6)
868 <                        return 0;
868 >                        return -1;
869 >                fvp = (float *)buf + 3;
870 >                if (DOT(fvp,fvp) <= FTINY*FTINY)
871 >                        return 0;       /* dummy ray */
872                  return sizeof(float)*6;
873          case 'd':
874                  if (fread(buf, sizeof(double), 6, fp) < 6)
875 <                        return 0;
875 >                        return -1;
876 >                dvp = (double *)buf + 3;
877 >                if (DOT(dvp,dvp) <= FTINY*FTINY)
878 >                        return 0;       /* dummy ray */
879                  return sizeof(double)*6;
880          }
881          error(INTERNAL, "botched input format");
882 <        return 0;       /* pro forma return */
882 >        return -1;      /* pro forma return */
883   }
884  
885 < static const float      *rparams = NULL;        /* ray parameter pointer */
885 > static float    rparams[9];             /* traced ray parameters */
886  
887   /* return channel (ray) value */
888   double
# Line 564 | Line 890 | chanvalue(int n)
890   {
891          if (--n < 0 || n >= 6)
892                  error(USER, "illegal channel number ($N)");
893 <        if (rparams == NULL)
568 <                error(USER, "illegal use of $N in constant expression");
569 <        return rparams[n];
893 >        return rparams[n+3];
894   }
895  
896 < /* add ray contribution to the appropriate modifier bin */
896 > /* add current ray contribution to the appropriate modifier bin */
897   void
898 < add_contrib(const char *modn, float rayval[9])
898 > add_contrib(const char *modn)
899   {
900          LUENT   *le = lu_find(&modconttab, modn);
901          MODCONT *mp = (MODCONT *)le->data;
# Line 581 | Line 905 | add_contrib(const char *modn, float rayval[9])
905                  sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
906                  error(USER, errmsg);
907          }
908 <        rparams = rayval + 3;           /* for chanvalue */
585 <        eclock++;
908 >        eclock++;                       /* get bin number */
909          bn = (int)(evalue(mp->binv) + .5);
910          if (bn <= 0)
911                  bn = 0;
912 <        else if (bn > mp->nbins) {      /* new bin */
913 <                mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
914 <                                                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;
912 >        else if (bn >= mp->nbins)       /* new bin */
913 >                le->data = (char *)(mp = growmodifier(mp, bn+1));
914 >        addcolor(mp->cbin[bn], rparams);
915   }
916  
917   /* output newline to ASCII file and/or flush as requested */
918   static int
919   puteol(const LUENT *e, void *p)
920   {
921 <        FILE    *fp = (FILE *)e->data;
921 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
922  
923          if (outfmt == 'a')
924 <                putc('\n', fp);
924 >                putc('\n', sop->ofp);
925          if (!waitflush)
926 <                fflush(fp);
927 <        if (ferror(fp)) {
926 >                fflush(sop->ofp);
927 >        if (ferror(sop->ofp)) {
928                  sprintf(errmsg, "write error on file '%s'", e->key);
929                  error(SYSTEM, errmsg);
930          }
931          return 0;
932   }
933  
934 < /* output ray tallies and clear for next primary */
934 > /* put out ray contribution to file */
935   void
936 < done_contrib(void)
936 > put_contrib(const DCOLOR cnt, FILE *fout)
937   {
938 <        int     i, j;
624 <        MODCONT *mp;
625 <        FILE    *fout;
626 <        double  dv[3];
938 >        float   fv[3];
939          COLR    cv;
940 +
941 +        switch (outfmt) {
942 +        case 'a':
943 +                fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
944 +                break;
945 +        case 'f':
946 +                copycolor(fv, cnt);
947 +                fwrite(fv, sizeof(float), 3, fout);
948 +                break;
949 +        case 'd':
950 +                fwrite(cnt, sizeof(double), 3, fout);
951 +                break;
952 +        case 'c':
953 +                setcolr(cv, cnt[0], cnt[1], cnt[2]);
954 +                fwrite(cv, sizeof(cv), 1, fout);
955 +                break;
956 +        default:
957 +                error(INTERNAL, "botched output format");
958 +        }
959 + }
960 +
961 + /* output ray tallies and clear for next accumulation */
962 + void
963 + done_contrib(void)
964 + {
965 +        int             i, j;
966 +        MODCONT         *mp;
967 +        STREAMOUT       *sop;
968                                                  /* output modifiers in order */
969          for (i = 0; i < nmods; i++) {
970                  mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
971 <                for (j = 0; j < mp->nbins; j++) {
972 <                        fout = getofile(mp->outspec, mp->modname, j);
973 <                        switch (outfmt) {
974 <                        case 'a':
975 <                                fprintf(fout, "%.6e\t%.6e\t%.6e\t",
976 <                                                mp->cbin[j][RED],
977 <                                                mp->cbin[j][GRN],
978 <                                                mp->cbin[j][BLU]);
979 <                                break;
980 <                        case 'f':
981 <                                fwrite(mp->cbin[j], sizeof(float), 3, fout);
982 <                                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 <                }
658 <                                                /* clear for next ray tree */
659 <                memset(mp->cbin, 0, sizeof(COLOR)*mp->nbins);
971 >                sop = getostream(mp->outspec, mp->modname, 0,0);
972 >                put_contrib(mp->cbin[0], sop->ofp);
973 >                if (mp->nbins > 3 &&            /* minor optimization */
974 >                                sop == getostream(mp->outspec, mp->modname, 1,0))
975 >                        for (j = 1; j < mp->nbins; j++)
976 >                                put_contrib(mp->cbin[j], sop->ofp);
977 >                else
978 >                        for (j = 1; j < mp->nbins; j++)
979 >                                put_contrib(mp->cbin[j],
980 >                                    getostream(mp->outspec,mp->modname,j,0)->ofp);
981 >                                                /* clear for next time */
982 >                memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
983          }
984          --waitflush;                            /* terminate records */
985          lu_doall(&ofiletab, puteol, NULL);
986 <        if (!waitflush)
986 >        if (using_stdout & (outfmt == 'a'))
987 >                putc('\n', stdout);
988 >        if (!waitflush) {
989                  waitflush = xres;
990 +                if (using_stdout)
991 +                        fflush(stdout);
992 +        }
993   }
994  
995 < /* process (or save) ray tree produced by rtrace process */
995 > /* queue completed ray tree produced by rtrace process */
996   void
997 < process_rays(struct rtproc *rtp)
997 > queue_raytree(struct rtproc *rtp)
998   {
999 <        struct rtproc   *rtu;
1000 <                                        /* check if time to process it */
1001 <        if (rtp->raynum == lastdone+1) {
1002 <                int             n = rtp->bpos - rtp->buf;
999 >        struct rtproc   *rtu, *rtl = NULL;
1000 >                                        /* insert following ray order */
1001 >        for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
1002 >                if (rtp->raynum < rtu->raynum)
1003 >                        break;
1004 >        rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
1005 >        if (rtu == NULL)
1006 >                error(SYSTEM, "out of memory in queue_raytree");
1007 >        *rtu = *rtp;
1008 >        if (rtl == NULL) {
1009 >                rtu->next = rt_unproc;
1010 >                rt_unproc = rtu;
1011 >        } else {
1012 >                rtu->next = rtl->next;
1013 >                rtl->next = rtu;
1014 >        }
1015 >        rtp->raynum = 0;                /* clear path for next ray tree */
1016 >        rtp->bsiz = 0;
1017 >        rtp->buf = NULL;
1018 >        rtp->nbr = 0;
1019 > }
1020 >
1021 > /* process completed ray trees from our queue */
1022 > void
1023 > process_queue(void)
1024 > {
1025 >        char    modname[128];
1026 >                                        /* ray-ordered queue */
1027 >        while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
1028 >                struct rtproc   *rtp = rt_unproc;
1029 >                int             n = rtp->nbr;
1030                  const char      *cp = rtp->buf;
1031                  while (n > 0) {         /* process rays */
1032 <                        char    matname[128];
678 <                        char    *mnp = matname;
1032 >                        register char   *mnp = modname;
1033                                          /* skip leading tabs */
1034                          while (n > 0 && *cp == '\t') {
1035                                  cp++; n--;
1036                          }
1037 <                                        /* get material name */
1038 <                        while (n > 0 && *cp != '\t') {
1037 >                        if (!n || !(isalpha(*cp) | (*cp == '_')))
1038 >                                error(USER, "bad modifier name from rtrace");
1039 >                                        /* get modifier name */
1040 >                        while (n > 1 && *cp != '\t') {
1041 >                                if (mnp - modname >= sizeof(modname)-2)
1042 >                                        error(INTERNAL, "modifier name too long");
1043                                  *mnp++ = *cp++; n--;
1044                          }
687                        if (!n)
688                                error(USER, "botched modifer name from rtrace");
1045                          *mnp = '\0';
1046 <                        cp++; n--;      /* skip terminating tab */
1046 >                        cp++; n--;      /* eat following tab */
1047                          if (n < (int)(sizeof(float)*9))
1048                                  error(USER, "incomplete ray value from rtrace");
1049                                          /* add ray contribution */
1050 <                        add_contrib(matname, (float *)cp);
1050 >                        memcpy(rparams, cp, sizeof(float)*9);
1051                          cp += sizeof(float)*9; n -= sizeof(float)*9;
1052 +                        add_contrib(modname);
1053                  }
1054 <                done_contrib();         /* sum up contributions & output */
1054 >                if (!accumulate)
1055 >                        done_contrib(); /* sum up contributions & output */
1056                  lastdone = rtp->raynum;
1057 <                free(rtp->buf);
1058 <                                        /* catch up with unprocessed list */
1059 <                while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
1060 <                        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 <                }
1057 >                if (rtp->buf != NULL)   /* free up buffer space */
1058 >                        free(rtp->buf);
1059 >                rt_unproc = rtp->next;
1060 >                free(rtp);              /* done with this ray tree */
1061          }
723        rtp->raynum = 0;                /* clear path for next ray tree */
724        rtp->bsiz = 0;
725        rtp->buf = NULL;
1062   }
1063  
1064   /* wait for rtrace process to finish with ray tree */
# Line 763 | Line 1099 | wait_rproc(void)
1099                          if (rt->buf == NULL) {
1100                                  rt->bsiz = treebufsiz;
1101                                  rt->buf = (char *)malloc(treebufsiz);
1102 <                        } else if (rt->bpos + BUFSIZ > rt->buf + rt->bsiz) {
1102 >                        } else if (rt->nbr + BUFSIZ > rt->bsiz) {
1103                                  if (rt->bsiz + BUFSIZ <= treebufsiz)
1104                                          rt->bsiz = treebufsiz;
1105                                  else
1106 <                                        rt->bsiz = treebufsiz += BUFSIZ;
1106 >                                        treebufsiz = rt->bsiz += BUFSIZ;
1107                                  rt->buf = (char *)realloc(rt->buf, rt->bsiz);
1108                          }
1109                          if (rt->buf == NULL)
1110                                  error(SYSTEM, "out of memory in wait_rproc");
1111 <                        nr = read(rt->pd.r, rt->bpos,
1112 <                                        rt->buf + rt->bsiz - rt->bpos);
777 <                        if (!nr)
1111 >                        nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
1112 >                        if (nr <= 0)
1113                                  error(USER, "rtrace process died");
1114 <                        rt->bpos += nr;         /* advance buffer & check */
1115 <                        if (rt->bpos[-1] == '\t' && rt->bpos[-2] == '-') {
1116 <                                rt->bpos -= 2;  /* elide terminator */
1117 <                                process_rays(rt);
1114 >                        rt->nbr += nr;          /* advance & check */
1115 >                        if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
1116 >                                                        "~\t~\t", 4)) {
1117 >                                rt->nbr -= 4;   /* elide terminator */
1118 >                                queue_raytree(rt);
1119                                  rtfree = rt;    /* ready for next ray */
1120                          }
1121                  }
# Line 801 | Line 1137 | get_rproc(void)
1137  
1138   /* trace ray contributions (main loop) */
1139   void
1140 < tracecontribs(FILE *fin)
1140 > trace_contribs(FILE *fin)
1141   {
1142          char            inpbuf[128];
1143          int             iblen;
1144          struct rtproc   *rtp;
1145                                                  /* loop over input */
1146 <        while ((iblen = getinp(inpbuf, fin)) > 0) {
1147 <                if (lastray+1 < lastray) {      /* counter rollover? */
1146 >        while ((iblen = getinp(inpbuf, fin)) >= 0) {
1147 >                if (!iblen ||                   /* need reset? */
1148 >                                queue_length() > 10*nrtprocs() ||
1149 >                                lastray+1 < lastray) {
1150                          while (wait_rproc() != NULL)
1151 <                                ;
1152 <                        lastdone = lastray = 0;
1151 >                                process_queue();
1152 >                        if (lastray+1 < lastray)
1153 >                                lastdone = lastray = 0;
1154                  }
1155                  rtp = get_rproc();              /* get avail. rtrace process */
1156 <                rtp->raynum = ++lastray;        /* assign this ray to it */
1157 <                writebuf(rtp->pd.w, inpbuf, iblen);
1158 <                if (!--raysleft)
1159 <                        break;                  /* explicit EOF */
1156 >                rtp->raynum = ++lastray;        /* assign ray */
1157 >                if (iblen) {                    /* trace ray if valid */
1158 >                        writebuf(rtp->pd.w, inpbuf, iblen);
1159 >                } else {                        /* else bypass dummy ray */
1160 >                        queue_raytree(rtp);     /* empty tree */
1161 >                        if ((yres <= 0) | (waitflush > 1))
1162 >                                waitflush = 1;  /* flush after this */
1163 >                }
1164 >                process_queue();                /* catch up with results */
1165 >                if (raysleft && !--raysleft)
1166 >                        break;                  /* preemptive EOI */
1167          }
1168          while (wait_rproc() != NULL)            /* process outstanding rays */
1169 <                ;
1169 >                process_queue();
1170 >        if (accumulate)
1171 >                done_contrib();                 /* output tallies */
1172 >        if (raysleft)
1173 >                error(USER, "unexpected EOF on input");
1174 >        lu_done(&ofiletab);                     /* close output files */
1175 > }
1176 >
1177 > /* get ray contribution from previous file */
1178 > static int
1179 > get_contrib(DCOLOR cnt, FILE *finp)
1180 > {
1181 >        COLOR   fv;
1182 >        COLR    cv;
1183 >
1184 >        switch (outfmt) {
1185 >        case 'a':
1186 >                return(fscanf(finp,"%lf %lf %lf",&cnt[0],&cnt[1],&cnt[2]) == 3);
1187 >        case 'f':
1188 >                if (fread(fv, sizeof(fv[0]), 3, finp) != 3)
1189 >                        return(0);
1190 >                copycolor(cnt, fv);
1191 >                return(1);
1192 >        case 'd':
1193 >                return(fread(cnt, sizeof(cnt[0]), 3, finp) == 3);
1194 >        case 'c':
1195 >                if (fread(cv, sizeof(cv), 1, finp) != 1)
1196 >                        return(0);
1197 >                colr_color(fv, cv);
1198 >                copycolor(cnt, fv);
1199 >                return(1);
1200 >        default:
1201 >                error(INTERNAL, "botched output format");
1202 >        }
1203 >        return(0);      /* pro forma return */
1204 > }
1205 >
1206 > /* close output file opened for input */
1207 > static int
1208 > myclose(const LUENT *e, void *p)
1209 > {
1210 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1211 >        
1212 >        if (sop->ofp == NULL)
1213 >                return;
1214 >        fclose(sop->ofp);
1215 >        sop->ofp = NULL;
1216 > }
1217 >
1218 > /* load previously accumulated values */
1219 > void
1220 > reload_output(void)
1221 > {
1222 >        int             i, j;
1223 >        MODCONT         *mp;
1224 >        int             ofl;
1225 >        char            oname[1024];
1226 >        char            *fmode = "rb";
1227 >        char            *outvfmt;
1228 >        LUENT           *ment, *oent;
1229 >        int             xr, yr;
1230 >        STREAMOUT       sout;
1231 >        DCOLOR          rgbv;
1232 >
1233 >        switch (outfmt) {
1234 >        case 'a':
1235 >                outvfmt = "ascii";
1236 >                fmode = "r";
1237 >                break;
1238 >        case 'f':
1239 >                outvfmt = "float";
1240 >                break;
1241 >        case 'd':
1242 >                outvfmt = "double";
1243 >                break;
1244 >        case 'c':
1245 >                outvfmt = COLRFMT;
1246 >                break;
1247 >        default:
1248 >                error(INTERNAL, "botched output format");
1249 >                return;
1250 >        }
1251 >                                                /* reload modifier values */
1252 >        for (i = 0; i < nmods; i++) {
1253 >                ment = lu_find(&modconttab,modname[i]);
1254 >                mp = (MODCONT *)ment->data;
1255 >                if (mp->outspec == NULL)
1256 >                        error(USER, "cannot reload from stdout");
1257 >                if (mp->outspec[0] == '!')
1258 >                        error(USER, "cannot reload from command");
1259 >                for (j = 0; ; j++) {            /* load each modifier bin */
1260 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1261 >                        if (ofl < 0)
1262 >                                error(USER, "bad output file specification");
1263 >                        oent = lu_find(&ofiletab, oname);
1264 >                        if (oent->data != NULL) {
1265 >                                sout = *(STREAMOUT *)oent->data;
1266 >                        } else {
1267 >                                sout.reclen = 0;
1268 >                                sout.outpipe = 0;
1269 >                                sout.xr = xres; sout.yr = yres;
1270 >                                sout.ofp = NULL;
1271 >                        }
1272 >                        if (sout.ofp == NULL) { /* open output as input */
1273 >                                sout.ofp = fopen(oname, fmode);
1274 >                                if (sout.ofp == NULL) {
1275 >                                        if (j)
1276 >                                                break;  /* assume end of modifier */
1277 >                                        sprintf(errmsg, "missing reload file '%s'",
1278 >                                                        oname);
1279 >                                        error(WARNING, errmsg);
1280 >                                        break;
1281 >                                }
1282 >                                if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1283 >                                        sprintf(errmsg, "format mismatch for '%s'",
1284 >                                                        oname);
1285 >                                        error(USER, errmsg);
1286 >                                }
1287 >                                if ((sout.xr > 0) & (sout.yr > 0) &&
1288 >                                                (!fscnresolu(&xr, &yr, sout.ofp) ||
1289 >                                                        (xr != sout.xr) |
1290 >                                                        (yr != sout.yr))) {
1291 >                                        sprintf(errmsg, "resolution mismatch for '%s'",
1292 >                                                        oname);
1293 >                                        error(USER, errmsg);
1294 >                                }
1295 >                        }
1296 >                                                        /* read in RGB value */
1297 >                        if (!get_contrib(rgbv, sout.ofp)) {
1298 >                                if (!j) {
1299 >                                        fclose(sout.ofp);
1300 >                                        break;          /* ignore empty file */
1301 >                                }
1302 >                                if (j < mp->nbins) {
1303 >                                        sprintf(errmsg, "missing data in '%s'",
1304 >                                                        oname);
1305 >                                        error(USER, errmsg);
1306 >                                }
1307 >                                break;
1308 >                        }
1309 >                        if (j >= mp->nbins)             /* grow modifier size */
1310 >                                ment->data = (char *)(mp = growmodifier(mp, j+1));
1311 >                        copycolor(mp->cbin[j], rgbv);
1312 >                        if (oent->key == NULL)          /* new file entry */
1313 >                                oent->key = strcpy((char *)
1314 >                                                malloc(strlen(oname)+1), oname);
1315 >                        if (oent->data == NULL)
1316 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1317 >                        *(STREAMOUT *)oent->data = sout;
1318 >                }
1319 >        }
1320 >        lu_doall(&ofiletab, myclose, NULL);     /* close all files */
1321 > }
1322 >
1323 > /* seek on the given output file */
1324 > static int
1325 > myseeko(const LUENT *e, void *p)
1326 > {
1327 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1328 >        off_t           nbytes = *(off_t *)p;
1329 >        
1330 >        if (sop->reclen > 1)
1331 >                nbytes = nbytes * sop->reclen;
1332 >        if (fseeko(sop->ofp, nbytes, SEEK_CUR) < 0) {
1333 >                sprintf(errmsg, "seek error on file '%s'", e->key);
1334 >                error(SYSTEM, errmsg);
1335 >        }
1336 >        return 0;
1337 > }
1338 >
1339 > /* recover output if possible */
1340 > void
1341 > recover_output(FILE *fin)
1342 > {
1343 >        off_t           lastout = -1;
1344 >        int             outvsiz, recsiz;
1345 >        char            *outvfmt;
1346 >        int             i, j;
1347 >        MODCONT         *mp;
1348 >        int             ofl;
1349 >        char            oname[1024];
1350 >        LUENT           *ment, *oent;
1351 >        STREAMOUT       sout;
1352 >        off_t           nvals;
1353 >        int             xr, yr;
1354 >
1355 >        switch (outfmt) {
1356 >        case 'a':
1357 >                error(USER, "cannot recover ASCII output");
1358 >                return;
1359 >        case 'f':
1360 >                outvsiz = sizeof(float)*3;
1361 >                outvfmt = "float";
1362 >                break;
1363 >        case 'd':
1364 >                outvsiz = sizeof(double)*3;
1365 >                outvfmt = "double";
1366 >                break;
1367 >        case 'c':
1368 >                outvsiz = sizeof(COLR);
1369 >                outvfmt = COLRFMT;
1370 >                break;
1371 >        default:
1372 >                error(INTERNAL, "botched output format");
1373 >                return;
1374 >        }
1375 >                                                /* check modifier outputs */
1376 >        for (i = 0; i < nmods; i++) {
1377 >                ment = lu_find(&modconttab,modname[i]);
1378 >                mp = (MODCONT *)ment->data;
1379 >                if (mp->outspec == NULL)
1380 >                        error(USER, "cannot recover from stdout");
1381 >                if (mp->outspec[0] == '!')
1382 >                        error(USER, "cannot recover from command");
1383 >                for (j = 0; ; j++) {            /* check each bin's file */
1384 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1385 >                        if (ofl < 0)
1386 >                                error(USER, "bad output file specification");
1387 >                        oent = lu_find(&ofiletab, oname);
1388 >                        if (oent->data != NULL) {
1389 >                                sout = *(STREAMOUT *)oent->data;
1390 >                        } else {
1391 >                                sout.reclen = 0;
1392 >                                sout.outpipe = 0;
1393 >                                sout.ofp = NULL;
1394 >                        }
1395 >                        if (sout.ofp != NULL) { /* already open? */
1396 >                                if (ofl & OF_BIN)
1397 >                                        continue;
1398 >                                break;
1399 >                        }
1400 >                                                /* open output */
1401 >                        sout.ofp = fopen(oname, "rb+");
1402 >                        if (sout.ofp == NULL) {
1403 >                                if (j)
1404 >                                        break;  /* assume end of modifier */
1405 >                                sprintf(errmsg, "missing recover file '%s'",
1406 >                                                oname);
1407 >                                error(WARNING, errmsg);
1408 >                                break;
1409 >                        }
1410 >                        nvals = lseek(fileno(sout.ofp), 0, SEEK_END);
1411 >                        if (nvals <= 0) {
1412 >                                lastout = 0;    /* empty output, quit here */
1413 >                                fclose(sout.ofp);
1414 >                                break;
1415 >                        }
1416 >                        if (!sout.reclen) {
1417 >                                if (!(ofl & OF_BIN)) {
1418 >                                        sprintf(errmsg,
1419 >                                                "need -bn to recover file '%s'",
1420 >                                                        oname);
1421 >                                        error(USER, errmsg);
1422 >                                }
1423 >                                recsiz = outvsiz;
1424 >                        } else
1425 >                                recsiz = outvsiz * sout.reclen;
1426 >
1427 >                        lseek(fileno(sout.ofp), 0, SEEK_SET);
1428 >                        if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1429 >                                sprintf(errmsg, "format mismatch for '%s'",
1430 >                                                oname);
1431 >                                error(USER, errmsg);
1432 >                        }
1433 >                        sout.xr = xres; sout.yr = yres;
1434 >                        if ((sout.xr > 0) & (sout.yr > 0) &&
1435 >                                        (!fscnresolu(&xr, &yr, sout.ofp) ||
1436 >                                                (xr != sout.xr) |
1437 >                                                (yr != sout.yr))) {
1438 >                                sprintf(errmsg, "resolution mismatch for '%s'",
1439 >                                                oname);
1440 >                                error(USER, errmsg);
1441 >                        }
1442 >                        nvals = (nvals - (off_t)ftell(sout.ofp)) / recsiz;
1443 >                        if ((lastout < 0) | (nvals < lastout))
1444 >                                lastout = nvals;
1445 >                        if (oent->key == NULL)  /* new entry */
1446 >                                oent->key = strcpy((char *)
1447 >                                                malloc(strlen(oname)+1), oname);
1448 >                        if (oent->data == NULL)
1449 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1450 >                        *(STREAMOUT *)oent->data = sout;
1451 >                        if (!(ofl & OF_BIN))
1452 >                                break;          /* no bin separation */
1453 >                }
1454 >                if (!lastout) {                 /* empty output */
1455 >                        error(WARNING, "no previous data to recover");
1456 >                        lu_done(&ofiletab);     /* reclose all outputs */
1457 >                        return;
1458 >                }
1459 >                if (j > mp->nbins)              /* reallocate modifier bins */
1460 >                        ment->data = (char *)(mp = growmodifier(mp, j));
1461 >        }
1462 >        if (lastout < 0) {
1463 >                error(WARNING, "no output files to recover");
1464 >                return;
1465 >        }
1466 >        if (raysleft && lastout >= raysleft) {
1467 >                error(WARNING, "output appears to be complete");
1468 >                /* XXX should read & discard input? */
1469 >                quit(0);
1470 >        }
1471 >                                                /* seek on all files */
1472 >        nvals = lastout * outvsiz;
1473 >        lu_doall(&ofiletab, myseeko, &nvals);
1474 >                                                /* skip repeated input */
1475 >        for (nvals = 0; nvals < lastout; nvals++)
1476 >                if (getinp(oname, fin) < 0)
1477 >                        error(USER, "unexpected EOF on input");
1478 >        lastray = lastdone = (unsigned long)lastout;
1479 >        if (raysleft)
1480 >                raysleft -= lastray;
1481   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines