ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rcomb.c
Revision: 2.11
Committed: Tue May 21 16:27:26 2024 UTC (11 months, 1 week ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.10: +10 -8 lines
Log Message:
perf(rcomb): Minor performance improvements for multi-processing mode

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: rcomb.c,v 2.10 2024/05/20 23:21:29 greg Exp $";
3 #endif
4 /*
5 * General component matrix combiner, operating on a row at a time.
6 */
7
8 #include <math.h>
9 #include "platform.h"
10 #include "rtprocess.h"
11 #include "rtio.h"
12 #include "rmatrix.h"
13 #include "calcomp.h"
14
15 #ifndef M_PI
16 #define M_PI 3.14159265358979323846
17 #endif
18
19 #define MAXCOMP MAXCSAMP /* #components we support */
20
21 /* Unary matrix operation(s) */
22 typedef struct {
23 double cmat[MAXCOMP*MAXCOMP]; /* component transformation */
24 double sca[MAXCOMP]; /* scalar coefficients */
25 const char *csym; /* symbolic coefficients */
26 short clen; /* number of coefficients */
27 short nsf; /* number of scalars */
28 } RUNARYOP;
29
30 /* Input matrix */
31 typedef struct {
32 const char *inspec; /* input specification */
33 RUNARYOP preop; /* transform operation */
34 RMATRIX imx; /* input matrix header info */
35 RMATRIX *rmp; /* active single-row matrix */
36 FILE *infp; /* open input stream */
37 } ROPMAT;
38
39 ROPMAT *mop = NULL; /* allocated input array */
40 int nall = 0; /* number allocated */
41 int nmats = 0; /* number of actual inputs */
42
43 RMATRIX *mcat = NULL; /* final concatenation */
44 int mcat_last = 0; /* goes after trailing ops? */
45
46 int in_nrows; /* number of input rows (or 0) */
47 #define in_ncols (mop[0].rmp->ncols) /* number of input columns */
48 #define in_ncomp (mop[0].rmp->ncomp) /* input #components */
49
50 extern int nowarn; /* turn off warnings? */
51
52 int cur_row; /* current input/output row */
53 int cur_col; /* current input/output column */
54 int cur_chan; /* if we're looping channels */
55
56 SUBPROC *cproc = NULL; /* child process array */
57 int nchildren = 0; /* # of child processes */
58 int inchild = -1; /* our child ID (-1: parent) */
59
60 static int checksymbolic(ROPMAT *rop);
61
62 static int
63 split_input(ROPMAT *rop)
64 {
65 if (rop->rmp == &rop->imx && !(rop->rmp = rmx_copy(&rop->imx))) {
66 fputs("Out of memory in split_input()\n", stderr);
67 return(0);
68 }
69 rmx_reset(rop->rmp);
70 return(1);
71 }
72
73 /* Check/set transform based on a reference input file */
74 static int
75 checkreffile(ROPMAT *rop)
76 {
77 static const char *curRF = NULL;
78 static RMATRIX refm;
79 const int nc = rop->imx.ncomp;
80 int i;
81
82 if (!curRF || strcmp(rop->preop.csym, curRF)) {
83 FILE *fp = fopen(rop->preop.csym, "rb");
84 if (!rmx_load_header(&refm, fp)) {
85 fprintf(stderr, "%s: cannot read info header\n",
86 rop->preop.csym);
87 curRF = NULL;
88 if (fp) fclose(fp);
89 return(0);
90 }
91 fclose(fp);
92 curRF = rop->preop.csym;
93 }
94 if (refm.ncomp == 3) {
95 rop->preop.csym = (refm.dtype == DTxyze) ? "XYZ" : "RGB";
96 return(checksymbolic(rop));
97 }
98 if (refm.ncomp == 2) {
99 fprintf(stderr, "%s: cannot convert to 2 components\n",
100 curRF);
101 return(0);
102 }
103 if (refm.ncomp == 1) {
104 rop->preop.csym = "Y"; /* XXX big assumption */
105 return(checksymbolic(rop));
106 }
107 if (refm.ncomp == nc &&
108 !memcmp(refm.wlpart, rop->imx.wlpart, sizeof(refm.wlpart)))
109 return(1); /* nothing to do */
110
111 if ((nc <= 3) | (nc > MAXCSAMP) | (refm.ncomp > MAXCSAMP)) {
112 fprintf(stderr, "%s: cannot resample from %d to %d components\n",
113 curRF, nc, refm.ncomp);
114 return(0);
115 }
116 if (!split_input(rop)) /* get our own struct */
117 return(0);
118 rop->preop.clen = refm.ncomp * nc; /* compute spec to ref */
119
120 for (i = 0; i < nc; i++) {
121 SCOLOR scstim, scresp;
122 int j;
123 memset(scstim, 0, sizeof(COLORV)*nc);
124 scstim[i] = 1.f;
125 convertscolor(scresp, refm.ncomp, refm.wlpart[0], refm.wlpart[3],
126 scstim, nc, rop->imx.wlpart[0], rop->imx.wlpart[3]);
127 for (j = refm.ncomp; j-- > 0; )
128 rop->preop.cmat[j*nc + i] = scresp[j];
129 }
130 /* remember new spectral params */
131 memcpy(rop->rmp->wlpart, refm.wlpart, sizeof(rop->rmp->wlpart));
132 rop->rmp->ncomp = refm.ncomp;
133 return(1);
134 }
135
136 /* Compute conversion row from spectrum to one channel of RGB */
137 static void
138 rgbrow(ROPMAT *rop, int r, int p)
139 {
140 const int nc = rop->imx.ncomp;
141 const float * wlp = rop->imx.wlpart;
142 int i;
143
144 for (i = nc; i--; ) {
145 int nmEnd = wlp[0] + (wlp[3] - wlp[0])*i/nc;
146 int nmStart = wlp[0] + (wlp[3] - wlp[0])*(i+1)/nc;
147 COLOR crgb;
148 spec_rgb(crgb, nmStart, nmEnd);
149 rop->preop.cmat[r*nc+i] = crgb[p];
150 }
151 }
152
153 /* Compute conversion row from spectrum to one channel of XYZ */
154 static void
155 xyzrow(ROPMAT *rop, int r, int p)
156 {
157 const int nc = rop->imx.ncomp;
158 const float * wlp = rop->imx.wlpart;
159 int i;
160
161 for (i = nc; i--; ) {
162 int nmEnd = wlp[0] + (wlp[3] - wlp[0])*i/nc;
163 int nmStart = wlp[0] + (wlp[3] - wlp[0])*(i+1)/nc;
164 COLOR cxyz;
165 spec_cie(cxyz, nmStart, nmEnd);
166 rop->preop.cmat[r*nc+i] = cxyz[p];
167 }
168 }
169
170 /* Use the spectral sensitivity function to compute matrix coefficients */
171 static void
172 sensrow(ROPMAT *rop, int r, double (*sf)(SCOLOR sc, int ncs, const float wlpt[4]))
173 {
174 const int nc = rop->imx.ncomp;
175 int i;
176
177 for (i = nc; i--; ) {
178 SCOLOR sclr;
179 memset(sclr, 0, sizeof(COLORV)*nc);
180 sclr[i] = 1.f;
181 rop->preop.cmat[r*nc+i] = (*sf)(sclr, nc, rop->imx.wlpart);
182 }
183 }
184
185 /* Check/set symbolic transform */
186 static int
187 checksymbolic(ROPMAT *rop)
188 {
189 const int nc = rop->imx.ncomp;
190 const int dt = rop->imx.dtype;
191 double cf = 1;
192 int i, j;
193 /* check suffix => reference file */
194 if (strchr(rop->preop.csym, '.') > rop->preop.csym)
195 return(checkreffile(rop));
196
197 if (nc < 3) {
198 fprintf(stderr, "%s: -c '%s' requires at least 3 components\n",
199 rop->inspec, rop->preop.csym);
200 return(0);
201 }
202 rop->preop.clen = strlen(rop->preop.csym) * nc;
203 if (rop->preop.clen > MAXCOMP*MAXCOMP) {
204 fprintf(stderr, "%s: -c '%s' results in too many components\n",
205 rop->inspec, rop->preop.csym);
206 return(0);
207 }
208 for (j = 0; rop->preop.csym[j]; j++) {
209 int comp = 0;
210 switch (rop->preop.csym[j]) {
211 case 'B':
212 case 'b':
213 ++comp;
214 /* fall through */
215 case 'G':
216 case 'g':
217 ++comp;
218 /* fall through */
219 case 'R':
220 case 'r':
221 if (rop->preop.csym[j] <= 'Z')
222 cf = 1./WHTEFFICACY;
223 if (dt == DTxyze) {
224 for (i = 3; i--; )
225 rop->preop.cmat[j*nc+i] = cf*xyz2rgbmat[comp][i];
226 } else if (nc == 3)
227 rop->preop.cmat[j*nc+comp] = 1.;
228 else
229 rgbrow(rop, j, comp);
230 break;
231 case 'Z':
232 case 'z':
233 ++comp;
234 /* fall through */
235 case 'Y':
236 case 'y':
237 ++comp;
238 /* fall through */
239 case 'X':
240 case 'x':
241 if ((rop->preop.csym[j] <= 'Z') & (dt != DTxyze))
242 cf = WHTEFFICACY;
243 if (dt == DTxyze) {
244 rop->preop.cmat[j*nc+comp] = 1.;
245 } else if (nc == 3) {
246 for (i = 3; i--; )
247 rop->preop.cmat[j*nc+i] =
248 rgb2xyzmat[comp][i];
249 } else if (comp == CIEY)
250 sensrow(rop, j, scolor2photopic);
251 else
252 xyzrow(rop, j, comp);
253
254 for (i = nc*(cf != 1); i--; )
255 rop->preop.cmat[j*nc+i] *= cf;
256 break;
257 case 'S': /* scotopic (il)luminance */
258 cf = WHTSCOTOPIC;
259 /* fall through */
260 case 's':
261 sensrow(rop, j, scolor2scotopic);
262 for (i = nc*(cf != 1); i--; )
263 rop->preop.cmat[j*nc+i] *= cf;
264 break;
265 case 'M': /* melanopic (il)luminance */
266 cf = WHTMELANOPIC;
267 /* fall through */
268 case 'm':
269 sensrow(rop, j, scolor2melanopic);
270 for (i = nc*(cf != 1); i--; )
271 rop->preop.cmat[j*nc+i] *= cf;
272 break;
273 case 'A': /* average component */
274 case 'a':
275 for (i = nc; i--; )
276 rop->preop.cmat[j*nc+i] = 1./(double)nc;
277 break;
278 default:
279 fprintf(stderr, "%s: -c '%c' unsupported\n",
280 rop->inspec, rop->preop.csym[j]);
281 return(0);
282 }
283 }
284 if (!split_input(rop)) /* get our own struct */
285 return(0);
286 memcpy(rop->rmp->wlpart, WLPART, sizeof(rop->rmp->wlpart));
287 rop->rmp->ncomp = rop->preop.clen / nc;
288 /* decide on output type */
289 if (!strcasecmp(rop->preop.csym, "XYZ")) {
290 if (dt <= DTspec)
291 rop->rmp->dtype = DTxyze;
292 } else if (!strcasecmp(rop->preop.csym, "RGB")) {
293 if (dt <= DTspec)
294 rop->rmp->dtype = DTrgbe;
295 } else if (rop->rmp->dtype == DTspec)
296 rop->rmp->dtype = DTfloat;
297 return(1);
298 }
299
300 static int
301 get_component_xfm(ROPMAT *rop)
302 {
303 int i, j;
304
305 if (rop->rmp != &rop->imx) { /* reset destination matrix */
306 rmx_free(rop->rmp);
307 rop->rmp = &rop->imx;
308 }
309 if (rop->preop.csym && /* symbolic transform? */
310 !checksymbolic(rop))
311 return(0);
312 /* undo exposure? */
313 if (fabs(1. - bright(rop->rmp->cexp)) > .025) {
314 if (rop->rmp->ncomp == 1)
315 rop->rmp->cexp[RED] = rop->rmp->cexp[GRN] =
316 rop->rmp->cexp[BLU] = bright(rop->rmp->cexp);
317 if (rop->preop.nsf <= 0) {
318 rop->preop.nsf = i = rop->rmp->ncomp;
319 while (i--)
320 rop->preop.sca[i] = 1.;
321 }
322 if (rop->preop.nsf == 1) {
323 if (rop->rmp->ncomp == 3) {
324 rop->preop.sca[2] = rop->preop.sca[1] =
325 rop->preop.sca[0];
326 rop->preop.nsf = 3;
327 } else
328 rop->preop.sca[0] /= bright(rop->rmp->cexp);
329 }
330 if (rop->preop.nsf == 3) {
331 opcolor(rop->preop.sca, /=, rop->rmp->cexp);
332 } else if (rop->preop.nsf > 3) { /* punt */
333 double mult = 1./bright(rop->rmp->cexp);
334 for (i = rop->preop.nsf; i--; )
335 rop->preop.sca[i] *= mult;
336 }
337 setcolor(rop->rmp->cexp, 1., 1., 1.);
338 }
339 if (rop->preop.clen > 0) { /* use component transform? */
340 if (rop->preop.clen % rop->imx.ncomp) {
341 fprintf(stderr, "%s: -c must have N x %d coefficients\n",
342 rop->inspec, rop->imx.ncomp);
343 return(0);
344 }
345 if (rop->preop.nsf > 0) { /* scale transform, instead */
346 if (rop->preop.nsf == 1) {
347 for (i = rop->preop.clen; i--; )
348 rop->preop.cmat[i] *= rop->preop.sca[0];
349 } else if (rop->preop.nsf*rop->imx.ncomp != rop->preop.clen) {
350 fprintf(stderr, "%s: -s must have one or %d factors\n",
351 rop->inspec,
352 rop->preop.clen/rop->imx.ncomp);
353 return(0);
354 } else {
355 for (i = rop->preop.nsf; i--; )
356 for (j = rop->imx.ncomp; j--; )
357 rop->preop.cmat[i*rop->imx.ncomp+j]
358 *= rop->preop.sca[i];
359 }
360 }
361 rop->preop.nsf = 0; /* now folded in */
362 if (!split_input(rop)) /* get our own struct */
363 return(0);
364 rop->rmp->ncomp = rop->preop.clen / rop->imx.ncomp;
365 if ((rop->rmp->ncomp > 3) & (rop->rmp->dtype <= DTspec)) {
366 rop->rmp->dtype = DTfloat; /* probably not actual spectrum */
367 memcpy(rop->rmp->wlpart, WLPART, sizeof(rop->rmp->wlpart));
368 }
369 } else if (rop->preop.nsf > 0) { /* else use scalar(s)? */
370 if (rop->preop.nsf == 1) {
371 for (i = rop->rmp->ncomp; --i; )
372 rop->preop.sca[i] = rop->preop.sca[0];
373 rop->preop.nsf = rop->rmp->ncomp;
374 } else if (rop->preop.nsf != rop->rmp->ncomp) {
375 fprintf(stderr, "%s: -s must have one or %d factors\n",
376 rop->inspec, rop->rmp->ncomp);
377 return(0);
378 }
379 }
380 return(1);
381 }
382
383 static int
384 apply_op(RMATRIX *dst, const RMATRIX *src, const RUNARYOP *ro)
385 {
386 if (ro->clen > 0) {
387 RMATRIX *res = rmx_transform(src, dst->ncomp, ro->cmat);
388 if (!res) {
389 fputs("Error in call to rmx_transform()\n", stderr);
390 return(0);
391 }
392 if (!rmx_transfer_data(dst, res, 0))
393 return(0);
394 rmx_free(res);
395 } else if (dst != src)
396 memcpy(dst->mtx, src->mtx, rmx_array_size(dst));
397 if (ro->nsf == dst->ncomp)
398 rmx_scale(dst, ro->sca);
399 return(1);
400 }
401
402 static int
403 open_input(ROPMAT *rop)
404 {
405 int outtype;
406
407 if (!rop || !rop->inspec || !rop->inspec[0])
408 return(0);
409 if (rop->inspec == stdin_name)
410 rop->infp = stdin;
411 else if (rop->inspec[0] == '!')
412 rop->infp = popen(rop->inspec+1, "r");
413 else
414 rop->infp = fopen(rop->inspec, "rb");
415
416 if (!rmx_load_header(&rop->imx, rop->infp)) {
417 fprintf(stderr, "Bad header from: %s\n", rop->inspec);
418 return(0);
419 }
420 return(get_component_xfm(rop));
421 }
422
423 /* Return nominal wavelength associated with input component (return nm) */
424 static double
425 l_wavelength(char *nam)
426 {
427 double comp = argument(1);
428
429 if ((comp < -.5) | (comp >= in_ncomp+.5)) {
430 errno = EDOM;
431 return(.0);
432 }
433 if (comp < .5) /* asking for #components? */
434 return(in_ncomp);
435
436 if (in_ncomp == 3) { /* special case for RGB */
437 const int w0 = (int)(comp - .5);
438 return(mop[0].rmp->wlpart[w0] +
439 (comp-.5)*(mop[0].rmp->wlpart[w0+1] -
440 mop[0].rmp->wlpart[w0]));
441 }
442 return(mop[0].rmp->wlpart[0] + /* general case, even div. */
443 (comp-.5)/(double)in_ncomp *
444 (mop[0].rmp->wlpart[3] - mop[0].rmp->wlpart[0]));
445 }
446
447 /* Return ith input with optional channel selector */
448 static double
449 l_chanin(char *nam)
450 {
451 double inp = argument(1);
452 int mi, chan;
453
454 if ((mi = (int)(inp-.5)) < 0 || mi >= nmats) {
455 errno = EDOM;
456 return(.0);
457 }
458 if (inp < .5) /* asking for #inputs? */
459 return(nmats);
460
461 if (nargum() >= 2) {
462 double cval = argument(2);
463 if (cval < .5 || (chan = (int)(cval-.5)) >= in_ncomp) {
464 errno = EDOM;
465 return(.0);
466 }
467 } else
468 chan = cur_chan;
469
470 return(mop[mi].rmp->mtx[cur_col*in_ncomp + chan]);
471 }
472
473 static int
474 initialize(RMATRIX *imp)
475 {
476 int i;
477 /* XXX struct is zeroed coming in */
478 setcolor(imp->cexp, 1.f, 1.f, 1.f);
479 for (i = 0; i < nmats; i++) { /* open each input */
480 int restype;
481 if (!open_input(&mop[i]))
482 return(0);
483 restype = mop[i].rmp->dtype;
484 if (!imp->dtype || (restype = rmx_newtype(restype, imp->dtype)) > 0)
485 imp->dtype = restype;
486 else
487 fprintf(stderr, "%s: warning - data type mismatch\n",
488 mop[i].inspec);
489 if (!i) {
490 imp->ncols = mop[0].rmp->ncols;
491 imp->ncomp = mop[0].rmp->ncomp;
492 memcpy(imp->wlpart, mop[0].rmp->wlpart, sizeof(imp->wlpart));
493 } else if ((mop[i].rmp->ncols != imp->ncols) |
494 (mop[i].rmp->ncomp != imp->ncomp) |
495 ((in_nrows > 0) & (mop[i].rmp->nrows > 0) &
496 (mop[i].rmp->nrows != in_nrows))) {
497 fprintf(stderr, "%s: mismatch in size or #components\n",
498 mop[i].inspec);
499 return(0);
500 } /* XXX should check wlpart? */
501 if (in_nrows <= 0)
502 in_nrows = imp->nrows = mop[i].rmp->nrows;
503 } /* set up .cal environment */
504 esupport |= E_VARIABLE|E_FUNCTION|E_RCONST;
505 esupport &= ~(E_OUTCHAN|E_INCHAN);
506 varset("PI", ':', M_PI);
507 varset("nfiles", ':', nmats);
508 varset("nrows", ':', in_nrows);
509 varset("ncols", ':', in_ncols);
510 varset("ncomp", ':', in_ncomp);
511 varset("R", ':', 1.);
512 varset("G", ':', 2.);
513 varset("B", ':', 3.);
514 funset("wl", 1, ':', l_wavelength);
515 funset("ci", 1, '=', l_chanin);
516 scompile("ri(i)=ci(i,R);gi(i)=ci(i,G);bi(i)=ci(i,B)", NULL, 0);
517 return(1);
518 }
519
520 static void
521 output_headinfo(FILE *fp)
522 {
523 int i;
524
525 for (i = 0; i < nmats; i++) {
526 const char *cp = mop[i].imx.info;
527 fputs(mop[i].inspec, fp);
528 fputs(":\n", fp);
529 if (!cp) continue;
530 while (*cp) {
531 if (*cp == '\n') {
532 cp++; /* avoid inadvertant terminus */
533 continue;
534 }
535 fputc('\t', fp); /* indent this input's info */
536 do
537 putc(*cp, fp);
538 while (*cp++ != '\n');
539 }
540 }
541 }
542
543 static int
544 spawned_children(int np)
545 {
546 int i, rv;
547
548 #if defined(_WIN32) || defined(_WIN64)
549 if (np > 1) {
550 fputs("Warning: only one process under Windows\n", stderr);
551 np = 1;
552 } else
553 #endif
554 if ((in_nrows > 0) & (np > in_nrows))
555 np = in_nrows;
556 /* we'll be doing a row at a time */
557 for (i = 0; i < nmats; i++) {
558 mop[i].imx.nrows = 1;
559 if (!rmx_prepare(&mop[i].imx))
560 goto memerror;
561 if (mop[i].rmp != &mop[i].imx) {
562 mop[i].rmp->nrows = 1;
563 if (!rmx_prepare(mop[i].rmp))
564 goto memerror;
565 }
566 }
567 /* prep output row buffer */
568 if (mcat || mop[nmats].preop.clen > 0) {
569 if (!split_input(&mop[nmats])) /* need separate buffer */
570 return(0);
571 if (mop[nmats].preop.clen > 0)
572 mop[nmats].rmp->ncomp = mop[nmats].preop.clen /
573 mop[nmats].imx.ncomp;
574 mop[nmats].rmp->nrows = 1;
575 if (!mcat | !mcat_last && !rmx_prepare(mop[nmats].rmp))
576 goto memerror;
577 }
578 mop[nmats].imx.nrows = 1;
579 if (!rmx_prepare(&mop[nmats].imx))
580 goto memerror;
581 if (np <= 1) { /* single process return point */
582 #ifdef getc_unlocked
583 for (i = 0; i < nmats; i++)
584 flockfile(mop[i].infp);
585 flockfile(stdout);
586 #endif
587 return(0);
588 }
589 fflush(stdout); /* flush header & spawn children */
590 cproc = (SUBPROC *)malloc(sizeof(SUBPROC)*np);
591 if (!cproc)
592 goto memerror;
593 nchildren = np;
594 for (i = 0; i < np; i++) {
595 cproc[i].flags = PF_FILT_OUT;
596 cproc[i].w = dup(1);
597 cproc[i].r = 0;
598 cproc[i].pid = -1;
599 rv = open_process(&cproc[i], NULL);
600 if (rv <= 0) break;
601 }
602 if (rv > 0)
603 return(1); /* parent return value */
604 if (rv < 0) {
605 perror("fork");
606 exit(1);
607 }
608 inchild = i; /* our child index */
609 while (i-- > 0) /* don't share siblings' pipes */
610 close(cproc[i].w);
611 fpurge(stdin); /* discard previous matrix input */
612 #ifdef getc_unlocked
613 flockfile(stdin);
614 #endif
615 for (i = 0; i < nmats; i++) {
616 if (mop[i].infp != stdin)
617 fclose(mop[i].infp); /* ! pclose() */
618 mop[i].infp = stdin;
619 mop[i].imx.dtype = DTdouble;
620 }
621 return(0); /* child return */
622 memerror:
623 fputs("Out of memory in spawned_children()\n", stderr);
624 exit(1);
625 }
626
627 static int
628 parent_loop()
629 {
630 FILE **outfp = (FILE **)malloc(nchildren*sizeof(FILE *));
631 int i;
632
633 if (!outfp) goto memerror;
634 for (i = 0; i < nchildren; i++) {
635 outfp[i] = fdopen(cproc[i].w, "w");
636 if (!outfp[i]) goto memerror;
637 #ifdef getc_unlocked
638 flockfile(outfp[i]);
639 #endif
640 }
641 #ifdef getc_unlocked
642 for (i = 0; i < nmats; i++)
643 flockfile(mop[i].infp);
644 #endif
645 for (cur_row = 0; (in_nrows <= 0) | (cur_row < in_nrows); cur_row++) {
646 FILE *ofp = outfp[cur_row % nchildren];
647 for (i = 0; i < nmats; i++)
648 if (!rmx_load_row(mop[i].imx.mtx, &mop[i].imx, mop[i].infp)) {
649 if (cur_row > in_nrows) /* unknown #input rows? */
650 break;
651 fprintf(stderr, "%s: read error at row %d\n",
652 mop[i].inspec, cur_row);
653 return(0);
654 }
655 if (i < nmats)
656 break;
657 for (i = 0; i < nmats; i++)
658 if (!rmx_write_data(mop[i].imx.mtx, mop[i].imx.ncomp,
659 mop[i].imx.ncols, DTdouble, ofp))
660 return(0);
661 if (fflush(ofp) == EOF)
662 return(0);
663 }
664 for (i = 0; i < nchildren; i++)
665 fclose(outfp[i]);
666 free(outfp);
667 i = close_processes(cproc, nchildren);
668 free(cproc); cproc = NULL;
669 if (i < 0) {
670 fputs("Warning: missing child in parent_loop()\n", stderr);
671 return(1);
672 }
673 if (i > 0) {
674 fprintf(stderr, "Child exited with status %d\n", i);
675 return(0);
676 }
677 return(1);
678 memerror:
679 fputs("Out of memory in parent_loop()\n", stderr);
680 exit(1);
681 }
682
683 static int
684 combine_input()
685 {
686 const int row0 = (inchild >= 0)*inchild;
687 const int rstep = nchildren + !nchildren;
688 ROPMAT *res = &mop[nmats];
689 int set_r, set_c;
690 RMATRIX *tmp = NULL;
691 int co_set;
692 int i;
693
694 if (mcat && mcat_last &&
695 !(tmp = rmx_alloc(1, res->imx.ncols, res->rmp->ncomp)))
696 goto memerror;
697 /* figure out what the user set */
698 co_set = fundefined("co");
699 if (!co_set)
700 co_set = -vardefined("co");
701 if (!co_set & (in_ncomp == 3) && vardefined("ro") &&
702 vardefined("go") && vardefined("bo")) {
703 scompile("co(p)=select(p,ro,go,bo)", NULL, 0);
704 co_set = 1;
705 }
706 if (co_set) { /* set if user wants, didn't set */
707 set_r = varlookup("r") != NULL && !vardefined("r");
708 set_c = varlookup("c") != NULL && !vardefined("c");
709 } else /* save a little time */
710 set_r = set_c = 0;
711 /* read/process row-by-row */
712 for (cur_row = row0; (in_nrows <= 0) | (cur_row < in_nrows); cur_row += rstep) {
713 RMATRIX *mres = NULL;
714 for (i = 0; i < nmats; i++)
715 if (!rmx_load_row(mop[i].imx.mtx, &mop[i].imx, mop[i].infp)) {
716 if (cur_row > in_nrows) /* unknown #input rows? */
717 break;
718 fprintf(stderr, "%s: read error at row %d\n",
719 mop[i].inspec, cur_row);
720 return(0);
721 }
722 if (i < nmats)
723 break;
724 for (i = 0; i < nmats; i++)
725 if (!apply_op(mop[i].rmp, &mop[i].imx, &mop[i].preop))
726 return(0);
727 if (set_r) varset("r", '=', cur_row);
728 for (cur_col = 0; cur_col < in_ncols; cur_col++) {
729 if (set_c) varset("c", '=', cur_col);
730 for (cur_chan = 0; cur_chan < in_ncomp; cur_chan++) {
731 const int ndx = cur_col*in_ncomp + cur_chan;
732 eclock++;
733 if (!co_set) { /* just summing elements? */
734 res->imx.mtx[ndx] = 0;
735 for (i = nmats; i--; )
736 res->imx.mtx[ndx] += mop[i].rmp->mtx[ndx];
737 } else if (co_set > 0) {
738 double dchan = cur_chan+1;
739 res->imx.mtx[ndx] = funvalue("co", 1, &dchan);
740 } else
741 res->imx.mtx[ndx] = varvalue("co");
742 }
743 } /* final conversions */
744 if (!mcat) {
745 if (!apply_op(res->rmp, &res->imx, &res->preop))
746 return(0);
747 } else if (mcat_last) {
748 if (!apply_op(tmp, &res->imx, &res->preop))
749 return(0);
750 mres = rmx_multiply(tmp, mcat);
751 if (!mres)
752 goto multerror;
753 if (!rmx_transfer_data(res->rmp, mres, 0))
754 return(0);
755 } else /* mcat && !mcat_last */ {
756 mres = rmx_multiply(&res->imx, mcat);
757 if (!mres)
758 goto multerror;
759 if (!apply_op(res->rmp, mres, &res->preop))
760 return(0);
761 }
762 rmx_free(mres); mres = NULL;
763 if (inchild >= 0) {
764 i = getc(stdin); /* child waits for turn to output */
765 if (i != EOF) ungetc(i, stdin);
766 }
767 if (!rmx_write_data(res->rmp->mtx, res->rmp->ncomp,
768 res->rmp->ncols, res->rmp->dtype, stdout))
769 return(0);
770 if (inchild >= 0 && fflush(stdout) == EOF)
771 return(0);
772 }
773 return(inchild >= 0 || fflush(stdout) != EOF);
774 memerror:
775 fputs("Out of buffer space in combine_input()\n", stderr);
776 return(0);
777 multerror:
778 fputs("Unexpected matrix multiply error in combine_input()\n", stderr);
779 return(0);
780 }
781
782 static int
783 get_factors(double da[], int n, char *av[])
784 {
785 int ac;
786
787 for (ac = 0; ac < n && isflt(av[ac]); ac++)
788 da[ac] = atof(av[ac]);
789 return(ac);
790 }
791
792 static void
793 resize_inparr(int n2alloc)
794 {
795 int i;
796
797 if (n2alloc == nall)
798 return;
799 for (i = nall; i > n2alloc; i--) {
800 rmx_reset(&mop[i].imx);
801 if (mop[i].rmp != &mop[i].imx)
802 rmx_free(mop[i].rmp);
803 }
804 mop = (ROPMAT *)realloc(mop, n2alloc*sizeof(ROPMAT));
805 if (mop == NULL) {
806 fputs("Out of memory in resize_inparr()\n", stderr);
807 exit(1);
808 }
809 if (n2alloc > nall)
810 memset(mop+nall, 0, (n2alloc-nall)*sizeof(ROPMAT));
811 nall = n2alloc;
812 }
813
814 /* Load one or more matrices and operate on them, sending results to stdout */
815 int
816 main(int argc, char *argv[])
817 {
818
819 int outfmt = DTfromHeader;
820 const char *defCsym = NULL;
821 int echoheader = 1;
822 int stdin_used = 0;
823 int nproc = 1;
824 const char *mcat_spec = NULL;
825 int n2comp = 0;
826 uby8 comp_ndx[128];
827 int i;
828 /* get starting input array */
829 mop = (ROPMAT *)calloc(nall=2, sizeof(ROPMAT));
830 /* get options and arguments */
831 for (i = 1; i < argc; i++)
832 if (argv[i][0] != '-' || !argv[i][1]) {
833 if (argv[i][0] == '-') {
834 if (stdin_used++) goto stdin_error;
835 mop[nmats].inspec = stdin_name;
836 } else
837 mop[nmats].inspec = argv[i];
838 if (!mop[nmats].preop.csym)
839 mop[nmats].preop.csym = defCsym;
840 if (++nmats >= nall)
841 resize_inparr(nmats + (nmats>>2) + 2);
842 } else {
843 int n = argc-1 - i;
844 switch (argv[i][1]) { /* get option */
845 case 'w':
846 nowarn = !nowarn;
847 break;
848 case 'h':
849 echoheader = !echoheader;
850 break;
851 case 'n':
852 nproc = atoi(argv[++i]);
853 if (nproc <= 0)
854 goto userr;
855 break;
856 case 'e':
857 if (!n) goto userr;
858 comp_ndx[n2comp++] = i++;
859 break;
860 case 'f':
861 switch (argv[i][2]) {
862 case '\0':
863 if (!n) goto userr;
864 comp_ndx[n2comp++] = i++;
865 break;
866 case 'd':
867 outfmt = DTdouble;
868 break;
869 case 'f':
870 outfmt = DTfloat;
871 break;
872 case 'a':
873 outfmt = DTascii;
874 break;
875 case 'c':
876 outfmt = DTrgbe;
877 break;
878 default:
879 goto userr;
880 }
881 break;
882 case 's':
883 if (n > MAXCOMP) n = MAXCOMP;
884 i += mop[nmats].preop.nsf =
885 get_factors(mop[nmats].preop.sca,
886 n, argv+i+1);
887 if (mop[nmats].preop.nsf <= 0) {
888 fprintf(stderr, "%s: -s missing arguments\n",
889 argv[0]);
890 goto userr;
891 }
892 break;
893 case 'C':
894 if (!n || isflt(argv[i+1]))
895 goto userr;
896 defCsym = mop[nmats].preop.csym = argv[++i];
897 mop[nmats].preop.clen = 0;
898 mcat_last = 0;
899 break;
900 case 'c':
901 if (n && !isflt(argv[i+1])) {
902 mop[nmats].preop.csym = argv[++i];
903 mop[nmats].preop.clen = 0;
904 break;
905 }
906 if (n > MAXCOMP*MAXCOMP) n = MAXCOMP*MAXCOMP;
907 i += mop[nmats].preop.clen =
908 get_factors(mop[nmats].preop.cmat,
909 n, argv+i+1);
910 if (mop[nmats].preop.clen <= 0) {
911 fprintf(stderr, "%s: -c missing arguments\n",
912 argv[0]);
913 goto userr;
914 }
915 mop[nmats].preop.csym = NULL;
916 mcat_last = 0;
917 break;
918 case 'm':
919 if (!n) goto userr;
920 if (argv[++i][0] == '-' && !argv[i][1]) {
921 if (stdin_used++) goto stdin_error;
922 mcat_spec = stdin_name;
923 } else
924 mcat_spec = argv[i];
925 mcat_last = 1;
926 break;
927 default:
928 fprintf(stderr, "%s: unknown option '%s'\n",
929 argv[0], argv[i]);
930 goto userr;
931 }
932 }
933 if (!nmats) {
934 fprintf(stderr, "%s: need at least one input matrix\n", argv[0]);
935 goto userr;
936 }
937 resize_inparr(nmats+1); /* extra matrix at end for result */
938 mop[nmats].inspec = "trailing_ops";
939 /* load final concatenation matrix */
940 if (mcat_spec && !(mcat = rmx_load(mcat_spec, RMPnone))) {
941 fprintf(stderr, "%s: error loading concatenation matrix: %s\n",
942 argv[0], mcat_spec);
943 return(1);
944 }
945 /* get/check inputs, set constants */
946 if (!initialize(&mop[nmats].imx))
947 return(1);
948
949 for (i = 0; i < n2comp; i++) /* user .cal files and expressions */
950 if (argv[comp_ndx[i]][1] == 'f') {
951 char *fpath = getpath(argv[comp_ndx[i]+1],
952 getrlibpath(), 0);
953 if (fpath == NULL) {
954 fprintf(stderr, "%s: cannot find file '%s'\n",
955 argv[0], argv[comp_ndx[i]+1]);
956 return(1);
957 }
958 fcompile(fpath);
959 } else /* (argv[comp_ndx[i]][1] == 'e') */
960 scompile(argv[comp_ndx[i]+1], NULL, 0);
961
962 /* get trailing color transform */
963 if (!get_component_xfm(&mop[nmats]))
964 return(1);
965 /* adjust output dimensions and #components */
966 if (mcat) {
967 if (mop[nmats].imx.ncols != mcat->nrows) {
968 fprintf(stderr,
969 "%s: number of input columns does not match number of rows in '%s'\n",
970 argv[0], mcat_spec);
971 return(1);
972 }
973 if (mcat->ncomp != (mcat_last ? mop[nmats].rmp->ncomp : mop[nmats].imx.ncomp)) {
974 fprintf(stderr,
975 "%s: number of components does not match those in '%s'\n",
976 argv[0], mcat_spec);
977 return(1);
978 }
979 if (!split_input(&mop[nmats]))
980 return(1);
981 mop[nmats].rmp->ncols = mcat->ncols;
982 }
983 newheader("RADIANCE", stdout); /* write output header */
984 if (echoheader)
985 output_headinfo(stdout);
986 printargs(argc, argv, stdout);
987 fputnow(stdout);
988 mop[nmats].rmp->dtype = rmx_write_header(mop[nmats].rmp, outfmt, stdout);
989 if (!mop[nmats].rmp->dtype) {
990 fprintf(stderr, "%s: unsupported output format\n", argv[0]);
991 return(1);
992 }
993 doptimize(1); /* optimize definitions */
994 if (spawned_children(nproc)) /* running in parent process? */
995 return(parent_loop() ? 0 : 1);
996 /* process & write rows */
997 return(combine_input() ? 0 : 1);
998 stdin_error:
999 fprintf(stderr, "%s: %s used for more than one input\n",
1000 argv[0], stdin_name);
1001 return(1);
1002 userr:
1003 fprintf(stderr,
1004 "Usage: %s [-h][-f{adfc}][-n nproc][-e expr][-f file][-s sf .. | -c ce ..] m1 .. -m mcat > mres\n",
1005 argv[0]);
1006 return(1);
1007 }