ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/rxpiece.cpp
Revision: 2.12
Committed: Wed Jun 4 20:32:25 2025 UTC (21 hours, 31 minutes ago) by greg
Branch: MAIN
CVS Tags: HEAD
Changes since 2.11: +6 -6 lines
Log Message:
feat(rxpiece): Added rxpiece to standard distribution

File Contents

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