ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.44
Committed: Thu Nov 15 18:32:34 2007 UTC (16 years, 5 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.43: +21 -7 lines
Log Message:
Allow -P and -PP options to be set by user

File Contents

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