ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/px/x11image.c
Revision: 2.45
Committed: Tue Apr 15 18:33:31 1997 UTC (27 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.44: +2 -0 lines
Log Message:
put in NOPROTO definition for non-ANSI compilers

File Contents

# Content
1 /* Copyright (c) 1997 Regents of the University of California */
2
3 #ifndef lint
4 static char SCCSid[] = "$SunId$ LBL";
5 #endif
6
7 /*
8 * x11image.c - driver for X-windows
9 *
10 * 3/1/90
11 */
12
13 /*
14 * Modified for X11
15 *
16 * January 1990
17 *
18 * Anat Grynberg and Greg Ward
19 */
20
21
22 #include "standard.h"
23
24 #include <signal.h>
25 #include <X11/Xlib.h>
26 #include <X11/cursorfont.h>
27 #include <X11/Xutil.h>
28 #include <X11/Xatom.h>
29
30 #undef NOPROTO
31 #define NOPROTO 1
32 #include "tonemap.h"
33 #include "view.h"
34 #include "x11raster.h"
35 #include "random.h"
36 #include "resolu.h"
37
38 #ifndef int4
39 #define int4 int /* most int's are 32-bit */
40 #endif
41
42 #define FONTNAME "8x13" /* text font we'll use */
43
44 #define CTRL(c) ((c)-'@')
45
46 #define BORWIDTH 5 /* border width */
47
48 #define ICONSIZ (8*10) /* maximum icon dimension (even 8) */
49
50 #define ourscreen DefaultScreen(thedisplay)
51 #define ourroot RootWindow(thedisplay,ourscreen)
52
53 #define revline(x0,y0,x1,y1) XDrawLine(thedisplay,wind,revgc,x0,y0,x1,y1)
54
55 #define redraw(x,y,w,h) patch_raster(wind,(x)-xoff,(y)-yoff,x,y,w,h,ourras)
56
57 double gamcor = 2.2; /* gamma correction */
58 char *gamstr = NULL; /* gamma value override */
59
60 int dither = 1; /* dither colors? */
61 int fast = 0; /* keep picture in Pixmap? */
62
63 char *dispname = NULL; /* our display name */
64
65 Window wind = 0; /* our output window */
66 unsigned long ourblack=0, ourwhite=1; /* black and white for this visual */
67 int maxcolors = 0; /* maximum colors */
68 int greyscale = 0; /* in grey */
69
70 int scale = 0; /* scalefactor; power of two */
71
72 int xoff = 0; /* x image offset */
73 int yoff = 0; /* y image offset */
74
75 int parent = 0; /* number of children, -1 if child */
76 int sequential = 0; /* display images in sequence */
77
78 char *tout = "od"; /* output of 't' command */
79 int tinterv = 0; /* interval between mouse reports */
80
81 int tmflags = -1; /* tone mapping flags (-1 for none) */
82
83 VIEW ourview = STDVIEW; /* image view parameters */
84 int gotview = 0; /* got parameters from file */
85
86 COLR *scanline; /* scan line buffer */
87 TMbright *lscan; /* encoded luminance scanline */
88 BYTE *cscan; /* encoded chroma scanline */
89 BYTE *pscan; /* compute pixel scanline */
90
91 RESOLU inpres; /* input resolution and ordering */
92 int xmax, ymax; /* picture dimensions */
93 int width, height; /* window size */
94 char *fname = NULL; /* input file name */
95 FILE *fin = stdin; /* input file */
96 long *scanpos = NULL; /* scan line positions in file */
97 int cury = 0; /* current scan location */
98
99 double exposure = 1.0; /* exposure compensation used */
100
101 int wrongformat = 0; /* input in another format? */
102
103 GC ourgc; /* standard graphics context */
104 GC revgc; /* graphics context with GXinvert */
105
106 int *ourrank; /* our visual class ranking */
107 XVisualInfo ourvis; /* our visual */
108 XRASTER *ourras; /* our stored image */
109 unsigned char *ourdata; /* our image data */
110
111 struct {
112 int xmin, ymin, xsiz, ysiz;
113 } box = {0, 0, 0, 0}; /* current box */
114
115 char *geometry = NULL; /* geometry specification */
116
117 char icondata[ICONSIZ*ICONSIZ/8]; /* icon bitmap data */
118 int iconwidth = 0, iconheight = 0;
119
120 char *progname;
121
122 char errmsg[128];
123
124 BYTE clrtab[256][3]; /* global color map */
125
126 extern long ftell();
127
128 extern char *getenv();
129
130 Display *thedisplay;
131 Atom closedownAtom, wmProtocolsAtom;
132
133 int sigrecv;
134
135 int onsig() { sigrecv++; }
136
137
138 main(argc, argv)
139 int argc;
140 char *argv[];
141 {
142 int headline();
143 int i;
144 int pid;
145
146 progname = argv[0];
147
148 for (i = 1; i < argc; i++)
149 if (argv[i][0] == '-')
150 switch (argv[i][1]) {
151 case 'c': /* number of colors */
152 maxcolors = atoi(argv[++i]);
153 break;
154 case 'b': /* greyscale only */
155 greyscale = !greyscale;
156 break;
157 case 'm': /* monochrome */
158 greyscale = 1;
159 maxcolors = 2;
160 break;
161 case 'd': /* display or dither */
162 if (argv[i][2] == 'i')
163 dispname = argv[++i];
164 else
165 dither = !dither;
166 break;
167 case 'f': /* save pixmap */
168 fast = !fast;
169 break;
170 case 's': /* one at a time */
171 sequential = !sequential;
172 break;
173 case 'o': /* 't' output */
174 tout = argv[i]+2;
175 break;
176 case 't': /* msec interval */
177 tinterv = atoi(argv[++i]);
178 break;
179 case 'e': /* exposure comp. */
180 i++;
181 if (!strcmp(argv[i], "auto")) {
182 tmflags = TM_F_CAMERA;
183 break;
184 }
185 if (!strcmp(argv[i], "human")) {
186 tmflags = TM_F_HUMAN;
187 break;
188 }
189 if (argv[i][0] != '+' && argv[i][0] != '-')
190 goto userr;
191 scale = atoi(argv[i]);
192 break;
193 case 'g': /* gamma comp. */
194 if (argv[i][2] == 'e')
195 geometry = argv[++i];
196 else
197 gamstr = argv[++i];
198 break;
199 default:
200 goto userr;
201 }
202 else if (argv[i][0] == '=')
203 geometry = argv[i];
204 else
205 break;
206
207 if (i > argc)
208 goto userr;
209 while (i < argc-1) {
210 sigrecv = 0;
211 signal(SIGCONT, onsig);
212 if ((pid=fork()) == 0) { /* a child for each picture */
213 parent = -1;
214 break;
215 }
216 if (pid < 0)
217 quiterr("fork failed");
218 parent++;
219 while (!sigrecv)
220 pause(); /* wait for wake-up call */
221 i++;
222 }
223 if (i < argc) { /* open picture file */
224 fname = argv[i];
225 fin = fopen(fname, "r");
226 if (fin == NULL)
227 quiterr("cannot open picture file");
228 }
229 /* get header */
230 getheader(fin, headline, NULL);
231 /* get picture dimensions */
232 if (wrongformat || !fgetsresolu(&inpres, fin))
233 quiterr("bad picture format");
234 xmax = scanlen(&inpres);
235 ymax = numscans(&inpres);
236 /* set view parameters */
237 if (gotview && setview(&ourview) != NULL)
238 gotview = 0;
239 if ((scanline = (COLR *)malloc(xmax*sizeof(COLR))) == NULL)
240 quiterr("out of memory");
241
242 init(argc, argv); /* get file and open window */
243
244 for ( ; ; )
245 getevent(); /* main loop */
246 userr:
247 fprintf(stderr,
248 "Usage: %s [-di disp][[-ge] spec][-b][-m][-d][-f][-c nclrs][-e spec][-g gamcor][-s][-ospec][-t intvl] pic ..\n",
249 progname);
250 exit(1);
251 }
252
253
254 headline(s) /* get relevant info from header */
255 char *s;
256 {
257 char fmt[32];
258
259 if (isexpos(s))
260 exposure *= exposval(s);
261 else if (formatval(fmt, s))
262 wrongformat = strcmp(fmt, COLRFMT);
263 else if (isview(s) && sscanview(&ourview, s) > 0)
264 gotview++;
265 }
266
267
268 init(argc, argv) /* get data and open window */
269 int argc;
270 char **argv;
271 {
272 XSetWindowAttributes ourwinattr;
273 XClassHint xclshints;
274 XWMHints xwmhints;
275 XSizeHints xszhints;
276 XTextProperty windowName, iconName;
277 XGCValues xgcv;
278 char *name;
279 register int i;
280
281 if (fname != NULL) {
282 scanpos = (long *)malloc(ymax*sizeof(long));
283 if (scanpos == NULL)
284 quiterr("out of memory");
285 for (i = 0; i < ymax; i++)
286 scanpos[i] = -1;
287 name = fname;
288 } else
289 name = progname;
290 /* remove directory prefix from name */
291 for (i = strlen(name); i-- > 0; )
292 if (name[i] == '/')
293 break;
294 name += i+1;
295 if ((thedisplay = XOpenDisplay(dispname)) == NULL)
296 quiterr("cannot open display");
297 /* set gamma value */
298 if (gamstr == NULL) /* get it from the X server */
299 gamstr = XGetDefault(thedisplay, "radiance", "gamma");
300 if (gamstr == NULL) /* get it from the environment */
301 gamstr = getenv("DISPLAY_GAMMA");
302 if (gamstr != NULL)
303 gamcor = atof(gamstr);
304 /* get best visual for default screen */
305 getbestvis();
306 /* store image */
307 getras();
308 /* get size and position */
309 xszhints.flags = 0;
310 xszhints.width = xmax; xszhints.height = ymax;
311 if (geometry != NULL) {
312 i = XParseGeometry(geometry, &xszhints.x, &xszhints.y,
313 (unsigned *)&xszhints.width,
314 (unsigned *)&xszhints.height);
315 if ((i&(WidthValue|HeightValue)) == (WidthValue|HeightValue))
316 xszhints.flags |= USSize;
317 else
318 xszhints.flags |= PSize;
319 if ((i&(XValue|YValue)) == (XValue|YValue)) {
320 xszhints.flags |= USPosition;
321 if (i & XNegative)
322 xszhints.x += DisplayWidth(thedisplay,
323 ourscreen)-1-xszhints.width-2*BORWIDTH;
324 if (i & YNegative)
325 xszhints.y += DisplayHeight(thedisplay,
326 ourscreen)-1-xszhints.height-2*BORWIDTH;
327 }
328 }
329 /* open window */
330 i = CWEventMask|CWCursor|CWBackPixel|CWBorderPixel;
331 ourwinattr.border_pixel = ourwhite;
332 ourwinattr.background_pixel = ourblack;
333 if (ourvis.visual != DefaultVisual(thedisplay,ourscreen)) {
334 ourwinattr.colormap = newcmap(thedisplay, ourscreen, ourvis.visual);
335 i |= CWColormap;
336 }
337 ourwinattr.event_mask = ExposureMask|KeyPressMask|ButtonPressMask|
338 ButtonReleaseMask|ButtonMotionMask|StructureNotifyMask;
339 ourwinattr.cursor = XCreateFontCursor(thedisplay, XC_diamond_cross);
340 wind = XCreateWindow(thedisplay, ourroot, xszhints.x, xszhints.y,
341 xszhints.width, xszhints.height, BORWIDTH,
342 ourvis.depth, InputOutput, ourvis.visual,
343 i, &ourwinattr);
344 if (wind == 0)
345 quiterr("cannot create window");
346 width = xmax;
347 height = ymax;
348 /* prepare graphics drawing context */
349 if ((xgcv.font = XLoadFont(thedisplay, FONTNAME)) == 0)
350 quiterr("cannot get font");
351 xgcv.foreground = ourblack;
352 xgcv.background = ourwhite;
353 ourgc = XCreateGC(thedisplay, wind, GCForeground|GCBackground|
354 GCFont, &xgcv);
355 xgcv.function = GXinvert;
356 revgc = XCreateGC(thedisplay, wind, GCForeground|GCBackground|
357 GCFunction, &xgcv);
358
359 /* set up the window manager */
360 xwmhints.flags = InputHint|IconPixmapHint;
361 xwmhints.input = True;
362 xwmhints.icon_pixmap = XCreateBitmapFromData(thedisplay,
363 wind, icondata, iconwidth, iconheight);
364
365 windowName.encoding = iconName.encoding = XA_STRING;
366 windowName.format = iconName.format = 8;
367 windowName.value = (u_char *)name;
368 windowName.nitems = strlen(windowName.value);
369 iconName.value = (u_char *)name;
370 iconName.nitems = strlen(windowName.value);
371
372 xclshints.res_name = NULL;
373 xclshints.res_class = "Ximage";
374 XSetWMProperties(thedisplay, wind, &windowName, &iconName,
375 argv, argc, &xszhints, &xwmhints, &xclshints);
376 closedownAtom = XInternAtom(thedisplay, "WM_DELETE_WINDOW", False);
377 wmProtocolsAtom = XInternAtom(thedisplay, "WM_PROTOCOLS", False);
378 XSetWMProtocols(thedisplay, wind, &closedownAtom, 1);
379
380 XMapWindow(thedisplay, wind);
381 } /* end of init */
382
383
384 quiterr(err) /* print message and exit */
385 char *err;
386 {
387 register int es;
388 int cs;
389
390 if (es = err != NULL)
391 fprintf(stderr, "%s: %s: %s\n", progname,
392 fname==NULL?"<stdin>":fname, err);
393 if (thedisplay != NULL)
394 XCloseDisplay(thedisplay);
395 if (parent < 0 & sigrecv == 0)
396 kill(getppid(), SIGCONT);
397 while (parent > 0 && wait(&cs) != -1) { /* wait for any children */
398 if (es == 0)
399 es = cs>>8 & 0xff;
400 parent--;
401 }
402 exit(es);
403 }
404
405
406 static int
407 viscmp(v1,v2) /* compare visual to see which is better, descending */
408 register XVisualInfo *v1, *v2;
409 {
410 int bad1 = 0, bad2 = 0;
411 register int *rp;
412
413 if (v1->class == v2->class) {
414 if (v1->class == TrueColor || v1->class == DirectColor) {
415 /* prefer 24-bit to 32-bit */
416 if (v1->depth == 24 && v2->depth == 32)
417 return(-1);
418 if (v1->depth == 32 && v2->depth == 24)
419 return(1);
420 return(0);
421 }
422 /* don't be too greedy */
423 if (maxcolors <= 1<<v1->depth && maxcolors <= 1<<v2->depth)
424 return(v1->depth - v2->depth);
425 return(v2->depth - v1->depth);
426 }
427 /* prefer Pseudo when < 24-bit */
428 if ((v1->class == TrueColor || v1->class == DirectColor) &&
429 v1->depth < 24)
430 bad1 = 1;
431 if ((v2->class == TrueColor || v2->class == DirectColor) &&
432 v2->depth < 24)
433 bad2 = -1;
434 if (bad1 | bad2)
435 return(bad1+bad2);
436 /* otherwise, use class ranking */
437 for (rp = ourrank; *rp != -1; rp++) {
438 if (v1->class == *rp)
439 return(-1);
440 if (v2->class == *rp)
441 return(1);
442 }
443 return(0);
444 }
445
446
447 getbestvis() /* get the best visual for this screen */
448 {
449 #ifdef DEBUG
450 static char vistype[][12] = {
451 "StaticGray",
452 "GrayScale",
453 "StaticColor",
454 "PseudoColor",
455 "TrueColor",
456 "DirectColor"
457 };
458 #endif
459 static int rankings[3][6] = {
460 {TrueColor,DirectColor,PseudoColor,GrayScale,StaticGray,-1},
461 {PseudoColor,GrayScale,StaticGray,-1},
462 {PseudoColor,GrayScale,StaticGray,-1}
463 };
464 XVisualInfo *xvi;
465 int vismatched;
466 register int i, j;
467
468 if (greyscale) {
469 ourrank = rankings[2];
470 if (maxcolors < 2) maxcolors = 256;
471 } else if (maxcolors >= 2 && maxcolors <= 256)
472 ourrank = rankings[1];
473 else {
474 ourrank = rankings[0];
475 maxcolors = 256;
476 }
477 /* find best visual */
478 ourvis.screen = ourscreen;
479 xvi = XGetVisualInfo(thedisplay,VisualScreenMask,&ourvis,&vismatched);
480 if (xvi == NULL)
481 quiterr("no visuals for this screen!");
482 #ifdef DEBUG
483 fprintf(stderr, "Supported visuals:\n");
484 for (i = 0; i < vismatched; i++)
485 fprintf(stderr, "\ttype %s, depth %d\n",
486 vistype[xvi[i].class], xvi[i].depth);
487 #endif
488 for (i = 0, j = 1; j < vismatched; j++)
489 if (viscmp(&xvi[i],&xvi[j]) > 0)
490 i = j;
491 /* compare to least acceptable */
492 for (j = 0; ourrank[j++] != -1; )
493 ;
494 ourvis.class = ourrank[--j];
495 ourvis.depth = 1;
496 if (viscmp(&xvi[i],&ourvis) > 0)
497 quiterr("inadequate visuals on this screen");
498 /* OK, we'll use it */
499 copystruct(&ourvis, &xvi[i]);
500 #ifdef DEBUG
501 fprintf(stderr, "Selected visual type %s, depth %d\n",
502 vistype[ourvis.class], ourvis.depth);
503 #endif
504 /* make appropriate adjustments */
505 if (ourvis.class == GrayScale || ourvis.class == StaticGray)
506 greyscale = 1;
507 if (ourvis.depth <= 8 && ourvis.colormap_size < maxcolors)
508 maxcolors = ourvis.colormap_size;
509 if (ourvis.class == StaticGray) {
510 ourblack = 0;
511 ourwhite = 255;
512 } else if (ourvis.class == PseudoColor) {
513 ourblack = BlackPixel(thedisplay,ourscreen);
514 ourwhite = WhitePixel(thedisplay,ourscreen);
515 if ((ourblack|ourwhite) & ~255L) {
516 ourblack = 0;
517 ourwhite = 1;
518 }
519 if (maxcolors > 4)
520 maxcolors -= 2;
521 } else {
522 ourblack = 0;
523 ourwhite = ourvis.red_mask|ourvis.green_mask|ourvis.blue_mask;
524 }
525 XFree((char *)xvi);
526 }
527
528
529 getras() /* get raster file */
530 {
531 XVisualInfo vinfo;
532
533 if (maxcolors <= 2) { /* monochrome */
534 ourdata = (unsigned char *)malloc(ymax*((xmax+7)/8));
535 if (ourdata == NULL)
536 goto fail;
537 ourras = make_raster(thedisplay, &ourvis, 1, ourdata,
538 xmax, ymax, 8);
539 if (ourras == NULL)
540 goto fail;
541 getmono();
542 } else if (ourvis.class == TrueColor | ourvis.class == DirectColor) {
543 ourdata = (unsigned char *)malloc(sizeof(int4)*xmax*ymax);
544 if (ourdata == NULL)
545 goto fail;
546 ourras = make_raster(thedisplay, &ourvis, sizeof(int4)*8,
547 ourdata, xmax, ymax, 32);
548 if (ourras == NULL)
549 goto fail;
550 getfull();
551 } else {
552 ourdata = (unsigned char *)malloc(xmax*ymax);
553 if (ourdata == NULL)
554 goto fail;
555 ourras = make_raster(thedisplay, &ourvis, 8, ourdata,
556 xmax, ymax, 8);
557 if (ourras == NULL)
558 goto fail;
559 if (greyscale)
560 getgrey();
561 else
562 getmapped();
563 if (ourvis.class != StaticGray && !init_rcolors(ourras,clrtab))
564 goto fail;
565 }
566 return;
567 fail:
568 quiterr("could not create raster image");
569 }
570
571
572 getevent() /* process the next event */
573 {
574 XEvent xev;
575
576 XNextEvent(thedisplay, &xev);
577 switch ((int)xev.type) {
578 case KeyPress:
579 docom(&xev.xkey);
580 break;
581 case ConfigureNotify:
582 width = xev.xconfigure.width;
583 height = xev.xconfigure.height;
584 break;
585 case MapNotify:
586 map_rcolors(ourras, wind);
587 if (fast)
588 make_rpixmap(ourras, wind);
589 if (!sequential & parent < 0 & sigrecv == 0) {
590 kill(getppid(), SIGCONT);
591 sigrecv--;
592 }
593 break;
594 case UnmapNotify:
595 if (!fast)
596 unmap_rcolors(ourras);
597 break;
598 case Expose:
599 redraw(xev.xexpose.x, xev.xexpose.y,
600 xev.xexpose.width, xev.xexpose.height);
601 break;
602 case ButtonPress:
603 if (xev.xbutton.state & (ShiftMask|ControlMask))
604 moveimage(&xev.xbutton);
605 else
606 switch (xev.xbutton.button) {
607 case Button1:
608 getbox(&xev.xbutton);
609 break;
610 case Button2:
611 traceray(xev.xbutton.x, xev.xbutton.y);
612 break;
613 case Button3:
614 trackrays(&xev.xbutton);
615 break;
616 }
617 break;
618 case ClientMessage:
619 if ((xev.xclient.message_type == wmProtocolsAtom) &&
620 (xev.xclient.data.l[0] == closedownAtom))
621 quiterr(NULL);
622 break;
623 }
624 }
625
626
627 traceray(xpos, ypos) /* print requested pixel data */
628 int xpos, ypos;
629 {
630 extern char *index();
631 FLOAT hv[2];
632 FVECT rorg, rdir;
633 COLOR cval;
634 register char *cp;
635
636 box.xmin = xpos; box.xsiz = 1;
637 box.ymin = ypos; box.ysiz = 1;
638 avgbox(cval);
639 scalecolor(cval, 1./exposure);
640 pix2loc(hv, &inpres, xpos-xoff, ypos-yoff);
641 if (!gotview || viewray(rorg, rdir, &ourview, hv[0], hv[1]) < 0)
642 rorg[0] = rorg[1] = rorg[2] =
643 rdir[0] = rdir[1] = rdir[2] = 0.;
644
645 for (cp = tout; *cp; cp++) /* print what they asked for */
646 switch (*cp) {
647 case 'o': /* origin */
648 printf("%e %e %e ", rorg[0], rorg[1], rorg[2]);
649 break;
650 case 'd': /* direction */
651 printf("%e %e %e ", rdir[0], rdir[1], rdir[2]);
652 break;
653 case 'v': /* radiance value */
654 printf("%e %e %e ", colval(cval,RED),
655 colval(cval,GRN), colval(cval,BLU));
656 break;
657 case 'l': /* luminance */
658 printf("%e ", luminance(cval));
659 break;
660 case 'p': /* pixel position */
661 printf("%d %d ", (int)(hv[0]*inpres.xr),
662 (int)(hv[1]*inpres.yr));
663 break;
664 }
665 putchar('\n');
666 fflush(stdout);
667 return(0);
668 }
669
670
671 docom(ekey) /* execute command */
672 XKeyPressedEvent *ekey;
673 {
674 char buf[80];
675 COLOR cval;
676 XColor cvx;
677 int com, n;
678 double comp;
679 FLOAT hv[2];
680
681 n = XLookupString(ekey, buf, sizeof(buf), NULL, NULL);
682 if (n == 0)
683 return(0);
684 com = buf[0];
685 switch (com) { /* interpret command */
686 case 'q':
687 case 'Q':
688 case CTRL('D'): /* quit */
689 quiterr(NULL);
690 case '\n':
691 case '\r':
692 case 'l':
693 case 'c': /* value */
694 if (avgbox(cval) == -1)
695 return(-1);
696 switch (com) {
697 case '\n':
698 case '\r': /* radiance */
699 sprintf(buf, "%.3f", intens(cval)/exposure);
700 break;
701 case 'l': /* luminance */
702 sprintf(buf, "%.0fL", luminance(cval)/exposure);
703 break;
704 case 'c': /* color */
705 comp = pow(2.0, (double)scale);
706 sprintf(buf, "(%.2f,%.2f,%.2f)",
707 colval(cval,RED)*comp,
708 colval(cval,GRN)*comp,
709 colval(cval,BLU)*comp);
710 break;
711 }
712 XDrawImageString(thedisplay, wind, ourgc,
713 box.xmin, box.ymin+box.ysiz, buf, strlen(buf));
714 return(0);
715 case 'i': /* identify (contour) */
716 if (ourras->pixels == NULL)
717 return(-1);
718 n = ourdata[ekey->x-xoff+xmax*(ekey->y-yoff)];
719 n = ourras->pmap[n];
720 cvx.pixel = ourras->cdefs[n].pixel;
721 cvx.red = random() & 65535;
722 cvx.green = random() & 65535;
723 cvx.blue = random() & 65535;
724 cvx.flags = DoRed|DoGreen|DoBlue;
725 XStoreColor(thedisplay, ourras->cmap, &cvx);
726 return(0);
727 case 'p': /* position */
728 pix2loc(hv, &inpres, ekey->x-xoff, ekey->y-yoff);
729 sprintf(buf, "(%d,%d)", (int)(hv[0]*inpres.xr),
730 (int)(hv[1]*inpres.yr));
731 XDrawImageString(thedisplay, wind, ourgc, ekey->x, ekey->y,
732 buf, strlen(buf));
733 return(0);
734 case 't': /* trace */
735 return(traceray(ekey->x, ekey->y));
736 case '=': /* adjust exposure */
737 case '@': /* adaptation level */
738 if (avgbox(cval) == -1)
739 return(-1);
740 comp = bright(cval);
741 if (comp < 1e-20) {
742 XBell(thedisplay, 0);
743 return(-1);
744 }
745 if (com == '@')
746 comp = 106./exposure/
747 pow(1.219+pow(comp*WHTEFFICACY/exposure,.4),2.5);
748 else
749 comp = .5/comp;
750 comp = log(comp)/.69315 - scale;
751 n = comp < 0 ? comp-.5 : comp+.5 ; /* round */
752 if (tmflags != -1)
753 tmflags = -1; /* turn off tone mapping */
754 else {
755 if (n == 0) /* else check if any change */
756 return(0);
757 scale_rcolors(ourras, pow(2.0, (double)n));
758 }
759 scale += n;
760 sprintf(buf, "%+d", scale);
761 XDrawImageString(thedisplay, wind, ourgc,
762 box.xmin, box.ymin+box.ysiz, buf, strlen(buf));
763 XFlush(thedisplay);
764 free(ourdata);
765 free_raster(ourras);
766 getras();
767 /* fall through */
768 case CTRL('R'): /* redraw */
769 case CTRL('L'):
770 unmap_rcolors(ourras);
771 XClearWindow(thedisplay, wind);
772 map_rcolors(ourras, wind);
773 if (fast)
774 make_rpixmap(ourras, wind);
775 redraw(0, 0, width, height);
776 return(0);
777 case 'f': /* turn on fast redraw */
778 fast = 1;
779 make_rpixmap(ourras, wind);
780 return(0);
781 case 'F': /* turn off fast redraw */
782 fast = 0;
783 free_rpixmap(ourras);
784 return(0);
785 case '0': /* recenter origin */
786 if (xoff == 0 & yoff == 0)
787 return(0);
788 xoff = yoff = 0;
789 XClearWindow(thedisplay, wind);
790 redraw(0, 0, width, height);
791 return(0);
792 case ' ': /* clear */
793 redraw(box.xmin, box.ymin, box.xsiz, box.ysiz);
794 return(0);
795 default:
796 XBell(thedisplay, 0);
797 return(-1);
798 }
799 }
800
801
802 moveimage(ebut) /* shift the image */
803 XButtonPressedEvent *ebut;
804 {
805 XEvent e;
806 int mxo, myo;
807
808 XMaskEvent(thedisplay, ButtonReleaseMask|ButtonMotionMask, &e);
809 while (e.type == MotionNotify) {
810 mxo = e.xmotion.x;
811 myo = e.xmotion.y;
812 revline(ebut->x, ebut->y, mxo, myo);
813 revbox(xoff+mxo-ebut->x, yoff+myo-ebut->y,
814 xoff+mxo-ebut->x+xmax, yoff+myo-ebut->y+ymax);
815 XMaskEvent(thedisplay,ButtonReleaseMask|ButtonMotionMask,&e);
816 revline(ebut->x, ebut->y, mxo, myo);
817 revbox(xoff+mxo-ebut->x, yoff+myo-ebut->y,
818 xoff+mxo-ebut->x+xmax, yoff+myo-ebut->y+ymax);
819 }
820 xoff += e.xbutton.x - ebut->x;
821 yoff += e.xbutton.y - ebut->y;
822 XClearWindow(thedisplay, wind);
823 redraw(0, 0, width, height);
824 }
825
826
827 getbox(ebut) /* get new box */
828 XButtonPressedEvent *ebut;
829 {
830 XEvent e;
831
832 XMaskEvent(thedisplay, ButtonReleaseMask|ButtonMotionMask, &e);
833 while (e.type == MotionNotify) {
834 revbox(ebut->x, ebut->y, box.xmin = e.xmotion.x, box.ymin = e.xmotion.y);
835 XMaskEvent(thedisplay,ButtonReleaseMask|ButtonMotionMask,&e);
836 revbox(ebut->x, ebut->y, box.xmin, box.ymin);
837 }
838 box.xmin = e.xbutton.x<0 ? 0 : (e.xbutton.x>=width ? width-1 : e.xbutton.x);
839 box.ymin = e.xbutton.y<0 ? 0 : (e.xbutton.y>=height ? height-1 : e.xbutton.y);
840 if (box.xmin > ebut->x) {
841 box.xsiz = box.xmin - ebut->x + 1;
842 box.xmin = ebut->x;
843 } else {
844 box.xsiz = ebut->x - box.xmin + 1;
845 }
846 if (box.ymin > ebut->y) {
847 box.ysiz = box.ymin - ebut->y + 1;
848 box.ymin = ebut->y;
849 } else {
850 box.ysiz = ebut->y - box.ymin + 1;
851 }
852 }
853
854
855 trackrays(ebut) /* trace rays as mouse moves */
856 XButtonPressedEvent *ebut;
857 {
858 XEvent e;
859 unsigned long lastrept;
860
861 traceray(ebut->x, ebut->y);
862 lastrept = ebut->time;
863 XMaskEvent(thedisplay, ButtonReleaseMask|ButtonMotionMask, &e);
864 while (e.type == MotionNotify) {
865 if (e.xmotion.time >= lastrept + tinterv) {
866 traceray(e.xmotion.x, e.xmotion.y);
867 lastrept = e.xmotion.time;
868 }
869 XMaskEvent(thedisplay,ButtonReleaseMask|ButtonMotionMask,&e);
870 }
871 }
872
873
874 revbox(x0, y0, x1, y1) /* draw box with reversed lines */
875 int x0, y0, x1, y1;
876 {
877 revline(x0, y0, x1, y0);
878 revline(x0, y1, x1, y1);
879 revline(x0, y0, x0, y1);
880 revline(x1, y0, x1, y1);
881 }
882
883
884 avgbox(clr) /* average color over current box */
885 COLOR clr;
886 {
887 static COLOR lc;
888 static int ll, lr, lt, lb;
889 int left, right, top, bottom;
890 int y;
891 double d;
892 COLOR ctmp;
893 register int x;
894
895 setcolor(clr, 0.0, 0.0, 0.0);
896 left = box.xmin - xoff;
897 right = left + box.xsiz;
898 if (left < 0)
899 left = 0;
900 if (right > xmax)
901 right = xmax;
902 if (left >= right)
903 return(-1);
904 top = box.ymin - yoff;
905 bottom = top + box.ysiz;
906 if (top < 0)
907 top = 0;
908 if (bottom > ymax)
909 bottom = ymax;
910 if (top >= bottom)
911 return(-1);
912 if (left == ll && right == lr && top == lt && bottom == lb) {
913 copycolor(clr, lc);
914 return(0);
915 }
916 for (y = top; y < bottom; y++) {
917 if (getscan(y) == -1)
918 return(-1);
919 for (x = left; x < right; x++) {
920 colr_color(ctmp, scanline[x]);
921 addcolor(clr, ctmp);
922 }
923 }
924 d = 1.0/((right-left)*(bottom-top));
925 scalecolor(clr, d);
926 ll = left; lr = right; lt = top; lb = bottom;
927 copycolor(lc, clr);
928 return(0);
929 }
930
931
932 make_tonemap() /* initialize tone mapping */
933 {
934 int y;
935
936 if (tmflags != -1 && fname == NULL) {
937 fprintf(stderr, "%s: cannot adjust tone of standard input\n",
938 progname);
939 tmflags = -1;
940 }
941 if (tmflags == -1) {
942 setcolrcor(pow, 1.0/gamcor);
943 return;
944 }
945 if (greyscale)
946 tmflags |= TM_F_BW;
947 /* initialize tm library */
948 if (tmInit(tmflags, stdprims, gamcor) == NULL)
949 goto memerr;
950 if (tmSetSpace(stdprims, WHTEFFICACY/exposure))
951 goto tmerr;
952 /* allocate encoding buffers */
953 if ((lscan = (TMbright *)malloc(xmax*sizeof(TMbright))) == NULL)
954 goto memerr;
955 if (tmflags & TM_F_BW) {
956 cscan = TM_NOCHROM;
957 if ((pscan = (BYTE *)malloc(sizeof(BYTE)*xmax)) == NULL)
958 goto memerr;
959 } else if ((pscan=cscan = (BYTE *)malloc(3*sizeof(BYTE)*xmax)) == NULL)
960 goto memerr;
961 /* compute picture histogram */
962 for (y = 0; y < ymax; y++) {
963 getscan(y);
964 if (tmCvColrs(lscan, TM_NOCHROM, scanline, xmax))
965 goto tmerr;
966 if (tmAddHisto(lscan, xmax, 1))
967 goto tmerr;
968 }
969 /* compute tone mapping */
970 if (tmComputeMapping(gamcor, 0., 0.))
971 goto tmerr;
972 free((char *)lscan);
973 return;
974 memerr:
975 quiterr("out of memory in make_tonemap");
976 tmerr:
977 quiterr("tone mapping error");
978 }
979
980
981 tmap_colrs(scn, len) /* apply tone mapping to scanline */
982 register COLR *scn;
983 int len;
984 {
985 register BYTE *ps;
986
987 if (tmflags == -1) {
988 if (scale)
989 shiftcolrs(scn, len, scale);
990 colrs_gambs(scn, len);
991 return;
992 }
993 if (len > xmax)
994 quiterr("code error 1 in tmap_colrs");
995 if (tmCvColrs(lscan, cscan, scn, len))
996 goto tmerr;
997 if (tmMapPixels(pscan, lscan, cscan, len))
998 goto tmerr;
999 ps = pscan;
1000 if (tmflags & TM_F_BW)
1001 while (len--) {
1002 scn[0][RED] = scn[0][GRN] = scn[0][BLU] = *ps++;
1003 scn[0][EXP] = COLXS;
1004 scn++;
1005 }
1006 else
1007 while (len--) {
1008 scn[0][RED] = *ps++;
1009 scn[0][GRN] = *ps++;
1010 scn[0][BLU] = *ps++;
1011 scn[0][EXP] = COLXS;
1012 scn++;
1013 }
1014 return;
1015 tmerr:
1016 quiterr("tone mapping error");
1017 }
1018
1019
1020 done_tonemap() /* clean up after tone mapping is done */
1021 {
1022 if (tmflags == -1 || tmTop == NULL)
1023 return;
1024 tmDone(tmTop); /* clear old mapping */
1025 free((char *)lscan); /* free memory */
1026 free((char *)pscan);
1027 }
1028
1029
1030 getmono() /* get monochrome data */
1031 {
1032 register unsigned char *dp;
1033 register int x, err;
1034 int y, errp;
1035 short *cerr;
1036
1037 if ((cerr = (short *)calloc(xmax,sizeof(short))) == NULL)
1038 quiterr("out of memory in getmono");
1039 dp = ourdata - 1;
1040 for (y = 0; y < ymax; y++) {
1041 getscan(y);
1042 add2icon(y, scanline);
1043 normcolrs(scanline, xmax, scale);
1044 err = 0;
1045 for (x = 0; x < xmax; x++) {
1046 if (!(x&7))
1047 *++dp = 0;
1048 errp = err;
1049 err += normbright(scanline[x]) + cerr[x];
1050 if (err > 127)
1051 err -= 255;
1052 else
1053 *dp |= 1<<(7-(x&07));
1054 err /= 3;
1055 cerr[x] = err + errp;
1056 }
1057 }
1058 free((char *)cerr);
1059 }
1060
1061
1062 add2icon(y, scan) /* add a scanline to our icon data */
1063 int y;
1064 COLR *scan;
1065 {
1066 static short cerr[ICONSIZ];
1067 static int ynext;
1068 static char *dp;
1069 COLR clr;
1070 register int err;
1071 register int x, ti;
1072 int errp;
1073
1074 if (iconheight == 0) { /* initialize */
1075 if (xmax <= ICONSIZ && ymax <= ICONSIZ) {
1076 iconwidth = xmax;
1077 iconheight = ymax;
1078 } else if (xmax > ymax) {
1079 iconwidth = ICONSIZ;
1080 iconheight = ICONSIZ*ymax/xmax;
1081 if (iconheight < 1)
1082 iconheight = 1;
1083 } else {
1084 iconwidth = ICONSIZ*xmax/ymax;
1085 if (iconwidth < 1)
1086 iconwidth = 1;
1087 iconheight = ICONSIZ;
1088 }
1089 ynext = 0;
1090 dp = icondata - 1;
1091 }
1092 if (y < ynext*ymax/iconheight) /* skip this one */
1093 return;
1094 err = 0;
1095 for (x = 0; x < iconwidth; x++) {
1096 if (!(x&7))
1097 *++dp = 0;
1098 errp = err;
1099 ti = x*xmax/iconwidth;
1100 copycolr(clr, scan[ti]);
1101 normcolrs(clr, 1, scale);
1102 err += normbright(clr) + cerr[x];
1103 if (err > 127)
1104 err -= 255;
1105 else
1106 *dp |= 1<<(x&07);
1107 err /= 3;
1108 cerr[x] = err + errp;
1109 }
1110 ynext++;
1111 }
1112
1113
1114 getfull() /* get full (24-bit) data */
1115 {
1116 int y;
1117 register unsigned int4 *dp;
1118 register int x;
1119 /* initialize tone mapping */
1120 make_tonemap();
1121 /* read and convert file */
1122 dp = (unsigned int4 *)ourdata;
1123 for (y = 0; y < ymax; y++) {
1124 getscan(y);
1125 add2icon(y, scanline);
1126 tmap_colrs(scanline, xmax);
1127 if (ourras->image->blue_mask & 1)
1128 for (x = 0; x < xmax; x++)
1129 *dp++ = (unsigned int4)scanline[x][RED] << 16 |
1130 (unsigned int4)scanline[x][GRN] << 8 |
1131 (unsigned int4)scanline[x][BLU] ;
1132 else
1133 for (x = 0; x < xmax; x++)
1134 *dp++ = (unsigned int4)scanline[x][RED] |
1135 (unsigned int4)scanline[x][GRN] << 8 |
1136 (unsigned int4)scanline[x][BLU] << 16 ;
1137 }
1138 done_tonemap();
1139 }
1140
1141
1142 getgrey() /* get greyscale data */
1143 {
1144 int y;
1145 register unsigned char *dp;
1146 register int x;
1147 /* initialize tone mapping */
1148 make_tonemap();
1149 /* read and convert file */
1150 dp = ourdata;
1151 for (y = 0; y < ymax; y++) {
1152 getscan(y);
1153 add2icon(y, scanline);
1154 tmap_colrs(scanline, xmax);
1155 if (maxcolors < 256)
1156 for (x = 0; x < xmax; x++)
1157 *dp++ = ((int4)scanline[x][GRN] *
1158 maxcolors + maxcolors/2) >> 8;
1159 else
1160 for (x = 0; x < xmax; x++)
1161 *dp++ = scanline[x][GRN];
1162 }
1163 for (x = 0; x < maxcolors; x++)
1164 clrtab[x][RED] = clrtab[x][GRN] =
1165 clrtab[x][BLU] = ((int4)x*256 + 128)/maxcolors;
1166 done_tonemap();
1167 }
1168
1169
1170 getmapped() /* get color-mapped data */
1171 {
1172 int y;
1173 /* make sure we can do it first */
1174 if (fname == NULL)
1175 quiterr("cannot map colors from standard input");
1176 /* initialize tone mapping */
1177 make_tonemap();
1178 /* make histogram */
1179 if (new_histo((int4)xmax*ymax) == -1)
1180 quiterr("cannot initialize histogram");
1181 for (y = 0; y < ymax; y++) {
1182 if (getscan(y) < 0)
1183 break;
1184 add2icon(y, scanline);
1185 tmap_colrs(scanline, xmax);
1186 cnt_colrs(scanline, xmax);
1187 }
1188 /* map pixels */
1189 if (!new_clrtab(maxcolors))
1190 quiterr("cannot create color map");
1191 for (y = 0; y < ymax; y++) {
1192 getscan(y);
1193 tmap_colrs(scanline, xmax);
1194 if (dither)
1195 dith_colrs(ourdata+y*xmax, scanline, xmax);
1196 else
1197 map_colrs(ourdata+y*xmax, scanline, xmax);
1198 }
1199 done_tonemap();
1200 }
1201
1202
1203 scale_rcolors(xr, sf) /* scale color map */
1204 register XRASTER *xr;
1205 double sf;
1206 {
1207 register int i;
1208 long maxv;
1209
1210 if (xr->pixels == NULL)
1211 return;
1212
1213 sf = pow(sf, 1.0/gamcor);
1214 maxv = 65535/sf;
1215
1216 for (i = xr->ncolors; i--; ) {
1217 xr->cdefs[i].red = xr->cdefs[i].red > maxv ?
1218 65535 :
1219 xr->cdefs[i].red * sf;
1220 xr->cdefs[i].green = xr->cdefs[i].green > maxv ?
1221 65535 :
1222 xr->cdefs[i].green * sf;
1223 xr->cdefs[i].blue = xr->cdefs[i].blue > maxv ?
1224 65535 :
1225 xr->cdefs[i].blue * sf;
1226 }
1227 XStoreColors(thedisplay, xr->cmap, xr->cdefs, xr->ncolors);
1228 }
1229
1230
1231 getscan(y)
1232 int y;
1233 {
1234 static int trunced = -1; /* truncated file? */
1235 skipit:
1236 if (trunced >= 0 && y >= trunced) {
1237 bzero(scanline, xmax*sizeof(COLR));
1238 return(-1);
1239 }
1240 if (y != cury) {
1241 if (scanpos == NULL || scanpos[y] == -1)
1242 return(-1);
1243 if (fseek(fin, scanpos[y], 0) == -1)
1244 quiterr("fseek error");
1245 cury = y;
1246 } else if (scanpos != NULL && scanpos[y] == -1)
1247 scanpos[y] = ftell(fin);
1248
1249 if (freadcolrs(scanline, xmax, fin) < 0) {
1250 fprintf(stderr, "%s: %s: unfinished picture\n",
1251 progname, fname==NULL?"<stdin>":fname);
1252 trunced = y;
1253 goto skipit;
1254 }
1255 cury++;
1256 return(0);
1257 }