ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/rxpiece.cpp
Revision: 2.11
Committed: Tue Apr 22 17:12:25 2025 UTC (9 days, 18 hours ago) by greg
Branch: MAIN
CVS Tags: HEAD
Changes since 2.10: +4 -1 lines
Log Message:
feat(rpict,rtrace,rvu,rxpict,rxtrace,rxpiece): Added -e expr and -f file.cal options

File Contents

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