ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/rxpiece.cpp
Revision: 2.10
Committed: Thu Jan 9 17:25:37 2025 UTC (3 months, 3 weeks ago) by greg
Branch: MAIN
Changes since 2.9: +1 -5 lines
Log Message:
fix(rxpiece,rxpict): Make sure child processes are waited for

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.10 static const char RCSid[] = "$Id: rxpiece.cpp,v 2.9 2025/01/02 20:19:48 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * rxpiece.cpp - main for rxpiece tile rendering program
6     */
7    
8     #include "copyright.h"
9    
10     #include <time.h>
11     #include <signal.h>
12     #include <sys/mman.h>
13     #include <unistd.h>
14    
15     #include "platform.h"
16     #include "RpictSimulManager.h"
17 greg 2.5 #include "ambient.h"
18     #include "pmapray.h"
19 greg 2.1 #include "random.h"
20    
21     extern char *progname; /* argv[0] */
22     const char *sigerr[NSIG]; /* signal error messages */
23    
24     VIEW ourview = STDVIEW; /* global view parameters */
25     int hresolu = 1024; /* horizontal resolution */
26     int vresolu = 1024; /* vertical resolution */
27     double pixaspect = 1.0; /* pixel aspect ratio */
28     int hres, vres; /* current image resolution for srcdraw.c */
29    
30     int tileGrid[2] = {5,5}; // tile subdivisions
31    
32     int psample = 4; /* pixel sample size */
33     double maxdiff = .05; /* max. difference for interpolation */
34     double dstrpix = 0.67; /* square pixel distribution */
35    
36     double mblur = 0.; /* motion blur parameter (unused) */
37    
38     double dblur = 0.; /* depth-of-field blur parameter */
39    
40 greg 2.7 int nproc = 1; /* number of processes to run (-1 in child) */
41 greg 2.1
42     RpictSimulManager myRPmanager; // global simulation manager
43    
44     static void onsig(int signo);
45     static void onalrm(int signo);
46     static void sigdie(int signo, const char *msg);
47     static void printdefaults(void);
48     static RenderDataType rpiece(char *pout, RenderDataType dt, char *zout);
49    
50     /* rxpiece additional features */
51     #define RXPIECE_FEATURES "Recovery\nIrradianceCalc\nViewTypes=v,l,a,h,s,c\n" \
52     "ParticipatingMedia=Mist\n" \
53     "HessianAmbientCache\nAmbientAveraging\nAmbientValueSharing\n" \
54     "PixelJitter\nPixelSampling\nPixelDepthOfField\n" \
55     "SmallSourceDrawing\n" \
56     "AdaptiveShadowTesting\nOutputs=v,l\n" \
57     "OutputCS=RGB,XYZ,prims,spec\n"
58    
59 greg 2.7 // Exit program
60 greg 2.1 void
61     quit(int code) /* quit program */
62     {
63 greg 2.9 exit(code); // don't bother to free data structs
64 greg 2.1 }
65    
66 greg 2.8 /* Set default options */
67     static void
68     default_options(void)
69     {
70     shadthresh = .05;
71     shadcert = .5;
72     srcsizerat = .25;
73     directrelay = 1;
74     ambacc = 0.2;
75     ambres = 64;
76     ambdiv = 512;
77     ambssamp = 128;
78     maxdepth = 7;
79     }
80 greg 2.1
81     int
82     main(int argc, char *argv[])
83     {
84     #define check(ol,al) if (argv[i][ol] || \
85     badarg(argc-i-1,argv+i+1,al)) \
86     goto badopt
87     #define check_bool(olen,var) switch (argv[i][olen]) { \
88     case '\0': var = !var; break; \
89     case 'y': case 'Y': case 't': case 'T': \
90     case '+': case '1': var = 1; break; \
91     case 'n': case 'N': case 'f': case 'F': \
92     case '-': case '0': var = 0; break; \
93     default: goto badopt; }
94     RGBPRIMS our_prims; /* private output color primitives */
95     RenderDataType dtype = RDTrgbe; // output data flags
96     char *outfile = NULL;
97     char *zfile = NULL;
98     int outfmt = 'c';
99     int rval;
100     int i;
101     /* global program name */
102     progname = argv[0];
103     /* feature check only? */
104     strcat(RFeatureList, RXPIECE_FEATURES);
105     if (argc > 1 && !strcmp(argv[1], "-features"))
106     return feature_status(argc-2, argv+2);
107 greg 2.8 /* set defaults */
108     default_options();
109 greg 2.1 /* option city */
110     for (i = 1; i < argc; i++) {
111     /* expand arguments */
112     while ((rval = expandarg(&argc, &argv, i)) > 0)
113     ;
114     if (rval < 0) {
115     sprintf(errmsg, "cannot expand '%s'", argv[i]);
116     error(SYSTEM, errmsg);
117     }
118     if (argv[i] == NULL || argv[i][0] != '-')
119     break; /* break from options */
120     if (!strcmp(argv[i], "-version")) {
121     puts(VersionID);
122     quit(0);
123     }
124     if (!strcmp(argv[i], "-defaults") ||
125     !strcmp(argv[i], "-help")) {
126     printdefaults();
127     quit(0);
128     }
129     rval = getrenderopt(argc-i, argv+i);
130     if (rval >= 0) {
131     i += rval;
132     continue;
133     }
134     rval = getviewopt(&ourview, argc-i, argv+i);
135     if (rval >= 0) {
136     i += rval;
137     continue;
138     }
139     /* rxpiece options */
140     switch (argv[i][1]) {
141     case 'v': /* view file */
142     if (argv[i][2] != 'f')
143     goto badopt;
144     check(3,"s");
145     rval = viewfile(argv[++i], &ourview, NULL);
146     if (rval < 0) {
147     sprintf(errmsg,
148     "cannot open view file \"%s\"",
149     argv[i]);
150     error(SYSTEM, errmsg);
151     } else if (rval == 0) {
152     sprintf(errmsg,
153     "bad view file \"%s\"",
154     argv[i]);
155     error(USER, errmsg);
156     }
157     break;
158     case 'n': /* number of processes */
159     check(2,"i");
160     nproc = atoi(argv[++i]);
161     if (nproc < 0 && (nproc += RadSimulManager::GetNCores()) <= 0)
162     nproc = 1;
163     break;
164     case 'f': /* output format */
165     if ((argv[i][2] != 'c') & (argv[i][2] != 'f')
166     || argv[i][3])
167     goto badopt;
168     outfmt = argv[i][2];
169     break;
170     case 'p': /* pixel */
171     switch (argv[i][2]) {
172     case 's': /* sample */
173     check(3,"i");
174     psample = atoi(argv[++i]);
175     if (psample < 1) psample = 1;
176     break;
177     case 't': /* threshold */
178     check(3,"f");
179     maxdiff = atof(argv[++i]);
180     break;
181     case 'j': /* jitter */
182     check(3,"f");
183     dstrpix = atof(argv[++i]);
184     break;
185     case 'a': /* aspect */
186     check(3,"f");
187     pixaspect = atof(argv[++i]);
188     break;
189     case 'd': /* aperture */
190     check(3,"f");
191     dblur = atof(argv[++i]);
192     dblur *= (dblur > 0);
193     break;
194     case 'R': /* standard RGB output */
195     if (strcmp(argv[i]+2, "RGB"))
196     goto badopt;
197     myRPmanager.prims = stdprims;
198     dtype = RDTnewCT(dtype, RDTrgbe);
199     break;
200     case 'X': /* XYZ output */
201     if (strcmp(argv[i]+2, "XYZ"))
202     goto badopt;
203     myRPmanager.prims = xyzprims;
204     dtype = RDTnewCT(dtype, RDTxyze);
205     break;
206     case 'c': /* chromaticities */
207     check(3,"ffffffff");
208     rval = 0;
209     for (int j = 0; j < 8; j++) {
210     our_prims[0][j] = atof(argv[++i]);
211     rval |= fabs(our_prims[0][j]-stdprims[0][j]) > .001;
212     }
213     if (rval) {
214     if (!colorprimsOK(our_prims))
215     error(USER, "illegal primary chromaticities");
216     myRPmanager.prims = our_prims;
217     } else
218     myRPmanager.prims = stdprims;
219     dtype = RDTnewCT(dtype, RDTrgbe);
220     break;
221     default:
222     goto badopt;
223     }
224     break;
225     case 'd': /* reference depth */
226     if (argv[i][2] || !myRPmanager.SetReferenceDepth(argv[++i]))
227     goto badopt;
228     dtype = RDTnewDT(dtype, RDTdshort);
229     break;
230     case 'x': /* x resolution */
231     check(2,"i");
232     hresolu = atoi(argv[++i]);
233     break;
234     case 'y': /* y resolution */
235     check(2,"i");
236     vresolu = atoi(argv[++i]);
237     break;
238     case 'X': /* horizontal tile subdivisions */
239     check(2,"i");
240     tileGrid[0] = atoi(argv[++i]);
241     break;
242     case 'Y': /* vertical tile subdivisions */
243     check(2,"i");
244     tileGrid[1] = atoi(argv[++i]);
245     break;
246     case 'o': /* output file */
247     check(2,"s");
248     outfile = argv[++i];
249     break;
250     case 'z': /* z file */
251     check(2,"s");
252     zfile = argv[++i];
253     break;
254     #if MAXCSAMP>3
255     case 'c': /* output spectral results */
256     if (argv[i][2] != 'o')
257     goto badopt;
258     rval = (myRPmanager.prims == NULL);
259     check_bool(3,rval);
260     if (rval)
261     myRPmanager.prims = NULL;
262     else if (myRPmanager.prims == NULL)
263     myRPmanager.prims = stdprims;
264     dtype = RDTnewCT(dtype, rval ? RDTscolr : RDTrgbe);
265     break;
266     #endif
267     case 'w': /* warnings */
268     rval = erract[WARNING].pf != NULL;
269     check_bool(2,rval);
270     if (rval) erract[WARNING].pf = wputs;
271     else erract[WARNING].pf = NULL;
272     break;
273     default:
274     goto badopt;
275     }
276     }
277     if (maxdiff <= FTINY) /* check for useless sampling */
278     psample = 1;
279     if (outfile == NULL)
280     error(USER, "missing output file (-o option)");
281     if (zfile == NULL) /* set up depth output */
282     dtype = RDTnewDT(dtype, RDTnone);
283     else if (!RDTdepthT(dtype))
284     dtype = RDTnewDT(dtype, RDTdfloat);
285     /* check pixel output type */
286     if ((myRPmanager.prims == NULL) & (NCSAMP == 3)) {
287     myRPmanager.prims = stdprims;
288     dtype = RDTnewCT(dtype, RDTrgbe);
289     }
290     if (outfmt == 'f')
291     switch (RDTcolorT(dtype)) {
292     case RDTrgbe:
293     dtype = RDTnewCT(dtype, RDTrgb);
294     break;
295     case RDTxyze:
296     dtype = RDTnewCT(dtype, RDTxyz);
297     break;
298     case RDTscolr:
299     dtype = RDTnewCT(dtype, RDTscolor);
300     break;
301     case RDTrgb:
302     case RDTxyz:
303     case RDTscolor:
304     break;
305     default:
306     error(INTERNAL, "botched color output type");
307     }
308     /* set up signal handling */
309     sigdie(SIGINT, "Interrupt");
310     sigdie(SIGHUP, "Hangup");
311     sigdie(SIGTERM, "Terminate");
312     sigdie(SIGPIPE, "Broken pipe");
313     signal(SIGALRM, onalrm); // used to gracefully terminate
314     #ifdef SIGXCPU
315     sigdie(SIGXCPU, "CPU limit exceeded");
316     sigdie(SIGXFSZ, "File size exceeded");
317     #endif
318     #ifdef NICE
319     nice(NICE); /* lower priority */
320     #endif
321     if (i < argc-1)
322     goto badopt;
323     // load octree
324     if (!myRPmanager.LoadOctree(argv[i]))
325     error(USER, "missing octree argument");
326     // add new header info
327     myRPmanager.AddHeader(i, argv);
328     {
329     char buf[128] = "SOFTWARE= ";
330     strcpy(buf+10, VersionID);
331     myRPmanager.AddHeader(buf);
332     }
333     // render tiles
334     dtype = rpiece(outfile, dtype, zfile);
335    
336 greg 2.7 ambsync(); // flush ambient cache
337    
338     ray_done_pmap(); /* PMAP: free photon maps */
339    
340 greg 2.5 quit(dtype==RDTnone); // status is 1 on failure
341 greg 2.1
342     badopt:
343     sprintf(errmsg, "command line error at '%s'", argv[i]);
344     error(USER, errmsg);
345     return 1; /* pro forma return */
346    
347     #undef check
348     #undef check_bool
349     }
350    
351    
352     void
353     wputs( /* warning output function */
354     const char *s
355     )
356     {
357 greg 2.6 if (!erract[WARNING].pf)
358     return; // warnings were disabled!
359 greg 2.1 int lasterrno = errno;
360     eputs(s);
361     errno = lasterrno;
362     }
363    
364    
365     void
366     eputs( /* put string to stderr */
367     const char *s
368     )
369     {
370     static int midline = 0;
371    
372     if (!*s)
373     return;
374     if (!midline++) {
375     fputs(progname, stderr);
376     fputs(": ", stderr);
377     }
378     fputs(s, stderr);
379     if (s[strlen(s)-1] == '\n') {
380     fflush(stderr);
381     midline = 0;
382     }
383     }
384    
385    
386     static void
387     onsig( /* fatal signal */
388     int signo
389     )
390     {
391     static int gotsig = 0;
392    
393     if (gotsig++) /* two signals and we're gone! */
394     _exit(signo);
395    
396     alarm(30); /* allow 30 seconds to clean up */
397     signal(SIGALRM, SIG_DFL); /* make certain we do die */
398     eputs("signal - ");
399     eputs(sigerr[signo]);
400     eputs("\n");
401     quit(3);
402     }
403    
404    
405     static bool gotALRM = false; // flag for ALRM signal
406    
407     static void
408     onalrm(int signo)
409     {
410     gotALRM = true;
411     }
412    
413    
414     static void
415     sigdie( /* set fatal signal */
416     int signo,
417     const char *msg
418     )
419     {
420     if (signal(signo, onsig) == SIG_IGN)
421     signal(signo, SIG_IGN);
422     sigerr[signo] = msg;
423     }
424    
425    
426     static void
427     printdefaults(void) /* print default values to stdout */
428     {
429     printf("-n %-2d\t\t\t\t# number of rendering processes\n", nproc);
430     printf("-vt%c\t\t\t\t# view type %s\n", ourview.type,
431     ourview.type==VT_PER ? "perspective" :
432     ourview.type==VT_PAR ? "parallel" :
433     ourview.type==VT_HEM ? "hemispherical" :
434     ourview.type==VT_ANG ? "angular" :
435     ourview.type==VT_CYL ? "cylindrical" :
436     ourview.type==VT_PLS ? "planisphere" :
437     "unknown");
438     printf("-vp %f %f %f\t# view point\n",
439     ourview.vp[0], ourview.vp[1], ourview.vp[2]);
440     printf("-vd %f %f %f\t# view direction\n",
441     ourview.vdir[0], ourview.vdir[1], ourview.vdir[2]);
442     printf("-vu %f %f %f\t# view up\n",
443     ourview.vup[0], ourview.vup[1], ourview.vup[2]);
444     printf("-vh %f\t\t\t# view horizontal size\n", ourview.horiz);
445     printf("-vv %f\t\t\t# view vertical size\n", ourview.vert);
446     printf("-vo %f\t\t\t# view fore clipping plane\n", ourview.vfore);
447     printf("-va %f\t\t\t# view aft clipping plane\n", ourview.vaft);
448     printf("-vs %f\t\t\t# view shift\n", ourview.hoff);
449     printf("-vl %f\t\t\t# view lift\n", ourview.voff);
450     printf("-x %-9d\t\t\t# x resolution\n", hresolu);
451     printf("-y %-9d\t\t\t# y resolution\n", vresolu);
452     printf("-X %-9d\t\t\t# horizontal tile divisions\n", tileGrid[0]);
453     printf("-Y %-9d\t\t\t# vertical tile divisions\n", tileGrid[1]);
454     if (myRPmanager.prims == stdprims)
455     printf("-pRGB\t\t\t\t# standard RGB color output\n");
456     else if (myRPmanager.prims == xyzprims)
457     printf("-pXYZ\t\t\t\t# CIE XYZ color output\n");
458     else if (myRPmanager.prims != NULL)
459     printf("-pc %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f\t# output color primaries and white point\n",
460     myRPmanager.prims[RED][0], myRPmanager.prims[RED][1],
461     myRPmanager.prims[GRN][0], myRPmanager.prims[GRN][1],
462     myRPmanager.prims[BLU][0], myRPmanager.prims[BLU][1],
463     myRPmanager.prims[WHT][0], myRPmanager.prims[WHT][1]);
464     if (NCSAMP > 3)
465     printf(myRPmanager.prims != NULL ? "-co-\t\t\t\t# output tristimulus colors\n" :
466     "-co+\t\t\t\t# output spectral values\n");
467     printf("-pa %f\t\t\t# pixel aspect ratio\n", pixaspect);
468     printf("-pj %f\t\t\t# pixel jitter\n", dstrpix);
469     printf("-pd %f\t\t\t# pixel depth-of-field\n", dblur);
470     printf("-ps %-9d\t\t\t# pixel sample\n", psample);
471     printf("-pt %f\t\t\t# pixel threshold\n", maxdiff);
472     printf(erract[WARNING].pf != NULL ?
473     "-w+\t\t\t\t# warning messages on\n" :
474     "-w-\t\t\t\t# warning messages off\n");
475     print_rdefaults();
476     }
477    
478    
479     // Struct for tracking tiles being rendered in mapped file / shared memory
480     struct TileProg {
481     short status; // 0==Unstarted, -1==InProgress, 1==Done
482     pid_t pID; // process operating on tile
483     } *tprog = NULL; // shared tile progress array
484    
485     #define tile_p(ti) (tprog + (ti)[1]*tileGrid[0] + (ti)[0])
486    
487     // Return true if tile is renderable
488     static bool
489     renderable_tile(TileProg *tp)
490     {
491     if (tp->status < 0 && kill(tp->pID, 0) < 0)
492     tp->status = 0; // dead process - reset
493    
494     return !tp->status;
495     }
496    
497    
498     // handle multi-processing if requested, return true if all done
499     static bool
500     children_finished()
501     {
502     if (nproc <= 1) // single process -> run in parent
503     return false;
504     int cnt = 0; // else count ready-to-go tiles
505     int ti[2];
506     for (ti[1] = 0; ti[1] < tileGrid[1]; ti[1]++)
507     for (ti[0] = 0; ti[0] < tileGrid[0]; ti[0]++)
508     cnt += renderable_tile(tile_p(ti));
509 greg 2.2 if (!cnt)
510     return false; // parent can do nothing
511 greg 2.1 if (cnt < nproc) {
512     sprintf(errmsg, "only %d renderable tiles, reducing process count", cnt);
513     error(WARNING, errmsg);
514     if ((nproc = cnt) == 1)
515     return false; // back to single process
516     }
517     cow_memshare(); // else we'll be sharing memory
518     fflush(NULL); // and forking children
519     pid_t cpid; // create nproc children
520     for (cnt = nproc; cnt && (cpid = fork()) != 0; cnt--)
521     if (cpid < 0)
522     error(SYSTEM, "fork error!");
523    
524     if (cpid == 0) { // children render tiles
525     sleep(nproc - cnt); // avoid race conditions
526 greg 2.7 nproc = -1; // flag as child
527 greg 2.1 return false;
528     }
529     cow_doneshare(); // parent frees memory and waits
530     signal(SIGALRM, SIG_IGN);
531     myRPmanager.Cleanup(true);
532     int nfailed = 0;
533     int status;
534     for (cnt = nproc; cnt && wait(&status) > 0; cnt--)
535     if (status) {
536     sprintf(errmsg, "child exited with status %d", status);
537     error(WARNING, errmsg);
538     if (!nfailed++ & (cnt > 1)) {
539     kill(0, SIGALRM);
540     error(WARNING, "waiting for other tiles to finish...");
541     }
542     }
543     if (cnt) {
544     sprintf(errmsg, "lost track of %d children", cnt);
545     error(WARNING, errmsg);
546     }
547     if (nfailed) {
548     sprintf(errmsg, "%d tiles were not completed", nfailed);
549     error(USER, errmsg);
550     }
551     return true; // all done!
552     }
553    
554     // return next renderable tile, false if everything is done
555     static bool
556     nexttile(int ti[2])
557     {
558     static pid_t ourpID = 0;
559     static short * tlist = NULL;
560     static int tlen = 0;
561     static int tnext = 0;
562    
563     if (gotALRM) { // pre-empting new work?
564     if (tlist) {
565     sprintf(errmsg, "process %d got alarm, exiting", ourpID);
566     CHECK(tnext<tlen, WARNING, errmsg);
567     free(tlist); tlist = NULL;
568     }
569     return false;
570     }
571     if (!tlist) { // initialize random tile list
572     ABitMap2 todoMap(tileGrid[0], tileGrid[1]);
573     tlen = 0;
574     for (ti[1] = 0; ti[1] < tileGrid[1]; ti[1]++)
575     for (ti[0] = 0; ti[0] < tileGrid[0]; ti[0]++)
576     if (renderable_tile(tile_p(ti))) {
577     todoMap.Set(ti[0], ti[1]);
578     tlen++;
579     }
580     if (!tlen)
581     return false; // nothing to do!
582     tlist = (short *)malloc(sizeof(short)*2*tlen);
583     CHECK(!tlist, SYSTEM, "out of memory in nexttile()");
584     tlen = 0; // assign entries
585     for (ti[0] = ti[1] = 0; todoMap.Find(&ti[0], &ti[1]); ti[0]++) {
586     tlist[2*tlen] = ti[0];
587     tlist[2*tlen+1] = ti[1];
588     tlen++;
589     }
590     // shuffle order w/ Fisher-Yates
591     for (int i = 0; i < tlen-1; i++) {
592     const int ix = irandom(tlen-i) + i;
593     ti[0] = tlist[2*i];
594     ti[1] = tlist[2*i+1];
595     tlist[2*i] = tlist[2*ix];
596     tlist[2*i+1] = tlist[2*ix+1];
597     tlist[2*ix] = ti[0];
598     tlist[2*ix+1] = ti[1];
599     }
600     ourpID = getpid(); // save time on system calls
601     }
602     while (tnext < tlen) { // find first available
603     ti[0] = tlist[2*tnext];
604     ti[1] = tlist[2*tnext+1];
605     tnext++; // take if still unclaimed
606     if (renderable_tile(tile_p(ti))) {
607     tile_p(ti)->status = -1;
608     tile_p(ti)->pID = ourpID;
609     return true;
610     }
611     }
612     free(tlist); tlist = NULL; // exhausted our list?
613     return false;
614     }
615    
616    
617     // Principal function for rpiece
618     static RenderDataType
619     rpiece(char *pout, RenderDataType dt, char *zout)
620     {
621     if (zout && *zout == '!')
622     error(USER, "cannot send depth to a command");
623    
624     const bool newOutput = (access(pout, F_OK) < 0);
625     FILE *pdfp[2];
626 greg 2.4 if (newOutput) { // new output file?
627     CHECK((tileGrid[0] <= 1) & (tileGrid[1] <= 1),
628     USER, "bad tiling specification");
629     } else {
630 greg 2.1 dt = myRPmanager.ReopenOutput(pdfp, pout, zout);
631     if (dt == RDTnone)
632 greg 2.7 return RDTnone;
633 greg 2.1 if (!fscnresolu(&hresolu, &vresolu, pdfp[0]))
634     error(USER, "missing picture resolution");
635 greg 2.2 pixaspect = .0; // need to leave this as is
636 greg 2.1 myRPmanager.NewHeader(pout); // get prev. header info
637     const char * tval = myRPmanager.GetHeadStr("TILED=");
638     if (tval) sscanf(tval, "%d %d", &tileGrid[0], &tileGrid[1]);
639 greg 2.4 CHECK(myRPmanager.GetView()==NULL,
640     USER, "missing view in picture file");
641 greg 2.1 ourview = *myRPmanager.GetView();
642     }
643     int hvdim[2] = {hresolu, vresolu}; // set up tiled frame
644     if (!myRPmanager.NewFrame(ourview, hvdim, &pixaspect, tileGrid))
645     error(USER, "tiling setup error in rpiece");
646    
647     if ((hvdim[0] != hresolu) | (hvdim[1] != vresolu)) {
648     if (!newOutput)
649     error(USER, "unexpected output size adjustment");
650     sprintf(errmsg, "resolution adjusted from %dx%d to %dx%d",
651     hresolu, vresolu, hvdim[0], hvdim[1]);
652     error(WARNING, errmsg);
653     hresolu = hvdim[0];
654     vresolu = hvdim[1];
655     }
656     if (newOutput){ // open new output here
657     char buf[64];
658     sprintf(buf, "TILED= %d %d\n", tileGrid[0], tileGrid[1]);
659     myRPmanager.AddHeader(buf);
660     dt = myRPmanager.NewOutput(pdfp, pout, dt, zout);
661     if (dt == RDTnone)
662 greg 2.7 return RDTnone;
663 greg 2.1 fprtresolu(hresolu, vresolu, pdfp[0]);
664 greg 2.5 fflush(pdfp[0]);
665     if (RDTdepthT(dt) == RDTdshort) {
666 greg 2.1 fprtresolu(hresolu, vresolu, pdfp[1]);
667 greg 2.5 fflush(pdfp[1]);
668     }
669     } else if (RDTdepthT(dt) == RDTdshort &&
670     (!fscnresolu(&hvdim[0], &hvdim[1], pdfp[1]) ||
671     (hvdim[0] != hresolu) | (hvdim[1] != vresolu)))
672     error(USER, "mismatched depth file resolution");
673 greg 2.1 // prepare (flat) pixel buffer
674     const long pdata_beg = ftell(pdfp[0]);
675     const size_t pixSiz = (RDTcolorT(dt)==RDTrgbe)|(RDTcolorT(dt)==RDTxyze) ? sizeof(COLR)
676     : (RDTcolorT(dt)==RDTrgb)|(RDTcolorT(dt)==RDTxyz) ? sizeof(COLORV)*3
677     : RDTcolorT(dt)==RDTscolr ? LSCOLR : sizeof(COLORV)*NCSAMP;
678     size_t pmlen = pdata_beg + pixSiz*hresolu*vresolu;
679     // put tile progress array at end
680     if (pmlen&7) pmlen += 8 - (pmlen&7); // 8-byte alignment to be safe
681     pmlen += sizeof(TileProg)*tileGrid[0]*tileGrid[1];
682     // map picture file to memory
683 greg 2.4 if (newOutput && ftruncate(fileno(pdfp[0]), pmlen) < 0)
684 greg 2.1 error(SYSTEM, "cannot extend picture buffer");
685     uby8 * pixMap = (uby8 *)mmap(NULL, pmlen, PROT_READ|PROT_WRITE,
686     MAP_SHARED, fileno(pdfp[0]), 0);
687     if ((void *)pixMap == MAP_FAILED)
688     error(SYSTEM, "cannot map picture file into memory");
689     // map depth buffer to memory
690     const long zdata_beg = RDTdepthT(dt) ? ftell(pdfp[1]) : 0L;
691     const size_t zdpSiz = RDTdepthT(dt)==RDTdshort ? sizeof(short) :
692     RDTdepthT(dt)==RDTdfloat ? sizeof(float) : 0;
693     const size_t zmlen = zdata_beg + zdpSiz*hresolu*vresolu;
694     uby8 * zdMap = NULL;
695     if (RDTdepthT(dt)) {
696 greg 2.4 if (newOutput && ftruncate(fileno(pdfp[1]), zmlen) < 0)
697 greg 2.1 error(SYSTEM, "cannot extend depth buffer");
698     zdMap = (uby8 *)mmap(NULL, zmlen, PROT_READ|PROT_WRITE,
699     MAP_SHARED, fileno(pdfp[1]), 0);
700     if ((void *)zdMap == MAP_FAILED)
701     error(SYSTEM, "cannot map depth file into memory");
702     }
703     fclose(pdfp[0]); // done with file pointers
704     if (RDTdepthT(dt)) fclose(pdfp[1]);
705     // point to tile progress array
706     tprog = (TileProg *)(pixMap + pmlen - sizeof(TileProg)*tileGrid[0]*tileGrid[1]);
707    
708     if (children_finished()) // work done in children?
709     return dt;
710    
711 greg 2.2 int ndone = 0; // else render tiles
712     int ti[2];
713 greg 2.1 while (nexttile(ti)) {
714     const int offset = (tileGrid[1]-1-ti[1])*myRPmanager.GetWidth()*myRPmanager.THeight() +
715     (myRPmanager.THeight()-1)*myRPmanager.GetWidth() +
716     ti[0]*myRPmanager.TWidth();
717     uby8 * pptr = pixMap + pdata_beg + pixSiz*offset;
718     uby8 * zptr = zdMap + zdata_beg + zdpSiz*offset;
719     bool ok = false;
720     switch (RDTcommonE(dt)<<1 | (RDTdepthT(dt)==RDTdshort)) {
721     case 2: // common-exponent color, float/no depth
722     ok = myRPmanager.RenderTile((COLRV *)pptr, -myRPmanager.GetWidth(),
723     (float *)zptr, ti);
724     break;
725     case 0: // float color, float/no depth
726     ok = myRPmanager.RenderTile((COLORV *)pptr, -myRPmanager.GetWidth(),
727     (float *)zptr, ti);
728     break;
729     case 3: // common-exponent color, encoded depth
730     ok = myRPmanager.RenderTile((COLRV *)pptr, -myRPmanager.GetWidth(),
731     (short *)zptr, ti);
732     break;
733     case 1: // float color, encoded depth
734     ok = myRPmanager.RenderTile((COLORV *)pptr, -myRPmanager.GetWidth(),
735     (short *)zptr, ti);
736     break;
737     }
738     if (!ok) { // got an error
739     sprintf(errmsg, "error rendering tile (%d,%d)/(%d,%d)",
740     ti[0], ti[1], tileGrid[0], tileGrid[1]);
741     error(USER, errmsg);
742     }
743     tile_p(ti)->status = 1; // mark tile completed
744 greg 2.3 ndone++;
745 greg 2.1 }
746 greg 2.2 if (!ndone)
747     error(WARNING, "no tiles need rendering, exit");
748 greg 2.1 /*
749     munmap(pixMap, pmlen); // technically unnecessary...
750     if (zdMap) munmap(zdMap, zmlen);
751     */
752     return dt; // we're done here
753     }