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.62 by greg, Wed Apr 6 00:39:07 2011 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  
23 < #define MAXMODLIST      1024            /* maximum modifiers we'll track */
23 > size_t  treebufsiz = BUFSIZ;            /* current tree buffer size */
24  
25 < int     treebufsiz = BUFSIZ;            /* current tree buffer size */
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 >        size_t          bsiz;           /* ray tree buffer length */
96 >        char            *buf;           /* ray tree buffer */
97 >        size_t          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", ".9", "-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             force_open = 0;         /* truncate existing output? */
135 + int             recover = 0;            /* recover previous output? */
136 + int             accumulate = 1;         /* input rays per output record */
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 > int             account;                /* current accumulation count */
141 > unsigned long   raysleft;               /* number of rays left to trace */
142   long            waitflush;              /* how long until next flush */
143  
144   unsigned long   lastray = 0;            /* last ray number sent */
145   unsigned long   lastdone = 0;           /* last ray processed */
146  
147 + int             using_stdout = 0;       /* are we using stdout? */
148 +
149   const char      *modname[MAXMODLIST];   /* ordered modifier name list */
150   int             nmods = 0;              /* number of modifiers */
151  
152 < MODCONT *addmodifier(char *modn, char *outf, char *binv);
152 > #define queue_length()          (lastray - lastdone)
153  
154 < int done_rprocs(struct rtproc *rtp);
154 > MODCONT *growmodifier(MODCONT *mp, int nb);
155 > MODCONT *addmodifier(char *modn, char *outf, char *binv, int bincnt);
156 > void addmodfile(char *fname, char *outf, char *binv, int bincnt);
157 >
158   void init(int np);
159 < void tracecontribs(FILE *fp);
159 > int done_rprocs(struct rtproc *rtp);
160 > void reload_output(void);
161 > void recover_output(FILE *fin);
162 > void trace_contribs(FILE *fin);
163   struct rtproc *wait_rproc(void);
164   struct rtproc *get_rproc(void);
165 < void process_rays(struct rtproc *rtp);
165 > void queue_raytree(struct rtproc *rtp);
166 > void process_queue(void);
167  
168 < void add_contrib(const char *modn, float rayval[7]);
169 < void done_contrib(void);
168 > void put_contrib(const DCOLOR cnt, FILE *fout);
169 > void add_contrib(const char *modn);
170 > void done_contrib(int navg);
171  
172 + /* return number of open rtrace processes */
173 + static int
174 + nrtprocs(void)
175 + {
176 +        int     nrtp = 0;
177 +        struct rtproc   *rtp;
178 +
179 +        for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
180 +                nrtp += rtp->pd.running;
181 +        return(nrtp);
182 + }
183 +
184   /* set input/output format */
185   static void
186   setformat(const char *fmt)
187   {
188          switch (fmt[0]) {
129        case 'a':
189          case 'f':
190          case 'd':
191 +                SET_FILE_BINARY(stdin);
192 +                /* fall through */
193 +        case 'a':
194                  inpfmt = fmt[0];
195                  break;
196          default:
# Line 158 | Line 220 | fmterr:
220   int
221   main(int argc, char *argv[])
222   {
223 +        int     contrib = 0;
224          int     nprocs = 1;
225          char    *curout = NULL;
226          char    *binval = NULL;
227 <        int     i;
228 <                                /* set global argument list */
229 <        gargc = argc;
227 >        int     bincnt = 0;
228 >        char    fmt[8];
229 >        int     i, j;
230 >                                /* need at least one argument */
231 >        if (argc < 2) {
232 >                fprintf(stderr,
233 > "Usage: %s [-n nprocs][-V][-r][-e expr][-f source][-o ospec][-b binv] {-m mod | -M file} [rtrace options] octree\n",
234 >                        argv[0]);
235 >                exit(1);
236 >        }
237 >                                /* global program name */
238          gargv = argv;
239 <                                /* set up calcomp functions */
239 >                                /* initialize calcomp routines */
240          esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
241          esupport &= ~(E_OUTCHAN);
242 +        varset("PI", ':', PI);
243                                  /* get our options */
244 <        for (i = 1; i < argc && argv[i][0] == '-'; i++) {
245 <                switch (argv[i][1]) {
246 <                case 'n':                       /* number of processes */
247 <                        if (argv[i][2] || i >= argc-1) break;
248 <                        nprocs = atoi(argv[++i]);
249 <                        if (nprocs <= 0)
250 <                                error(USER, "illegal number of processes");
251 <                        continue;
252 <                case 'h':                       /* output header? */
253 <                        switch (argv[i][2]) {
254 <                        case '\0':
255 <                                header = !header;
244 >        for (i = 1; i < argc-1; i++) {
245 >                                                /* expand arguments */
246 >                while ((j = expandarg(&argc, &argv, i)) > 0)
247 >                        ;
248 >                if (j < 0) {
249 >                        fprintf(stderr, "%s: cannot expand '%s'\n",
250 >                                        argv[0], argv[i]);
251 >                        exit(1);
252 >                }
253 >                if (argv[i][0] == '-')
254 >                        switch (argv[i][1]) {
255 >                        case 'n':               /* number of processes */
256 >                                if (argv[i][2] || i >= argc-2) break;
257 >                                nprocs = atoi(argv[++i]);
258 >                                if (nprocs <= 0)
259 >                                        error(USER, "illegal number of processes");
260                                  continue;
261 <                        case '+': case '1': case 'T': case 't':
262 <                                header = 1;
261 >                        case 'V':               /* output contributions */
262 >                                switch (argv[i][2]) {
263 >                                case '\0':
264 >                                        contrib = !contrib;
265 >                                        continue;
266 >                                case '+': case '1':
267 >                                case 'T': case 't':
268 >                                case 'Y': case 'y':
269 >                                        contrib = 1;
270 >                                        continue;
271 >                                case '-': case '0':
272 >                                case 'F': case 'f':
273 >                                case 'N': case 'n':
274 >                                        contrib = 0;
275 >                                        continue;
276 >                                }
277 >                                break;
278 >                        case 'c':               /* input rays per output */
279 >                                if (argv[i][2] || i >= argc-2) break;
280 >                                accumulate = atoi(argv[++i]);
281                                  continue;
282 <                        case '-': case '0': case 'F': case 'f':
283 <                                header = 0;
282 >                        case 'r':               /* recover output */
283 >                                if (argv[i][2]) break;
284 >                                recover = 1;
285                                  continue;
286 <                        }
287 <                        break;
288 <                case 'f':                       /* file or i/o format */
289 <                        if (!argv[i][2]) {
290 <                                if (i >= argc-1) break;
291 <                                fcompile(argv[++i]);
286 >                        case 'h':               /* output header? */
287 >                                switch (argv[i][2]) {
288 >                                case '\0':
289 >                                        header = !header;
290 >                                        continue;
291 >                                case '+': case '1':
292 >                                case 'T': case 't':
293 >                                case 'Y': case 'y':
294 >                                        header = 1;
295 >                                        continue;
296 >                                case '-': case '0':
297 >                                case 'F': case 'f':
298 >                                case 'N': case 'n':
299 >                                        header = 0;
300 >                                        continue;
301 >                                }
302 >                                break;
303 >                        case 'f':               /* file or force or format */
304 >                                if (!argv[i][2]) {
305 >                                        char    *fpath;
306 >                                        if (i >= argc-2) break;
307 >                                        fpath = getpath(argv[++i],
308 >                                                        getrlibpath(), R_OK);
309 >                                        if (fpath == NULL) {
310 >                                                sprintf(errmsg,
311 >                                                        "cannot find file '%s'",
312 >                                                                argv[i]);
313 >                                                error(USER, errmsg);
314 >                                        }
315 >                                        fcompile(fpath);
316 >                                        continue;
317 >                                }
318 >                                if (argv[i][2] == 'o') {
319 >                                        force_open = 1;
320 >                                        continue;
321 >                                }
322 >                                setformat(argv[i]+2);
323                                  continue;
324 +                        case 'e':               /* expression */
325 +                                if (argv[i][2] || i >= argc-2) break;
326 +                                scompile(argv[++i], NULL, 0);
327 +                                continue;
328 +                        case 'o':               /* output file spec. */
329 +                                if (argv[i][2] || i >= argc-2) break;
330 +                                curout = argv[++i];
331 +                                continue;
332 +                        case 'x':               /* horiz. output resolution */
333 +                                if (argv[i][2] || i >= argc-2) break;
334 +                                xres = atoi(argv[++i]);
335 +                                continue;
336 +                        case 'y':               /* vert. output resolution */
337 +                                if (argv[i][2] || i >= argc-2) break;
338 +                                yres = atoi(argv[++i]);
339 +                                continue;
340 +                        case 'b':               /* bin expression/count */
341 +                                if (i >= argc-2) break;
342 +                                if (argv[i][2] == 'n') {
343 +                                        bincnt = (int)(eval(argv[++i]) + .5);
344 +                                        continue;
345 +                                }
346 +                                if (argv[i][2]) break;
347 +                                binval = argv[++i];
348 +                                continue;
349 +                        case 'm':               /* modifier name */
350 +                                if (argv[i][2] || i >= argc-2) break;
351 +                                rtargv[rtargc++] = "-ti";
352 +                                rtargv[rtargc++] = argv[++i];
353 +                                addmodifier(argv[i], curout, binval, bincnt);
354 +                                continue;
355 +                        case 'M':               /* modifier file */
356 +                                if (argv[i][2] || i >= argc-2) break;
357 +                                rtargv[rtargc++] = "-tI";
358 +                                rtargv[rtargc++] = argv[++i];
359 +                                addmodfile(argv[i], curout, binval, bincnt);
360 +                                continue;
361 +                        case 'P':               /* persist file */
362 +                                if (i >= argc-2) break;
363 +                                persist_state = (argv[i][2] == 'P') ?
364 +                                                PERSIST_PARALL : PERSIST_SINGLE;
365 +                                rtargv[rtargc++] = argv[i];
366 +                                rtargv[rtargc++] = argv[++i];
367 +                                continue;
368                          }
369 <                        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 */
369 >                rtargv[rtargc++] = argv[i];     /* assume rtrace option */
370          }
371 <        for ( ; i < argc; i++)  /* transfer rtrace-specific options */
372 <                rtargv[rtargc++] = argv[i];
373 <        if (!strcmp(rtargv[--rtargc], "-defaults"))
374 <                nprocs = 0;
238 <        if (nprocs > 1) {       /* add persist file if parallel invocation */
239 <                rtargv[rtargc++] = "-PP";
240 <                rtargv[rtargc++] = mktemp(persistfn);
241 <        }
371 >        if (accumulate <= 0)    /* no output flushing for single record */
372 >                xres = yres = 0;
373 >                                /* set global argument list */
374 >        gargc = argc; gargv = argv;
375                                  /* add "mandatory" rtrace settings */
376 <        for (i = 0; myrtopts[i] != NULL; i++)
377 <                rtargv[rtargc++] = myrtopts[i];
378 <        if (!nprocs) {          /* just asking for defaults? */
379 <                char    sxres[16], syres[16];
376 >        for (j = 0; myrtopts[j] != NULL; j++)
377 >                rtargv[rtargc++] = myrtopts[j];
378 >        rtargv[rtargc++] = contrib ? RTCONTRIB : RTCOEFF;
379 >                                /* just asking for defaults? */
380 >        if (!strcmp(argv[i], "-defaults")) {
381 >                char    nps[8], sxres[16], syres[16];
382                  char    *rtpath;
383 <                printf("-n  1\t\t\t\t# number of processes\n", nprocs);
383 >                printf("-c %-5d\t\t\t# accumulated rays per record\n",
384 >                                accumulate);
385 >                printf("-V%c\t\t\t\t# output %s\n", contrib ? '+' : '-',
386 >                                contrib ? "contributions" : "coefficients");
387                  fflush(stdout);                 /* report OUR options */
388 +                rtargv[rtargc++] = "-n";
389 +                sprintf(nps, "%d", nprocs);
390 +                rtargv[rtargc++] = nps;
391                  rtargv[rtargc++] = header ? "-h+" : "-h-";
392                  sprintf(fmt, "-f%c%c", inpfmt, outfmt);
393                  rtargv[rtargc++] = fmt;
# Line 256 | Line 397 | main(int argc, char *argv[])
397                  rtargv[rtargc++] = "-y";
398                  sprintf(syres, "%d", yres);
399                  rtargv[rtargc++] = syres;
259                rtargv[rtargc++] = "-oW";
400                  rtargv[rtargc++] = "-defaults";
401                  rtargv[rtargc] = NULL;
402                  rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
# Line 269 | Line 409 | main(int argc, char *argv[])
409                  perror(rtpath); /* execv() should not return */
410                  exit(1);
411          }
412 <        if (!nmods)
413 <                error(USER, "No modifiers specified");
414 <        if (argc < 2 || argv[argc-1][0] == '-')
415 <                error(USER, "missing octree argument");
412 >        if (nprocs > 1) {       /* add persist file if parallel */
413 >                if (persist_state == PERSIST_SINGLE)
414 >                        error(USER, "use -PP option for multiple processes");
415 >                if (persist_state == PERSIST_NONE) {
416 >                        rtargv[rtargc++] = "-PP";
417 >                        rtargv[rtargc++] = mktemp(persistfn);
418 >                        persist_state = PERSIST_OURS;
419 >                }
420 >        }
421                                  /* add format string */
422          sprintf(fmt, "-f%cf", inpfmt);
423          rtargv[rtargc++] = fmt;
424                                  /* octree argument is last */
425 <        rtargv[rtargc++] = octree = argv[argc-1];
425 >        if (i <= 0 || i != argc-1 || argv[i][0] == '-')
426 >                error(USER, "missing octree argument");
427 >        rtargv[rtargc++] = octree = argv[i];
428          rtargv[rtargc] = NULL;
429 <                                /* start rtrace & sum contributions */
429 >                                /* start rtrace & recover if requested */
430          init(nprocs);
431 <        tracecontribs(stdin);
431 >                                /* compute contributions */
432 >        trace_contribs(stdin);
433 >                                /* clean up */
434          quit(0);
435   }
436  
437 + #ifndef SIGALRM
438 + #define SIGALRM SIGTERM
439 + #endif
440   /* kill persistent rtrace process */
441   static void
442   killpersist(void)
443   {
444          FILE    *fp = fopen(persistfn, "r");
445 <        int     pid;
445 >        RT_PID  pid;
446  
447          if (fp == NULL)
448                  return;
# Line 324 | Line 476 | quit(int status)
476   {
477          int     rtstat;
478  
479 <        if (rt0.next != NULL)           /* terminate persistent rtrace */
479 >        if (persist_state == PERSIST_OURS)  /* terminate waiting rtrace */
480                  killpersist();
481                                          /* clean up rtrace process(es) */
482          rtstat = done_rprocs(&rt0);
# Line 333 | Line 485 | quit(int status)
485          exit(status);                   /* flushes all output streams */
486   }
487  
488 < /* start rtrace and initialize buffers */
488 > /* start rtrace processes and initialize */
489   void
490   init(int np)
491   {
492          struct rtproc   *rtp;
493          int     i;
494          int     maxbytes;
495 +                                        /* make sure we have something to do */
496 +        if (!nmods)
497 +                error(USER, "No modifiers specified");
498                                          /* assign ray variables */
499          scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
500          scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
501                                          /* set up signal handling */
502 < #ifdef SIGPIPE /* not present on Windows */
502 >        signal(SIGINT, quit);
503 > #ifdef SIGHUP
504 >        signal(SIGHUP, quit);
505 > #endif
506 > #ifdef SIGTERM
507 >        signal(SIGTERM, quit);
508 > #endif
509 > #ifdef SIGPIPE
510          signal(SIGPIPE, quit);
511   #endif
512          rtp = &rt0;                     /* start rtrace process(es) */
# Line 360 | Line 522 | init(int np)
522                          error(SYSTEM, "cannot start rtrace process");
523                  if (maxbytes > treebufsiz)
524                          treebufsiz = maxbytes;
525 +                rtp->raynum = 0;
526                  rtp->bsiz = 0;
527                  rtp->buf = NULL;
528 <                rtp->raynum = 0;
528 >                rtp->nbr = 0;
529                  if (i == np)            /* last process? */
530                          break;
531                  if (i == 1)
# Line 375 | Line 538 | init(int np)
538          rtp->next = NULL;               /* terminate list */
539          if (yres > 0) {
540                  if (xres > 0)
541 <                        raysleft = xres*yres;
541 >                        raysleft = (unsigned long)xres*yres;
542                  else
543                          raysleft = yres;
544          } else
545                  raysleft = 0;
546 <        waitflush = xres;
546 >        if ((account = accumulate) > 0)
547 >                raysleft *= accumulate;
548 >        waitflush = (yres > 0) & (xres > 1) ? 0 : xres;
549 >        if (!recover)
550 >                return;
551 >                                        /* recover previous values */
552 >        if (accumulate <= 0)
553 >                reload_output();
554 >        else
555 >                recover_output(stdin);
556   }
557  
558 + /* grow modifier to accommodate more bins */
559 + MODCONT *
560 + growmodifier(MODCONT *mp, int nb)
561 + {
562 +        if (nb <= mp->nbins)
563 +                return mp;
564 +        mp = (MODCONT *)realloc(mp, sizeof(MODCONT) + sizeof(DCOLOR)*(nb-1));
565 +        if (mp == NULL)
566 +                error(SYSTEM, "out of memory in growmodifier");
567 +        memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(nb-mp->nbins));
568 +        mp->nbins = nb;
569 +        return mp;
570 + }
571 +
572   /* add modifier to our list to track */
573   MODCONT *
574 < addmodifier(char *modn, char *outf, char *binv)
574 > addmodifier(char *modn, char *outf, char *binv, int bincnt)
575   {
576          LUENT   *lep = lu_find(&modconttab, modn);
577          MODCONT *mp;
578 +        int     i;
579          
580          if (lep->data != NULL) {
581                  sprintf(errmsg, "duplicate modifier '%s'", modn);
582                  error(USER, errmsg);
583          }
584          if (nmods >= MAXMODLIST)
585 <                error(USER, "too many modifiers");
585 >                error(INTERNAL, "too many modifiers");
586          modname[nmods++] = modn;        /* XXX assumes static string */
587          lep->key = modn;                /* XXX assumes static string */
588          mp = (MODCONT *)malloc(sizeof(MODCONT));
589          if (mp == NULL)
590                  error(SYSTEM, "out of memory in addmodifier");
404        lep->data = (char *)mp;
591          mp->outspec = outf;             /* XXX assumes static string */
592          mp->modname = modn;             /* XXX assumes static string */
593 <        if (binv != NULL)
594 <                mp->binv = eparse(binv);
595 <        else
596 <                mp->binv = eparse("0");
597 <        mp->nbins = 1;
593 >        if (binv == NULL)
594 >                binv = "0";             /* use single bin if unspecified */
595 >        mp->binv = eparse(binv);
596 >        if (mp->binv->type == NUM) {    /* check value if constant */
597 >                bincnt = (int)(evalue(mp->binv) + 1.5);
598 >                if (bincnt != 1) {
599 >                        sprintf(errmsg, "illegal non-zero constant for bin (%s)",
600 >                                        binv);
601 >                        error(USER, errmsg);
602 >                }
603 >        }
604 >        mp->nbins = 1;                  /* initialize results holder */
605          setcolor(mp->cbin[0], 0., 0., 0.);
606 +        if (bincnt > 1)
607 +                mp = growmodifier(mp, bincnt);
608 +        lep->data = (char *)mp;
609 +                                        /* allocate output streams */
610 +        for (i = bincnt; i-- > 0; )
611 +                getostream(mp->outspec, mp->modname, i, 1);
612          return mp;
613   }
614  
615 + /* add modifiers from a file list */
616 + void
617 + addmodfile(char *fname, char *outf, char *binv, int bincnt)
618 + {
619 +        char    *mname[MAXMODLIST];
620 +        int     i;
621 +                                        /* find the file & store strings */
622 +        if (wordfile(mname, getpath(fname, getrlibpath(), R_OK)) < 0) {
623 +                sprintf(errmsg, "cannot find modifier file '%s'", fname);
624 +                error(SYSTEM, errmsg);
625 +        }
626 +        for (i = 0; mname[i]; i++)      /* add each one */
627 +                addmodifier(mname[i], outf, binv, bincnt);
628 + }
629 +
630   /* put string to stderr */
631   void
632   eputs(char  *s)
# Line 428 | Line 642 | eputs(char  *s)
642          midline = s[strlen(s)-1] != '\n';
643   }
644  
645 + /* construct output file name and return flags whether modifier/bin present */
646 + int
647 + ofname(char *oname, const char *ospec, const char *mname, int bn)
648 + {
649 +        const char      *mnp = NULL;
650 +        const char      *bnp = NULL;
651 +        const char      *cp;
652 +        
653 +        if (ospec == NULL)
654 +                return -1;
655 +        for (cp = ospec; *cp; cp++)             /* check format position(s) */
656 +                if (*cp == '%') {
657 +                        do
658 +                                ++cp;
659 +                        while (isdigit(*cp));
660 +                        switch (*cp) {
661 +                        case '%':
662 +                                break;
663 +                        case 's':
664 +                                if (mnp != NULL)
665 +                                        return -1;
666 +                                mnp = cp;
667 +                                break;
668 +                        case 'd':
669 +                        case 'i':
670 +                        case 'o':
671 +                        case 'x':
672 +                        case 'X':
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);
460        if (xres > 0) {
461                if (yres > 0)                   /* resolution string */
462                        fprtresolu(xres, yres, fout);
463                fflush(fout);
464        }
731   }
732  
733 < /* Get output file pointer (open and write header if new) */
734 < FILE *
735 < getofile(const char *ospec, const char *mname, int bn)
733 > /* write resolution string to given output stream */
734 > void
735 > printresolu(FILE *fout, int xr, int yr)
736   {
737 <        static int      using_stdout = 0;
738 <        const char      *mnp = NULL;
739 <        const char      *bnp = NULL;
740 <        const char      *cp;
741 <        char            ofname[1024];
742 <        LUENT           *lep;
737 >        if ((xr > 0) & (yr > 0))        /* resolution string */
738 >                fprtresolu(xr, yr, fout);
739 > }
740 >
741 > /* Get output stream pointer (open and write header if new and noopen==0) */
742 > STREAMOUT *
743 > getostream(const char *ospec, const char *mname, int bn, int noopen)
744 > {
745 >        static const DCOLOR     nocontrib = BLKCOLOR;
746 >        static STREAMOUT        stdos;
747 >        int                     ofl;
748 >        char                    oname[1024];
749 >        LUENT                   *lep;
750 >        STREAMOUT               *sop;
751          
752          if (ospec == NULL) {                    /* use stdout? */
753 <                if (!using_stdout && header)
754 <                        printheader(stdout);
755 <                using_stdout = 1;
756 <                return stdout;
753 >                if (!noopen && !using_stdout) {
754 >                        if (outfmt != 'a')
755 >                                SET_FILE_BINARY(stdout);
756 >                        if (header)
757 >                                printheader(stdout, NULL);
758 >                        printresolu(stdout, xres, yres);
759 >                        if (waitflush > 0)
760 >                                fflush(stdout);
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 > 0) {           /* global resolution */
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/accumulate : 0; 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 (waitflush > 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(int navg)
964 + {
965 +        double          sf = 1.;
966 +        int             i, j;
967 +        MODCONT         *mp;
968 +        STREAMOUT       *sop;
969 +                                                /* set average scaling */
970 +        if (navg > 1)
971 +                sf = 1. / (double)navg;
972                                                  /* output modifiers in order */
973          for (i = 0; i < nmods; i++) {
974                  mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
975 <                for (j = 0; j < mp->nbins; j++) {
976 <                        fout = getofile(mp->outspec, mp->modname, j);
977 <                        switch (outfmt) {
978 <                        case 'a':
979 <                                fprintf(fout, "%.6e\t%.6e\t%.6e\t",
980 <                                                mp->cbin[j][RED],
981 <                                                mp->cbin[j][GRN],
982 <                                                mp->cbin[j][BLU]);
983 <                                break;
984 <                        case 'f':
985 <                                fwrite(mp->cbin[j], sizeof(float), 3, fout);
986 <                                break;
987 <                        case 'd':
988 <                                dv[0] = mp->cbin[j][0];
989 <                                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);
975 >                if (navg > 1)                   /* average scaling */
976 >                        for (j = mp->nbins; j--; )
977 >                                scalecolor(mp->cbin[j], sf);
978 >                sop = getostream(mp->outspec, mp->modname, 0,0);
979 >                put_contrib(mp->cbin[0], sop->ofp);
980 >                if (mp->nbins > 3 &&            /* minor optimization */
981 >                                sop == getostream(mp->outspec, mp->modname, 1,0))
982 >                        for (j = 1; j < mp->nbins; j++)
983 >                                put_contrib(mp->cbin[j], sop->ofp);
984 >                else
985 >                        for (j = 1; j < mp->nbins; j++)
986 >                                put_contrib(mp->cbin[j],
987 >                                    getostream(mp->outspec,mp->modname,j,0)->ofp);
988 >                                                /* clear for next time */
989 >                memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
990          }
991          --waitflush;                            /* terminate records */
992          lu_doall(&ofiletab, puteol, NULL);
993 <        if (!waitflush)
994 <                waitflush = xres;
993 >        if (using_stdout & (outfmt == 'a'))
994 >                putc('\n', stdout);
995 >        if (!waitflush) {
996 >                waitflush = (yres > 0) & (xres > 1) ? 0 : xres;
997 >                if (using_stdout)
998 >                        fflush(stdout);
999 >        }
1000   }
1001  
1002 < /* process (or save) ray tree produced by rtrace process */
1002 > /* queue completed ray tree produced by rtrace process */
1003   void
1004 < process_rays(struct rtproc *rtp)
1004 > queue_raytree(struct rtproc *rtp)
1005   {
1006 <        struct rtproc   *rtu;
1007 <                                        /* check if time to process it */
1008 <        if (rtp->raynum == lastdone+1) {
1009 <                int             n = rtp->bpos - rtp->buf;
1006 >        struct rtproc   *rtu, *rtl = NULL;
1007 >                                        /* insert following ray order */
1008 >        for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
1009 >                if (rtp->raynum < rtu->raynum)
1010 >                        break;
1011 >        rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
1012 >        if (rtu == NULL)
1013 >                error(SYSTEM, "out of memory in queue_raytree");
1014 >        *rtu = *rtp;
1015 >        if (rtl == NULL) {
1016 >                rtu->next = rt_unproc;
1017 >                rt_unproc = rtu;
1018 >        } else {
1019 >                rtu->next = rtl->next;
1020 >                rtl->next = rtu;
1021 >        }
1022 >        rtp->raynum = 0;                /* clear path for next ray tree */
1023 >        rtp->bsiz = 0;
1024 >        rtp->buf = NULL;
1025 >        rtp->nbr = 0;
1026 > }
1027 >
1028 > /* process completed ray trees from our queue */
1029 > void
1030 > process_queue(void)
1031 > {
1032 >        char    modname[128];
1033 >                                        /* ray-ordered queue */
1034 >        while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
1035 >                struct rtproc   *rtp = rt_unproc;
1036 >                int             n = rtp->nbr;
1037                  const char      *cp = rtp->buf;
1038                  while (n > 0) {         /* process rays */
1039 <                        char    matname[128];
678 <                        char    *mnp = matname;
1039 >                        register char   *mnp = modname;
1040                                          /* skip leading tabs */
1041                          while (n > 0 && *cp == '\t') {
1042                                  cp++; n--;
1043                          }
1044 <                                        /* get material name */
1045 <                        while (n > 0 && *cp != '\t') {
1044 >                        if (!n || !(isalpha(*cp) | (*cp == '_')))
1045 >                                error(USER, "bad modifier name from rtrace");
1046 >                                        /* get modifier name */
1047 >                        while (n > 1 && *cp != '\t') {
1048 >                                if (mnp - modname >= sizeof(modname)-2)
1049 >                                        error(INTERNAL, "modifier name too long");
1050                                  *mnp++ = *cp++; n--;
1051                          }
687                        if (!n)
688                                error(USER, "botched modifer name from rtrace");
1052                          *mnp = '\0';
1053 <                        cp++; n--;      /* skip terminating tab */
1053 >                        cp++; n--;      /* eat following tab */
1054                          if (n < (int)(sizeof(float)*9))
1055                                  error(USER, "incomplete ray value from rtrace");
1056                                          /* add ray contribution */
1057 <                        add_contrib(matname, (float *)cp);
1057 >                        memcpy(rparams, cp, sizeof(float)*9);
1058                          cp += sizeof(float)*9; n -= sizeof(float)*9;
1059 +                        add_contrib(modname);
1060                  }
1061 <                done_contrib();         /* sum up contributions & output */
1061 >                                        /* time to produce record? */
1062 >                if (account > 0 && !--account)
1063 >                        done_contrib(account = accumulate);
1064                  lastdone = rtp->raynum;
1065 <                free(rtp->buf);
1066 <                                        /* catch up with unprocessed list */
1067 <                while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
1068 <                        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 <                }
1065 >                if (rtp->buf != NULL)   /* free up buffer space */
1066 >                        free(rtp->buf);
1067 >                rt_unproc = rtp->next;
1068 >                free(rtp);              /* done with this ray tree */
1069          }
723        rtp->raynum = 0;                /* clear path for next ray tree */
724        rtp->bsiz = 0;
725        rtp->buf = NULL;
1070   }
1071  
1072   /* wait for rtrace process to finish with ray tree */
# Line 731 | Line 1075 | wait_rproc(void)
1075   {
1076          struct rtproc   *rtfree = NULL;
1077          fd_set          readset, errset;
1078 <        int             nr;
1078 >        ssize_t         nr;
1079          struct rtproc   *rt;
1080          int             n;
1081          
# Line 762 | Line 1106 | wait_rproc(void)
1106                                  continue;
1107                          if (rt->buf == NULL) {
1108                                  rt->bsiz = treebufsiz;
1109 <                                rt->buf = (char *)malloc(treebufsiz);
1110 <                        } else if (rt->bpos + BUFSIZ > rt->buf + rt->bsiz) {
1109 >                                rt->buf = (char *)malloc(rt->bsiz);
1110 >                        } else if (rt->nbr + BUFSIZ > rt->bsiz) {
1111                                  if (rt->bsiz + BUFSIZ <= treebufsiz)
1112                                          rt->bsiz = treebufsiz;
1113                                  else
1114 <                                        rt->bsiz = treebufsiz += BUFSIZ;
1114 >                                        treebufsiz = rt->bsiz += BUFSIZ;
1115                                  rt->buf = (char *)realloc(rt->buf, rt->bsiz);
1116                          }
1117                          if (rt->buf == NULL)
1118                                  error(SYSTEM, "out of memory in wait_rproc");
1119 <                        nr = read(rt->pd.r, rt->bpos,
1120 <                                        rt->buf + rt->bsiz - rt->bpos);
777 <                        if (!nr)
1119 >                        nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
1120 >                        if (nr <= 0)
1121                                  error(USER, "rtrace process died");
1122 <                        rt->bpos += nr;         /* advance buffer & check */
1123 <                        if (rt->bpos[-1] == '\t' && rt->bpos[-2] == '-') {
1124 <                                rt->bpos -= 2;  /* elide terminator */
1125 <                                process_rays(rt);
1122 >                        rt->nbr += nr;          /* advance & check */
1123 >                        if (rt->nbr >= 6 && !memcmp(rt->buf+rt->nbr-6,
1124 >                                                        "~\t~\t~\t", 6)) {
1125 >                                rt->nbr -= 6;   /* elide terminator */
1126 >                                queue_raytree(rt);
1127                                  rtfree = rt;    /* ready for next ray */
1128                          }
1129                  }
# Line 801 | Line 1145 | get_rproc(void)
1145  
1146   /* trace ray contributions (main loop) */
1147   void
1148 < tracecontribs(FILE *fin)
1148 > trace_contribs(FILE *fin)
1149   {
1150 +        static int      ignore_warning_given = 0;
1151          char            inpbuf[128];
1152          int             iblen;
1153          struct rtproc   *rtp;
1154                                                  /* loop over input */
1155 <        while ((iblen = getinp(inpbuf, fin)) > 0) {
1156 <                if (lastray+1 < lastray) {      /* counter rollover? */
1155 >        while ((iblen = getinp(inpbuf, fin)) >= 0) {
1156 >                if (!iblen && accumulate != 1) {
1157 >                        if (!ignore_warning_given++)
1158 >                                error(WARNING,
1159 >                                "dummy ray(s) ignored during accumulation\n");
1160 >                        continue;
1161 >                }
1162 >                if (!iblen ||                   /* need flush/reset? */
1163 >                                queue_length() > 10*nrtprocs() ||
1164 >                                lastray+1 < lastray) {
1165                          while (wait_rproc() != NULL)
1166 <                                ;
1166 >                                process_queue();
1167                          lastdone = lastray = 0;
1168                  }
1169                  rtp = get_rproc();              /* get avail. rtrace process */
1170 <                rtp->raynum = ++lastray;        /* assign this ray to it */
1171 <                writebuf(rtp->pd.w, inpbuf, iblen);
1172 <                if (!--raysleft)
1173 <                        break;                  /* explicit EOF */
1170 >                rtp->raynum = ++lastray;        /* assign ray */
1171 >                if (iblen) {                    /* trace ray if valid */
1172 >                        writebuf(rtp->pd.w, inpbuf, iblen);
1173 >                } else {                        /* else bypass dummy ray */
1174 >                        queue_raytree(rtp);     /* queue empty ray/record */
1175 >                        if ((yres <= 0) | (xres <= 0))
1176 >                                waitflush = 1;  /* flush right after */
1177 >                }
1178 >                process_queue();                /* catch up with results */
1179 >                if (raysleft && !--raysleft)
1180 >                        break;                  /* preemptive EOI */
1181          }
1182          while (wait_rproc() != NULL)            /* process outstanding rays */
1183 <                ;
1183 >                process_queue();
1184 >        if (accumulate <= 0)
1185 >                done_contrib(0);                /* output tallies */
1186 >        else if (account < accumulate) {
1187 >                error(WARNING, "partial accumulation in final record");
1188 >                done_contrib(accumulate - account);
1189 >        }
1190 >        if (raysleft)
1191 >                error(USER, "unexpected EOF on input");
1192 >        lu_done(&ofiletab);                     /* close output files */
1193 > }
1194 >
1195 > /* get ray contribution from previous file */
1196 > static int
1197 > get_contrib(DCOLOR cnt, FILE *finp)
1198 > {
1199 >        COLOR   fv;
1200 >        COLR    cv;
1201 >
1202 >        switch (outfmt) {
1203 >        case 'a':
1204 >                return(fscanf(finp,"%lf %lf %lf",&cnt[0],&cnt[1],&cnt[2]) == 3);
1205 >        case 'f':
1206 >                if (fread(fv, sizeof(fv[0]), 3, finp) != 3)
1207 >                        return(0);
1208 >                copycolor(cnt, fv);
1209 >                return(1);
1210 >        case 'd':
1211 >                return(fread(cnt, sizeof(cnt[0]), 3, finp) == 3);
1212 >        case 'c':
1213 >                if (fread(cv, sizeof(cv), 1, finp) != 1)
1214 >                        return(0);
1215 >                colr_color(fv, cv);
1216 >                copycolor(cnt, fv);
1217 >                return(1);
1218 >        default:
1219 >                error(INTERNAL, "botched output format");
1220 >        }
1221 >        return(0);      /* pro forma return */
1222 > }
1223 >
1224 > /* close output file opened for input */
1225 > static int
1226 > myclose(const LUENT *e, void *p)
1227 > {
1228 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1229 >        
1230 >        if (sop->ofp == NULL)
1231 >                return(0);
1232 >        fclose(sop->ofp);
1233 >        sop->ofp = NULL;
1234 >        return(0);
1235 > }
1236 >
1237 > /* load previously accumulated values */
1238 > void
1239 > reload_output(void)
1240 > {
1241 >        int             i, j;
1242 >        MODCONT         *mp;
1243 >        int             ofl;
1244 >        char            oname[1024];
1245 >        char            *fmode = "rb";
1246 >        char            *outvfmt;
1247 >        LUENT           *ment, *oent;
1248 >        int             xr, yr;
1249 >        STREAMOUT       sout;
1250 >        DCOLOR          rgbv;
1251 >
1252 >        switch (outfmt) {
1253 >        case 'a':
1254 >                outvfmt = "ascii";
1255 >                fmode = "r";
1256 >                break;
1257 >        case 'f':
1258 >                outvfmt = "float";
1259 >                break;
1260 >        case 'd':
1261 >                outvfmt = "double";
1262 >                break;
1263 >        case 'c':
1264 >                outvfmt = COLRFMT;
1265 >                break;
1266 >        default:
1267 >                error(INTERNAL, "botched output format");
1268 >                return;
1269 >        }
1270 >                                                /* reload modifier values */
1271 >        for (i = 0; i < nmods; i++) {
1272 >                ment = lu_find(&modconttab,modname[i]);
1273 >                mp = (MODCONT *)ment->data;
1274 >                if (mp->outspec == NULL)
1275 >                        error(USER, "cannot reload from stdout");
1276 >                if (mp->outspec[0] == '!')
1277 >                        error(USER, "cannot reload from command");
1278 >                for (j = 0; ; j++) {            /* load each modifier bin */
1279 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1280 >                        if (ofl < 0)
1281 >                                error(USER, "bad output file specification");
1282 >                        oent = lu_find(&ofiletab, oname);
1283 >                        if (oent->data != NULL) {
1284 >                                sout = *(STREAMOUT *)oent->data;
1285 >                        } else {
1286 >                                sout.reclen = 0;
1287 >                                sout.outpipe = 0;
1288 >                                sout.xr = xres; sout.yr = yres;
1289 >                                sout.ofp = NULL;
1290 >                        }
1291 >                        if (sout.ofp == NULL) { /* open output as input */
1292 >                                sout.ofp = fopen(oname, fmode);
1293 >                                if (sout.ofp == NULL) {
1294 >                                        if (j)
1295 >                                                break;  /* assume end of modifier */
1296 >                                        sprintf(errmsg, "missing reload file '%s'",
1297 >                                                        oname);
1298 >                                        error(WARNING, errmsg);
1299 >                                        break;
1300 >                                }
1301 >                                if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1302 >                                        sprintf(errmsg, "format mismatch for '%s'",
1303 >                                                        oname);
1304 >                                        error(USER, errmsg);
1305 >                                }
1306 >                                if ((sout.xr > 0) & (sout.yr > 0) &&
1307 >                                                (!fscnresolu(&xr, &yr, sout.ofp) ||
1308 >                                                        (xr != sout.xr) |
1309 >                                                        (yr != sout.yr))) {
1310 >                                        sprintf(errmsg, "resolution mismatch for '%s'",
1311 >                                                        oname);
1312 >                                        error(USER, errmsg);
1313 >                                }
1314 >                        }
1315 >                                                        /* read in RGB value */
1316 >                        if (!get_contrib(rgbv, sout.ofp)) {
1317 >                                if (!j) {
1318 >                                        fclose(sout.ofp);
1319 >                                        break;          /* ignore empty file */
1320 >                                }
1321 >                                if (j < mp->nbins) {
1322 >                                        sprintf(errmsg, "missing data in '%s'",
1323 >                                                        oname);
1324 >                                        error(USER, errmsg);
1325 >                                }
1326 >                                break;
1327 >                        }
1328 >                        if (j >= mp->nbins)             /* grow modifier size */
1329 >                                ment->data = (char *)(mp = growmodifier(mp, j+1));
1330 >                        copycolor(mp->cbin[j], rgbv);
1331 >                        if (oent->key == NULL)          /* new file entry */
1332 >                                oent->key = strcpy((char *)
1333 >                                                malloc(strlen(oname)+1), oname);
1334 >                        if (oent->data == NULL)
1335 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1336 >                        *(STREAMOUT *)oent->data = sout;
1337 >                }
1338 >        }
1339 >        lu_doall(&ofiletab, myclose, NULL);     /* close all files */
1340 > }
1341 >
1342 > /* seek on the given output file */
1343 > static int
1344 > myseeko(const LUENT *e, void *p)
1345 > {
1346 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1347 >        off_t           nbytes = *(off_t *)p;
1348 >        
1349 >        if (sop->reclen > 1)
1350 >                nbytes = nbytes * sop->reclen;
1351 >        if (fseeko(sop->ofp, nbytes, SEEK_CUR) < 0) {
1352 >                sprintf(errmsg, "seek error on file '%s'", e->key);
1353 >                error(SYSTEM, errmsg);
1354 >        }
1355 >        return 0;
1356 > }
1357 >
1358 > /* recover output if possible */
1359 > void
1360 > recover_output(FILE *fin)
1361 > {
1362 >        off_t           lastout = -1;
1363 >        int             outvsiz, recsiz;
1364 >        char            *outvfmt;
1365 >        int             i, j;
1366 >        MODCONT         *mp;
1367 >        int             ofl;
1368 >        char            oname[1024];
1369 >        LUENT           *ment, *oent;
1370 >        STREAMOUT       sout;
1371 >        off_t           nvals;
1372 >        int             xr, yr;
1373 >
1374 >        switch (outfmt) {
1375 >        case 'a':
1376 >                error(USER, "cannot recover ASCII output");
1377 >                return;
1378 >        case 'f':
1379 >                outvsiz = sizeof(float)*3;
1380 >                outvfmt = "float";
1381 >                break;
1382 >        case 'd':
1383 >                outvsiz = sizeof(double)*3;
1384 >                outvfmt = "double";
1385 >                break;
1386 >        case 'c':
1387 >                outvsiz = sizeof(COLR);
1388 >                outvfmt = COLRFMT;
1389 >                break;
1390 >        default:
1391 >                error(INTERNAL, "botched output format");
1392 >                return;
1393 >        }
1394 >                                                /* check modifier outputs */
1395 >        for (i = 0; i < nmods; i++) {
1396 >                ment = lu_find(&modconttab,modname[i]);
1397 >                mp = (MODCONT *)ment->data;
1398 >                if (mp->outspec == NULL)
1399 >                        error(USER, "cannot recover from stdout");
1400 >                if (mp->outspec[0] == '!')
1401 >                        error(USER, "cannot recover from command");
1402 >                for (j = 0; ; j++) {            /* check each bin's file */
1403 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1404 >                        if (ofl < 0)
1405 >                                error(USER, "bad output file specification");
1406 >                        oent = lu_find(&ofiletab, oname);
1407 >                        if (oent->data != NULL) {
1408 >                                sout = *(STREAMOUT *)oent->data;
1409 >                        } else {
1410 >                                sout.reclen = 0;
1411 >                                sout.outpipe = 0;
1412 >                                sout.ofp = NULL;
1413 >                        }
1414 >                        if (sout.ofp != NULL) { /* already open? */
1415 >                                if (ofl & OF_BIN)
1416 >                                        continue;
1417 >                                break;
1418 >                        }
1419 >                                                /* open output */
1420 >                        sout.ofp = fopen(oname, "rb+");
1421 >                        if (sout.ofp == NULL) {
1422 >                                if (j)
1423 >                                        break;  /* assume end of modifier */
1424 >                                sprintf(errmsg, "missing recover file '%s'",
1425 >                                                oname);
1426 >                                error(WARNING, errmsg);
1427 >                                break;
1428 >                        }
1429 >                        nvals = lseek(fileno(sout.ofp), 0, SEEK_END);
1430 >                        if (nvals <= 0) {
1431 >                                lastout = 0;    /* empty output, quit here */
1432 >                                fclose(sout.ofp);
1433 >                                break;
1434 >                        }
1435 >                        if (!sout.reclen) {
1436 >                                if (!(ofl & OF_BIN)) {
1437 >                                        sprintf(errmsg,
1438 >                                                "need -bn to recover file '%s'",
1439 >                                                        oname);
1440 >                                        error(USER, errmsg);
1441 >                                }
1442 >                                recsiz = outvsiz;
1443 >                        } else
1444 >                                recsiz = outvsiz * sout.reclen;
1445 >
1446 >                        lseek(fileno(sout.ofp), 0, SEEK_SET);
1447 >                        if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1448 >                                sprintf(errmsg, "format mismatch for '%s'",
1449 >                                                oname);
1450 >                                error(USER, errmsg);
1451 >                        }
1452 >                        sout.xr = xres; sout.yr = yres;
1453 >                        if ((sout.xr > 0) & (sout.yr > 0) &&
1454 >                                        (!fscnresolu(&xr, &yr, sout.ofp) ||
1455 >                                                (xr != sout.xr) |
1456 >                                                (yr != sout.yr))) {
1457 >                                sprintf(errmsg, "resolution mismatch for '%s'",
1458 >                                                oname);
1459 >                                error(USER, errmsg);
1460 >                        }
1461 >                        nvals = (nvals - (off_t)ftell(sout.ofp)) / recsiz;
1462 >                        if ((lastout < 0) | (nvals < lastout))
1463 >                                lastout = nvals;
1464 >                        if (oent->key == NULL)  /* new entry */
1465 >                                oent->key = strcpy((char *)
1466 >                                                malloc(strlen(oname)+1), oname);
1467 >                        if (oent->data == NULL)
1468 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1469 >                        *(STREAMOUT *)oent->data = sout;
1470 >                        if (!(ofl & OF_BIN))
1471 >                                break;          /* no bin separation */
1472 >                }
1473 >                if (!lastout) {                 /* empty output */
1474 >                        error(WARNING, "no previous data to recover");
1475 >                        lu_done(&ofiletab);     /* reclose all outputs */
1476 >                        return;
1477 >                }
1478 >                if (j > mp->nbins)              /* reallocate modifier bins */
1479 >                        ment->data = (char *)(mp = growmodifier(mp, j));
1480 >        }
1481 >        if (lastout < 0) {
1482 >                error(WARNING, "no output files to recover");
1483 >                return;
1484 >        }
1485 >        if (raysleft && lastout >= raysleft/accumulate) {
1486 >                error(WARNING, "output appears to be complete");
1487 >                /* XXX should read & discard input? */
1488 >                quit(0);
1489 >        }
1490 >                                                /* seek on all files */
1491 >        nvals = lastout * outvsiz;
1492 >        lu_doall(&ofiletab, myseeko, &nvals);
1493 >                                                /* skip repeated input */
1494 >        for (nvals = 0; nvals < lastout; nvals++)
1495 >                if (getinp(oname, fin) < 0)
1496 >                        error(USER, "unexpected EOF on input");
1497 >        lastray = lastdone = (unsigned long)lastout * accumulate;
1498 >        if (raysleft)
1499 >                raysleft -= lastray;
1500   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines