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.30 by greg, Wed Oct 5 19:44:17 2005 UTC

# Line 5 | Line 5 | static const char RCSid[] = "$Id$";
5   * Gather rtrace output to compute contributions from particular sources
6   */
7  
8 + #include  "standard.h"
9   #include  <ctype.h>
10 < #include  "rtio.h"
10 < #include  "rterror.h"
10 > #include  <signal.h>
11   #include  "platform.h"
12   #include  "rtprocess.h"
13   #include  "selcall.h"
# Line 16 | Line 16 | static const char RCSid[] = "$Id$";
16   #include  "lookup.h"
17   #include  "calcomp.h"
18  
19 < #ifdef getc_unlocked            /* avoid horrendous overhead of flockfile */
20 < #undef getc
21 < #undef putc
22 < #define getc    getc_unlocked
23 < #define putc    putc_unlocked
24 < #define ferror  ferror_unlocked
19 > #ifndef MAXMODLIST
20 > #define MAXMODLIST      1024            /* maximum modifiers we'll track */
21   #endif
22  
27 #define MAXMODLIST      1024            /* maximum modifiers we'll track */
28
23   int     treebufsiz = BUFSIZ;            /* current tree buffer size */
24  
25 + typedef double  DCOLOR[3];              /* double-precision color */
26 +
27   /*
28   * The modcont structure is used to accumulate ray contributions
29   * for a particular modifier, which may be subdivided into bins
# 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); }
# Line 55 | Line 51 | static void closefile(void *p) { fclose((FILE *)p); }
51  
52   LUTAB   ofiletab = LU_SINIT(free,closefile);    /* output file table */
53  
54 + #define OF_MODIFIER     01
55 + #define OF_BIN          02
56 +
57   FILE *getofile(const char *ospec, const char *mname, int bn);
58 + int ofname(char *oname, const char *ospec, const char *mname, int bn);
59 + void printheader(FILE *fout, const char *info);
60 + void printresolu(FILE *fout);
61  
62   /*
63   * The rcont structure is used to manage i/o with a particular
# Line 66 | Line 68 | FILE *getofile(const char *ospec, const char *mname, i
68   struct rtproc {
69          struct rtproc   *next;          /* next in list of processes */
70          SUBPROC         pd;             /* rtrace pipe descriptors */
71 <        unsigned long   raynum;         /* ray number for this buffer */
72 <        int             bsiz;           /* rtrace buffer length */
73 <        char            *buf;           /* rtrace i/o buffer */
74 <        char            *bpos;          /* current buffer position */
75 < };                              /* rtrace process */
71 >        unsigned long   raynum;         /* ray number for this tree */
72 >        int             bsiz;           /* ray tree buffer length */
73 >        char            *buf;           /* ray tree buffer */
74 >        int             nbr;            /* number of bytes from rtrace */
75 > };                              /* rtrace process buffer */
76  
77                                          /* rtrace command and defaults */
78 < char            *rtargv[256] = { "rtrace", "-dj", ".5", "-dr", "3",
79 <                                "-ab", "1", "-ad", "512", };
78 > char            *rtargv[256+2*MAXMODLIST] = { "rtrace",
79 >                                "-dj", ".5", "-dr", "3",
80 >                                "-ab", "1", "-ad", "128", };
81   int  rtargc = 9;
82                                          /* overriding rtrace options */
83 < char            *myrtopts[] = { "-o-TmWdp", "-h-",
84 <                                "-x", "1", "-y", "0", NULL };
83 > char            *myrtopts[] = { "-o~~TmWdp", "-h-", "-x", "1", "-y", "0",
84 >                                "-dt", "0", "-as", "0", "-aa", "0", NULL };
85  
86   struct rtproc   rt0;                    /* head of rtrace process list */
87  
88   struct rtproc   *rt_unproc = NULL;      /* unprocessed ray trees */
89  
90   char    persistfn[] = "pfXXXXXX";       /* persist file name */
88 char    fmt[8];                         /* rtrace i/o format */
91  
92   int             gargc;                  /* global argc */
93   char            **gargv;                /* global argv */
# Line 100 | Line 102 | int            header = 1;             /* output header? */
102   int             xres = 0;               /* horiz. output resolution */
103   int             yres = 0;               /* vert. output resolution */
104  
105 < long            raysleft;               /* number of rays left to trace */
105 > unsigned long   raysleft;               /* number of rays left to trace */
106   long            waitflush;              /* how long until next flush */
107  
108   unsigned long   lastray = 0;            /* last ray number sent */
109   unsigned long   lastdone = 0;           /* last ray processed */
110  
111 + int             using_stdout = 0;       /* are we using stdout? */
112 +
113   const char      *modname[MAXMODLIST];   /* ordered modifier name list */
114   int             nmods = 0;              /* number of modifiers */
115  
116 + #define queue_length()          (lastray - lastdone)
117 +
118   MODCONT *addmodifier(char *modn, char *outf, char *binv);
119 + void addmodfile(char *fname, char *outf, char *binv);
120  
114 int done_rprocs(struct rtproc *rtp);
121   void init(int np);
122 < void tracecontribs(FILE *fp);
122 > int done_rprocs(struct rtproc *rtp);
123 > void recover_output(FILE *fin);
124 > void trace_contribs(FILE *fin);
125   struct rtproc *wait_rproc(void);
126   struct rtproc *get_rproc(void);
127 < void process_rays(struct rtproc *rtp);
127 > void queue_raytree(struct rtproc *rtp);
128 > void process_queue(void);
129  
130 < void add_contrib(const char *modn, float rayval[7]);
130 > void put_contrib(const DCOLOR cnt, FILE *fout);
131 > void add_contrib(const char *modn);
132   void done_contrib(void);
133  
134 + /* return number of open rtrace processes */
135 + static int
136 + nrtprocs(void)
137 + {
138 +        int     nrtp = 0;
139 +        struct rtproc   *rtp;
140 +
141 +        for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
142 +                nrtp += rtp->pd.running;
143 +        return(nrtp);
144 + }
145 +
146   /* set input/output format */
147   static void
148   setformat(const char *fmt)
149   {
150          switch (fmt[0]) {
129        case 'a':
151          case 'f':
152          case 'd':
153 +                SET_FILE_BINARY(stdin);
154 +                /* fall through */
155 +        case 'a':
156                  inpfmt = fmt[0];
157                  break;
158          default:
# Line 159 | Line 183 | int
183   main(int argc, char *argv[])
184   {
185          int     nprocs = 1;
186 +        int     recover = 0;
187          char    *curout = NULL;
188          char    *binval = NULL;
189 <        int     i;
190 <                                /* set global argument list */
191 <        gargc = argc;
189 >        char    fmt[8];
190 >        int     i, j;
191 >                                /* need at least one argument */
192 >        if (argc < 2) {
193 >                fprintf(stderr,
194 > "Usage: %s [-n nprocs][-r][-e expr][-f source][-o ospec][-b binv] {-m mod | -M file} [rtrace options] octree\n",
195 >                        argv[0]);
196 >                exit(1);
197 >        }
198 >                                /* global program name */
199          gargv = argv;
200 <                                /* set up calcomp functions */
200 >                                /* initialize calcomp routines */
201          esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
202          esupport &= ~(E_OUTCHAN);
203 +        varset("PI", ':', PI);
204                                  /* get our options */
205 <        for (i = 1; i < argc && argv[i][0] == '-'; i++) {
206 <                switch (argv[i][1]) {
207 <                case 'n':                       /* number of processes */
208 <                        if (argv[i][2] || i >= argc-1) break;
209 <                        nprocs = atoi(argv[++i]);
210 <                        if (nprocs <= 0)
211 <                                error(USER, "illegal number of processes");
212 <                        continue;
213 <                case 'h':                       /* output header? */
214 <                        switch (argv[i][2]) {
215 <                        case '\0':
216 <                                header = !header;
205 >        for (i = 1; i < argc-1; i++) {
206 >                                                /* expand arguments */
207 >                while ((j = expandarg(&argc, &argv, i)) > 0)
208 >                        ;
209 >                if (j < 0) {
210 >                        fprintf(stderr, "%s: cannot expand '%s'",
211 >                                        argv[0], argv[i]);
212 >                        exit(1);
213 >                }
214 >                if (argv[i][0] == '-')
215 >                        switch (argv[i][1]) {
216 >                        case 'r':               /* recover output */
217 >                                if (argv[i][2]) break;
218 >                                recover++;
219                                  continue;
220 <                        case '+': case '1': case 'T': case 't':
221 <                                header = 1;
220 >                        case 'n':               /* number of processes */
221 >                                if (argv[i][2] || i >= argc-2) break;
222 >                                nprocs = atoi(argv[++i]);
223 >                                if (nprocs <= 0)
224 >                                        error(USER, "illegal number of processes");
225                                  continue;
226 <                        case '-': case '0': case 'F': case 'f':
227 <                                header = 0;
226 >                        case 'h':               /* output header? */
227 >                                switch (argv[i][2]) {
228 >                                case '\0':
229 >                                        header = !header;
230 >                                        continue;
231 >                                case '+': case '1':
232 >                                case 'T': case 't':
233 >                                case 'Y': case 'y':
234 >                                        header = 1;
235 >                                        continue;
236 >                                case '-': case '0':
237 >                                case 'F': case 'f':
238 >                                case 'N': case 'n':
239 >                                        header = 0;
240 >                                        continue;
241 >                                }
242 >                                break;
243 >                        case 'f':               /* file or i/o format */
244 >                                if (!argv[i][2]) {
245 >                                        char    *fpath;
246 >                                        if (i >= argc-2) break;
247 >                                        fpath = getpath(argv[++i],
248 >                                                        getrlibpath(), R_OK);
249 >                                        if (fpath == NULL) {
250 >                                                sprintf(errmsg,
251 >                                                        "cannot find file '%s'",
252 >                                                                argv[i]);
253 >                                                error(USER, errmsg);
254 >                                        }
255 >                                        fcompile(fpath);
256 >                                        continue;
257 >                                }
258 >                                setformat(argv[i]+2);
259                                  continue;
260 <                        }
261 <                        break;
262 <                case 'f':                       /* file or i/o format */
194 <                        if (!argv[i][2]) {
195 <                                if (i >= argc-1) break;
196 <                                fcompile(argv[++i]);
260 >                        case 'e':               /* expression */
261 >                                if (argv[i][2] || i >= argc-2) break;
262 >                                scompile(argv[++i], NULL, 0);
263                                  continue;
264 +                        case 'o':               /* output file spec. */
265 +                                if (argv[i][2] || i >= argc-2) break;
266 +                                curout = argv[++i];
267 +                                continue;
268 +                        case 'x':               /* horiz. output resolution */
269 +                                if (argv[i][2] || i >= argc-2) break;
270 +                                xres = atoi(argv[++i]);
271 +                                continue;
272 +                        case 'y':               /* vert. output resolution */
273 +                                if (argv[i][2] || i >= argc-2) break;
274 +                                yres = atoi(argv[++i]);
275 +                                continue;
276 +                        case 'b':               /* bin expression */
277 +                                if (argv[i][2] || i >= argc-2) break;
278 +                                binval = argv[++i];
279 +                                continue;
280 +                        case 'm':               /* modifier name */
281 +                                if (argv[i][2] || i >= argc-2) break;
282 +                                rtargv[rtargc++] = "-ti";
283 +                                rtargv[rtargc++] = argv[++i];
284 +                                addmodifier(argv[i], curout, binval);
285 +                                continue;
286 +                        case 'M':               /* modifier file */
287 +                                if (argv[i][2] || i >= argc-2) break;
288 +                                rtargv[rtargc++] = "-tI";
289 +                                rtargv[rtargc++] = argv[++i];
290 +                                addmodfile(argv[i], curout, binval);
291 +                                continue;
292                          }
293 <                        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 */
293 >                rtargv[rtargc++] = argv[i];     /* assume rtrace option */
294          }
295 <        for ( ; i < argc; i++)  /* transfer rtrace-specific options */
296 <                rtargv[rtargc++] = argv[i];
236 <        if (!strcmp(rtargv[--rtargc], "-defaults"))
237 <                nprocs = 0;
238 <        if (nprocs > 1) {       /* add persist file if parallel invocation */
239 <                rtargv[rtargc++] = "-PP";
240 <                rtargv[rtargc++] = mktemp(persistfn);
241 <        }
295 >                                /* set global argument list */
296 >        gargc = argc; gargv = argv;
297                                  /* add "mandatory" rtrace settings */
298 <        for (i = 0; myrtopts[i] != NULL; i++)
299 <                rtargv[rtargc++] = myrtopts[i];
300 <        if (!nprocs) {          /* just asking for defaults? */
298 >        for (j = 0; myrtopts[j] != NULL; j++)
299 >                rtargv[rtargc++] = myrtopts[j];
300 >                                /* just asking for defaults? */
301 >        if (!strcmp(argv[i], "-defaults")) {
302                  char    sxres[16], syres[16];
303                  char    *rtpath;
304 <                printf("-n  1\t\t\t\t# number of processes\n", nprocs);
304 >                printf("-n  %-2d\t\t\t\t# number of processes\n", nprocs);
305                  fflush(stdout);                 /* report OUR options */
306                  rtargv[rtargc++] = header ? "-h+" : "-h-";
307                  sprintf(fmt, "-f%c%c", inpfmt, outfmt);
# Line 256 | Line 312 | main(int argc, char *argv[])
312                  rtargv[rtargc++] = "-y";
313                  sprintf(syres, "%d", yres);
314                  rtargv[rtargc++] = syres;
315 <                rtargv[rtargc++] = "-oW";
315 >                rtargv[rtargc++] = "-oTW";
316                  rtargv[rtargc++] = "-defaults";
317                  rtargv[rtargc] = NULL;
318                  rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
# Line 269 | Line 325 | main(int argc, char *argv[])
325                  perror(rtpath); /* execv() should not return */
326                  exit(1);
327          }
328 <        if (!nmods)
329 <                error(USER, "No modifiers specified");
330 <        if (argc < 2 || argv[argc-1][0] == '-')
331 <                error(USER, "missing octree argument");
328 >        if (nprocs > 1) {       /* add persist file if parallel */
329 >                rtargv[rtargc++] = "-PP";
330 >                rtargv[rtargc++] = mktemp(persistfn);
331 >        }
332                                  /* add format string */
333          sprintf(fmt, "-f%cf", inpfmt);
334          rtargv[rtargc++] = fmt;
335                                  /* octree argument is last */
336 <        rtargv[rtargc++] = octree = argv[argc-1];
336 >        if (i <= 0 || i != argc-1 || argv[i][0] == '-')
337 >                error(USER, "missing octree argument");
338 >        rtargv[rtargc++] = octree = argv[i];
339          rtargv[rtargc] = NULL;
340 <                                /* start rtrace & sum contributions */
340 >                                /* start rtrace */
341          init(nprocs);
342 <        tracecontribs(stdin);
342 >        if (recover)            /* perform recovery if requested */
343 >                recover_output(stdin);
344 >        trace_contribs(stdin);  /* compute contributions */
345          quit(0);
346   }
347  
348 + #ifndef SIGALRM
349 + #define SIGALRM SIGTERM
350 + #endif
351   /* kill persistent rtrace process */
352   static void
353   killpersist(void)
354   {
355          FILE    *fp = fopen(persistfn, "r");
356 <        int     pid;
356 >        RT_PID  pid;
357  
358          if (fp == NULL)
359                  return;
# Line 333 | Line 396 | quit(int status)
396          exit(status);                   /* flushes all output streams */
397   }
398  
399 < /* start rtrace and initialize buffers */
399 > /* start rtrace processes and initialize */
400   void
401   init(int np)
402   {
403          struct rtproc   *rtp;
404          int     i;
405          int     maxbytes;
406 +                                        /* make sure we have something to do */
407 +        if (!nmods)
408 +                error(USER, "No modifiers specified");
409                                          /* assign ray variables */
410          scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
411          scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
412                                          /* set up signal handling */
413 < #ifdef SIGPIPE /* not present on Windows */
413 >        signal(SIGINT, quit);
414 > #ifdef SIGHUP
415 >        signal(SIGHUP, quit);
416 > #endif
417 > #ifdef SIGTERM
418 >        signal(SIGTERM, quit);
419 > #endif
420 > #ifdef SIGPIPE
421          signal(SIGPIPE, quit);
422   #endif
423          rtp = &rt0;                     /* start rtrace process(es) */
# Line 360 | Line 433 | init(int np)
433                          error(SYSTEM, "cannot start rtrace process");
434                  if (maxbytes > treebufsiz)
435                          treebufsiz = maxbytes;
436 +                rtp->raynum = 0;
437                  rtp->bsiz = 0;
438                  rtp->buf = NULL;
439 <                rtp->raynum = 0;
439 >                rtp->nbr = 0;
440                  if (i == np)            /* last process? */
441                          break;
442                  if (i == 1)
# Line 375 | Line 449 | init(int np)
449          rtp->next = NULL;               /* terminate list */
450          if (yres > 0) {
451                  if (xres > 0)
452 <                        raysleft = xres*yres;
452 >                        raysleft = (unsigned long)xres*yres;
453                  else
454                          raysleft = yres;
455          } else
# Line 413 | Line 487 | addmodifier(char *modn, char *outf, char *binv)
487          return mp;
488   }
489  
490 + /* add modifiers from a file list */
491 + void
492 + addmodfile(char *fname, char *outf, char *binv)
493 + {
494 +        char    *mname[MAXMODLIST];
495 +        int     i;
496 +                                        /* find the file & store strings */
497 +        if (wordfile(mname, getpath(fname, getrlibpath(), R_OK)) < 0) {
498 +                sprintf(errmsg, "cannot find modifier file '%s'", fname);
499 +                error(SYSTEM, errmsg);
500 +        }
501 +        for (i = 0; mname[i]; i++)      /* add each one */
502 +                addmodifier(mname[i], outf, binv);
503 + }
504 +
505   /* put string to stderr */
506   void
507   eputs(char  *s)
# Line 428 | Line 517 | eputs(char  *s)
517          midline = s[strlen(s)-1] != '\n';
518   }
519  
520 + /* construct output file name and return flags whether modifier/bin present */
521 + int
522 + ofname(char *oname, const char *ospec, const char *mname, int bn)
523 + {
524 +        const char      *mnp = NULL;
525 +        const char      *bnp = NULL;
526 +        const char      *cp;
527 +        
528 +        if (ospec == NULL)
529 +                return -1;
530 +        for (cp = ospec; *cp; cp++)             /* check format position(s) */
531 +                if (*cp == '%') {
532 +                        do
533 +                                ++cp;
534 +                        while (isdigit(*cp));
535 +                        switch (*cp) {
536 +                        case '%':
537 +                                break;
538 +                        case 's':
539 +                                if (mnp != NULL)
540 +                                        return -1;
541 +                                mnp = cp;
542 +                                break;
543 +                        case 'd':
544 +                                if (bnp != NULL)
545 +                                        return -1;
546 +                                bnp = cp;
547 +                                break;
548 +                        default:
549 +                                return -1;
550 +                        }
551 +                }
552 +        if (mnp != NULL) {                      /* create file name */
553 +                if (bnp != NULL) {
554 +                        if (bnp > mnp)
555 +                                sprintf(oname, ospec, mname, bn);
556 +                        else
557 +                                sprintf(oname, ospec, bn, mname);
558 +                        return OF_MODIFIER|OF_BIN;
559 +                }
560 +                sprintf(oname, ospec, mname);
561 +                return OF_MODIFIER;
562 +        }
563 +        if (bnp != NULL) {
564 +                sprintf(oname, ospec, bn);
565 +                return OF_BIN;
566 +        }
567 +        strcpy(oname, ospec);
568 +        return 0;
569 + }
570 +
571   /* write header to the given output stream */
572   void
573 < printheader(FILE *fout)
573 > printheader(FILE *fout, const char *info)
574   {
575          extern char     VersionID[];
576          FILE            *fin = fopen(octree, "r");
577          
578          if (fin == NULL)
579                  quit(1);
580 <        getheader(fin, (gethfunc *)fputs, fout);        /* copy octree header */
580 >        checkheader(fin, "ignore", fout);       /* copy octree header */
581          fclose(fin);
582          printargs(gargc-1, gargv, fout);        /* add our command */
583          fprintf(fout, "SOFTWARE= %s\n", VersionID);
584          fputnow(fout);
585 +        if (info != NULL)                       /* add extra info if given */
586 +                fputs(info, fout);
587          switch (outfmt) {                       /* add output format */
588          case 'a':
589                  fputformat("ascii", fout);
# Line 457 | Line 599 | printheader(FILE *fout)
599                  break;
600          }
601          fputc('\n', fout);
602 + }
603 +
604 + /* write resolution string to given output stream */
605 + void
606 + printresolu(FILE *fout)
607 + {
608          if (xres > 0) {
609                  if (yres > 0)                   /* resolution string */
610                          fprtresolu(xres, yres, fout);
# Line 468 | Line 616 | printheader(FILE *fout)
616   FILE *
617   getofile(const char *ospec, const char *mname, int bn)
618   {
619 <        static int      using_stdout = 0;
620 <        const char      *mnp = NULL;
473 <        const char      *bnp = NULL;
474 <        const char      *cp;
475 <        char            ofname[1024];
619 >        int             ofl;
620 >        char            oname[1024];
621          LUENT           *lep;
622          
623          if (ospec == NULL) {                    /* use stdout? */
624 <                if (!using_stdout && header)
625 <                        printheader(stdout);
624 >                if (!using_stdout) {
625 >                        if (outfmt != 'a')
626 >                                SET_FILE_BINARY(stdout);
627 >                        if (header)
628 >                                printheader(stdout, NULL);
629 >                        printresolu(stdout);
630 >                }
631                  using_stdout = 1;
632                  return stdout;
633          }
634 <        for (cp = ospec; *cp; cp++)             /* check format position(s) */
635 <                if (*cp == '%') {
636 <                        do
637 <                                ++cp;
638 <                        while (isdigit(*cp));
639 <                        switch (*cp) {
490 <                        case '%':
491 <                                break;
492 <                        case 's':
493 <                                if (mnp != NULL)
494 <                                        goto badspec;
495 <                                mnp = cp;
496 <                                break;
497 <                        case 'd':
498 <                                if (bnp != NULL)
499 <                                        goto badspec;
500 <                                bnp = cp;
501 <                                break;
502 <                        default:
503 <                                goto badspec;
504 <                        }
505 <                }
506 <        if (mnp != NULL) {                      /* create file name */
507 <                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 */
634 >        ofl = ofname(oname, ospec, mname, bn);  /* get output name */
635 >        if (ofl < 0) {
636 >                sprintf(errmsg, "bad output format '%s'", ospec);
637 >                error(USER, errmsg);
638 >        }
639 >        lep = lu_find(&ofiletab, oname);        /* look it up */
640          if (lep->key == NULL)                   /* new entry */
641 <                lep->key = strcpy((char *)malloc(strlen(ofname)+1), ofname);
641 >                lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
642          if (lep->data == NULL) {                /* open output file */
643 <                lep->data = (char *)fopen(ofname, "w");
644 <                if (lep->data == NULL) {
645 <                        sprintf(errmsg, "cannot open '%s' for writing", ofname);
643 >                FILE            *fp;
644 >                int             i;
645 >                if (oname[0] == '!')            /* output to command */
646 >                        fp = popen(oname+1, "w");
647 >                else
648 >                        fp = fopen(oname, "w");
649 >                if (fp == NULL) {
650 >                        sprintf(errmsg, "cannot open '%s' for writing", oname);
651                          error(SYSTEM, errmsg);
652                  }
653 <                if (header)
654 <                        printheader((FILE *)lep->data);
653 >                if (outfmt != 'a')
654 >                        SET_FILE_BINARY(fp);
655 >                if (header) {
656 >                        char    info[512];
657 >                        char    *cp = info;
658 >                        if (ofl & OF_MODIFIER) {
659 >                                sprintf(cp, "MODIFIER=%s\n", mname);
660 >                                while (*cp) ++cp;
661 >                        }
662 >                        if (ofl & OF_BIN) {
663 >                                sprintf(cp, "BIN=%d\n", bn);
664 >                                while (*cp) ++cp;
665 >                        }
666 >                        *cp = '\0';
667 >                        printheader(fp, info);
668 >                }
669 >                printresolu(fp);
670 >                                                /* play catch-up */
671 >                for (i = 0; i < lastdone; i++) {
672 >                        static const DCOLOR     nocontrib = BLKCOLOR;
673 >                        put_contrib(nocontrib, fp);
674 >                        if (outfmt == 'a')
675 >                                putc('\n', fp);
676 >                }
677 >                if (xres > 0)
678 >                        fflush(fp);
679 >                lep->data = (char *)fp;
680          }
681          return (FILE *)lep->data;               /* return open file pointer */
531 badspec:
532        sprintf(errmsg, "bad output format '%s'", ospec);
533        error(USER, errmsg);
534        return NULL;            /* pro forma return */
682   }
683  
684   /* read input ray into buffer */
685   int
686   getinp(char *buf, FILE *fp)
687   {
688 +        char    *cp;
689 +        int     i;
690 +
691          switch (inpfmt) {
692          case 'a':
693 <                if (fgets(buf, 128, fp) == NULL)
694 <                        return 0;
693 >                cp = buf;               /* make sure we get 6 floats */
694 >                for (i = 0; i < 6; i++) {
695 >                        if (fgetword(cp, buf+127-cp, fp) == NULL)
696 >                                return 0;
697 >                        if ((cp = fskip(cp)) == NULL || *cp)
698 >                                return 0;
699 >                        *cp++ = ' ';
700 >                }
701 >                getc(fp);               /* get/put eol */
702 >                *cp-- = '\0'; *cp = '\n';
703                  return strlen(buf);
704          case 'f':
705                  if (fread(buf, sizeof(float), 6, fp) < 6)
# Line 556 | Line 714 | getinp(char *buf, FILE *fp)
714          return 0;       /* pro forma return */
715   }
716  
717 < static const float      *rparams = NULL;        /* ray parameter pointer */
717 > static float    rparams[9];             /* traced ray parameters */
718  
719   /* return channel (ray) value */
720   double
# Line 564 | Line 722 | chanvalue(int n)
722   {
723          if (--n < 0 || n >= 6)
724                  error(USER, "illegal channel number ($N)");
725 <        if (rparams == NULL)
568 <                error(USER, "illegal use of $N in constant expression");
569 <        return rparams[n];
725 >        return rparams[n+3];
726   }
727  
728 < /* add ray contribution to the appropriate modifier bin */
728 > /* add current ray contribution to the appropriate modifier bin */
729   void
730 < add_contrib(const char *modn, float rayval[9])
730 > add_contrib(const char *modn)
731   {
732          LUENT   *le = lu_find(&modconttab, modn);
733          MODCONT *mp = (MODCONT *)le->data;
# Line 581 | Line 737 | add_contrib(const char *modn, float rayval[9])
737                  sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
738                  error(USER, errmsg);
739          }
740 <        rparams = rayval + 3;           /* for chanvalue */
585 <        eclock++;
740 >        eclock++;                       /* get bin number */
741          bn = (int)(evalue(mp->binv) + .5);
742          if (bn <= 0)
743                  bn = 0;
744 <        else if (bn > mp->nbins) {      /* new bin */
744 >        else if (bn >= mp->nbins) {     /* new bin */
745                  mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
746 <                                                bn*sizeof(COLOR));
746 >                                                bn*sizeof(DCOLOR));
747                  if (mp == NULL)
748                          error(SYSTEM, "out of memory in add_contrib");
749 <                memset(mp->cbin+mp->nbins, 0, sizeof(COLOR)*(bn+1-mp->nbins));
749 >                memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(bn+1-mp->nbins));
750                  mp->nbins = bn+1;
751                  le->data = (char *)mp;
752          }
753 <        addcolor(mp->cbin[bn], rayval);
599 <        rparams = NULL;
753 >        addcolor(mp->cbin[bn], rparams);
754   }
755  
756   /* output newline to ASCII file and/or flush as requested */
# Line 616 | Line 770 | puteol(const LUENT *e, void *p)
770          return 0;
771   }
772  
773 + /* put out ray contribution to file */
774 + void
775 + put_contrib(const DCOLOR cnt, FILE *fout)
776 + {
777 +        float   fv[3];
778 +        COLR    cv;
779 +
780 +        switch (outfmt) {
781 +        case 'a':
782 +                fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
783 +                break;
784 +        case 'f':
785 +                fv[0] = cnt[0];
786 +                fv[1] = cnt[1];
787 +                fv[2] = cnt[2];
788 +                fwrite(fv, sizeof(float), 3, fout);
789 +                break;
790 +        case 'd':
791 +                fwrite(cnt, sizeof(double), 3, fout);
792 +                break;
793 +        case 'c':
794 +                setcolr(cv, cnt[0], cnt[1], cnt[2]);
795 +                fwrite(cv, sizeof(cv), 1, fout);
796 +                break;
797 +        default:
798 +                error(INTERNAL, "botched output format");
799 +        }
800 + }
801 +
802   /* output ray tallies and clear for next primary */
803   void
804   done_contrib(void)
805   {
806          int     i, j;
807          MODCONT *mp;
808 <        FILE    *fout;
626 <        double  dv[3];
627 <        COLR    cv;
808 >        FILE    *fp;
809                                                  /* output modifiers in order */
810          for (i = 0; i < nmods; i++) {
811                  mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
812 <                for (j = 0; j < mp->nbins; j++) {
813 <                        fout = getofile(mp->outspec, mp->modname, j);
814 <                        switch (outfmt) {
815 <                        case 'a':
816 <                                fprintf(fout, "%.6e\t%.6e\t%.6e\t",
817 <                                                mp->cbin[j][RED],
818 <                                                mp->cbin[j][GRN],
819 <                                                mp->cbin[j][BLU]);
820 <                                break;
821 <                        case 'f':
641 <                                fwrite(mp->cbin[j], sizeof(float), 3, fout);
642 <                                break;
643 <                        case 'd':
644 <                                dv[0] = mp->cbin[j][0];
645 <                                dv[1] = mp->cbin[j][1];
646 <                                dv[2] = mp->cbin[j][2];
647 <                                fwrite(dv, sizeof(double), 3, fout);
648 <                                break;
649 <                        case 'c':
650 <                                setcolr(cv, mp->cbin[j][RED],
651 <                                        mp->cbin[j][GRN], mp->cbin[j][BLU]);
652 <                                fwrite(cv, sizeof(COLR), 1, fout);
653 <                                break;
654 <                        default:
655 <                                error(INTERNAL, "botched output format");
656 <                        }
657 <                }
812 >                fp = getofile(mp->outspec, mp->modname, 0);
813 >                put_contrib(mp->cbin[0], fp);
814 >                if (mp->nbins > 3 &&            /* minor optimization */
815 >                                fp == getofile(mp->outspec, mp->modname, 1))
816 >                        for (j = 1; j < mp->nbins; j++)
817 >                                put_contrib(mp->cbin[j], fp);
818 >                else
819 >                        for (j = 1; j < mp->nbins; j++)
820 >                                put_contrib(mp->cbin[j],
821 >                                        getofile(mp->outspec, mp->modname, j));
822                                                  /* clear for next ray tree */
823 <                memset(mp->cbin, 0, sizeof(COLOR)*mp->nbins);
823 >                memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
824          }
825          --waitflush;                            /* terminate records */
826          lu_doall(&ofiletab, puteol, NULL);
827 <        if (!waitflush)
827 >        if (using_stdout & (outfmt == 'a'))
828 >                putc('\n', stdout);
829 >        if (!waitflush) {
830                  waitflush = xres;
831 +                if (using_stdout)
832 +                        fflush(stdout);
833 +        }
834   }
835  
836 < /* process (or save) ray tree produced by rtrace process */
836 > /* queue completed ray tree produced by rtrace process */
837   void
838 < process_rays(struct rtproc *rtp)
838 > queue_raytree(struct rtproc *rtp)
839   {
840 <        struct rtproc   *rtu;
841 <                                        /* check if time to process it */
842 <        if (rtp->raynum == lastdone+1) {
843 <                int             n = rtp->bpos - rtp->buf;
840 >        struct rtproc   *rtu, *rtl = NULL;
841 >                                        /* insert following ray order */
842 >        for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
843 >                if (rtp->raynum < rtu->raynum)
844 >                        break;
845 >        rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
846 >        if (rtu == NULL)
847 >                error(SYSTEM, "out of memory in queue_raytree");
848 >        *rtu = *rtp;
849 >        if (rtl == NULL) {
850 >                rtu->next = rt_unproc;
851 >                rt_unproc = rtu;
852 >        } else {
853 >                rtu->next = rtl->next;
854 >                rtl->next = rtu;
855 >        }
856 >        rtp->raynum = 0;                /* clear path for next ray tree */
857 >        rtp->bsiz = 0;
858 >        rtp->buf = NULL;
859 >        rtp->nbr = 0;
860 > }
861 >
862 > /* process completed ray trees from our queue */
863 > void
864 > process_queue(void)
865 > {
866 >        char    modname[128];
867 >                                        /* ray-ordered queue */
868 >        while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
869 >                struct rtproc   *rtp = rt_unproc;
870 >                int             n = rtp->nbr;
871                  const char      *cp = rtp->buf;
872                  while (n > 0) {         /* process rays */
873 <                        char    matname[128];
678 <                        char    *mnp = matname;
873 >                        register char   *mnp = modname;
874                                          /* skip leading tabs */
875                          while (n > 0 && *cp == '\t') {
876                                  cp++; n--;
877                          }
878 <                                        /* get material name */
878 >                        if (!n || !(isalpha(*cp) | (*cp == '_')))
879 >                                error(USER, "bad modifier name from rtrace");
880 >                                        /* get modifier name */
881                          while (n > 0 && *cp != '\t') {
882                                  *mnp++ = *cp++; n--;
883                          }
687                        if (!n)
688                                error(USER, "botched modifer name from rtrace");
884                          *mnp = '\0';
885 <                        cp++; n--;      /* skip terminating tab */
885 >                        cp++; n--;      /* eat following tab */
886                          if (n < (int)(sizeof(float)*9))
887                                  error(USER, "incomplete ray value from rtrace");
888                                          /* add ray contribution */
889 <                        add_contrib(matname, (float *)cp);
889 >                        memcpy(rparams, cp, sizeof(float)*9);
890                          cp += sizeof(float)*9; n -= sizeof(float)*9;
891 +                        add_contrib(modname);
892                  }
893                  done_contrib();         /* sum up contributions & output */
894                  lastdone = rtp->raynum;
895 <                free(rtp->buf);
896 <                                        /* catch up with unprocessed list */
897 <                while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
702 <                        process_rays(rt_unproc);
703 <                        rt_unproc = (rtu=rt_unproc)->next;
704 <                        free(rtu);
705 <                }
706 <        } else {                        /* else insert in unprocessed list */
707 <                struct rtproc   *rtl = NULL;
708 <                for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
709 <                        if (rtp->raynum < rtu->raynum)
710 <                                break;
711 <                rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
712 <                if (rtu == NULL)
713 <                        error(SYSTEM, "out of memory in process_rays");
714 <                *rtu = *rtp;
715 <                if (rtl == NULL) {
716 <                        rtu->next = rt_unproc;
717 <                        rt_unproc = rtu;
718 <                } else {
719 <                        rtu->next = rtl->next;
720 <                        rtl->next = rtu;
721 <                }
895 >                free(rtp->buf);         /* free up buffer space */
896 >                rt_unproc = rtp->next;
897 >                free(rtp);              /* done with this ray tree */
898          }
723        rtp->raynum = 0;                /* clear path for next ray tree */
724        rtp->bsiz = 0;
725        rtp->buf = NULL;
899   }
900  
901   /* wait for rtrace process to finish with ray tree */
# Line 763 | Line 936 | wait_rproc(void)
936                          if (rt->buf == NULL) {
937                                  rt->bsiz = treebufsiz;
938                                  rt->buf = (char *)malloc(treebufsiz);
939 <                        } else if (rt->bpos + BUFSIZ > rt->buf + rt->bsiz) {
939 >                        } else if (rt->nbr + BUFSIZ > rt->bsiz) {
940                                  if (rt->bsiz + BUFSIZ <= treebufsiz)
941                                          rt->bsiz = treebufsiz;
942                                  else
943 <                                        rt->bsiz = treebufsiz += BUFSIZ;
943 >                                        treebufsiz = rt->bsiz += BUFSIZ;
944                                  rt->buf = (char *)realloc(rt->buf, rt->bsiz);
945                          }
946                          if (rt->buf == NULL)
947                                  error(SYSTEM, "out of memory in wait_rproc");
948 <                        nr = read(rt->pd.r, rt->bpos,
949 <                                        rt->buf + rt->bsiz - rt->bpos);
777 <                        if (!nr)
948 >                        nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
949 >                        if (nr <= 0)
950                                  error(USER, "rtrace process died");
951 <                        rt->bpos += nr;         /* advance buffer & check */
952 <                        if (rt->bpos[-1] == '\t' && rt->bpos[-2] == '-') {
953 <                                rt->bpos -= 2;  /* elide terminator */
954 <                                process_rays(rt);
951 >                        rt->nbr += nr;          /* advance & check */
952 >                        if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
953 >                                                        "~\t~\t", 4)) {
954 >                                rt->nbr -= 4;   /* elide terminator */
955 >                                queue_raytree(rt);
956                                  rtfree = rt;    /* ready for next ray */
957                          }
958                  }
# Line 801 | Line 974 | get_rproc(void)
974  
975   /* trace ray contributions (main loop) */
976   void
977 < tracecontribs(FILE *fin)
977 > trace_contribs(FILE *fin)
978   {
979          char            inpbuf[128];
980          int             iblen;
981          struct rtproc   *rtp;
982                                                  /* loop over input */
983          while ((iblen = getinp(inpbuf, fin)) > 0) {
984 <                if (lastray+1 < lastray) {      /* counter rollover? */
984 >                if (lastray+1 < lastray ||      /* need reset? */
985 >                                queue_length() > 5*nrtprocs()) {
986                          while (wait_rproc() != NULL)
987 <                                ;
987 >                                process_queue();
988                          lastdone = lastray = 0;
989                  }
990                  rtp = get_rproc();              /* get avail. rtrace process */
991 <                rtp->raynum = ++lastray;        /* assign this ray to it */
991 >                rtp->raynum = ++lastray;        /* assign ray to it */
992                  writebuf(rtp->pd.w, inpbuf, iblen);
993 <                if (!--raysleft)
994 <                        break;                  /* explicit EOF */
993 >                if (raysleft && !--raysleft)
994 >                        break;
995 >                process_queue();                /* catch up with results */
996          }
997          while (wait_rproc() != NULL)            /* process outstanding rays */
998 <                ;
998 >                process_queue();
999 >        if (raysleft)
1000 >                error(USER, "unexpected EOF on input");
1001 >        lu_done(&ofiletab);                     /* close output files */
1002 > }
1003 >
1004 > /* seek on the given output file */
1005 > static int
1006 > myseeko(const LUENT *e, void *p)
1007 > {
1008 >        if (fseeko((FILE *)e->data, *(off_t *)p, SEEK_CUR) < 0) {
1009 >                sprintf(errmsg, "seek error on file '%s'", e->key);
1010 >                error(SYSTEM, errmsg);
1011 >        }
1012 > }
1013 >
1014 > /* recover output if possible */
1015 > void
1016 > recover_output(FILE *fin)
1017 > {
1018 >        off_t   lastout = -1;
1019 >        int     outvsiz;
1020 >        char    *outvfmt;
1021 >        int     i, j;
1022 >        MODCONT *mp;
1023 >        int     ofl;
1024 >        char    oname[1024];
1025 >        LUENT   *ment, *oent;
1026 >        FILE    *fp;
1027 >        off_t   nvals;
1028 >
1029 >        switch (outfmt) {
1030 >        case 'a':
1031 >                error(USER, "cannot recover ASCII output");
1032 >                return;
1033 >        case 'f':
1034 >                outvsiz = sizeof(float)*3;
1035 >                outvfmt = "float";
1036 >                break;
1037 >        case 'd':
1038 >                outvsiz = sizeof(double)*3;
1039 >                outvfmt = "double";
1040 >                break;
1041 >        case 'c':
1042 >                outvsiz = sizeof(COLR);
1043 >                outvfmt = COLRFMT;
1044 >                break;
1045 >        default:
1046 >                error(INTERNAL, "botched output format");
1047 >                return;
1048 >        }
1049 >                                                /* check modifier outputs */
1050 >        for (i = 0; i < nmods; i++) {
1051 >                ment = lu_find(&modconttab,modname[i]);
1052 >                mp = (MODCONT *)ment->data;
1053 >                if (mp->outspec == NULL)
1054 >                        error(USER, "cannot recover from stdout");
1055 >                for (j = 0; ; j++) {            /* check each bin's file */
1056 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1057 >                        if (ofl < 0)
1058 >                                error(USER, "bad output file specification");
1059 >                        oent = lu_find(&ofiletab, oname);
1060 >                        if (oent->data != NULL) { /* saw this one already */
1061 >                                if (ofl & OF_BIN)
1062 >                                        continue;
1063 >                                break;
1064 >                        }
1065 >                        if (oname[0] == '!')
1066 >                                error(USER, "cannot recover from command");
1067 >                                                /* open output */
1068 >                        fp = fopen(oname, "rb+");
1069 >                        if (fp == NULL) {
1070 >                                if (j)
1071 >                                        break;  /* assume end of modifier */
1072 >                                sprintf(errmsg, "missing recover file '%s'",
1073 >                                                oname);
1074 >                                error(USER, errmsg);
1075 >                        }
1076 >                        nvals = lseek(fileno(fp), 0, SEEK_END);
1077 >                        if (nvals <= 0) {
1078 >                                lastout = 0;    /* empty output, quit here */
1079 >                                fclose(fp);
1080 >                                break;
1081 >                        }
1082 >                        lseek(fileno(fp), 0, SEEK_SET);
1083 >                        if (header) {
1084 >                                int     xr, yr;
1085 >                                if (checkheader(fp, outvfmt, NULL) != 1) {
1086 >                                        sprintf(errmsg,
1087 >                                                "format mismatch for '%s'",
1088 >                                                        oname);
1089 >                                        error(USER, errmsg);
1090 >                                }
1091 >                                if (xres > 0 && yres > 0 &&
1092 >                                                (!fscnresolu(&xr, &yr, fp) ||
1093 >                                                        xr != xres ||
1094 >                                                        yr != yres)) {
1095 >                                        sprintf(errmsg,
1096 >                                                "resolution mismatch for '%s'",
1097 >                                                        oname);
1098 >                                        error(USER, errmsg);
1099 >                                }
1100 >                        }
1101 >                        nvals = (nvals - (off_t)ftell(fp)) / outvsiz;
1102 >                        if (lastout < 0 || nvals < lastout)
1103 >                                lastout = nvals;
1104 >                        if (oent->key == NULL) /* new entry */
1105 >                                oent->key = strcpy((char *)
1106 >                                                malloc(strlen(oname)+1), oname);
1107 >                        oent->data = (char *)fp;
1108 >                        if (!(ofl & OF_BIN))
1109 >                                break;          /* no bin separation */
1110 >                }
1111 >                if (!lastout) {                 /* empty output */
1112 >                        error(WARNING, "no previous data to recover");
1113 >                        lu_done(&ofiletab);     /* reclose all outputs */
1114 >                        return;
1115 >                }
1116 >                if (j > mp->nbins) {            /* preallocate modifier bins */
1117 >                        mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
1118 >                                                        (j-1)*sizeof(DCOLOR));
1119 >                        if (mp == NULL)
1120 >                                error(SYSTEM, "out of memory in recover_output");
1121 >                        memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
1122 >                        mp->nbins = j;
1123 >                        ment->data = (char *)mp;
1124 >                }
1125 >        }
1126 >        if (lastout < 0) {
1127 >                error(WARNING, "no output files to recover");
1128 >                return;
1129 >        }
1130 >        if (raysleft && lastout >= raysleft) {
1131 >                error(WARNING, "output appears to be complete");
1132 >                /* XXX should read & discard input? */
1133 >                quit(0);
1134 >        }
1135 >                                                /* seek on all files */
1136 >        nvals = lastout * outvsiz;
1137 >        lu_doall(&ofiletab, myseeko, &nvals);
1138 >                                                /* skip repeated input */
1139 >        for (nvals = 0; nvals < lastout; nvals++)
1140 >                if (getinp(oname, fin) <= 0)
1141 >                        error(USER, "unexpected EOF on input");
1142 >        lastray = lastdone = (unsigned long)lastout;
1143 >        if (raysleft)
1144 >                raysleft -= lastray;
1145   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines