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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines