1b95173ae8432e64095b47afeb1189efa2b9e76e
[xscreensaver] / hacks / glx / font-ximage.c
1 /* font-ximage.c --- renders text to an XImage for use with OpenGL.
2  * xscreensaver, Copyright (c) 2001 Jamie Zawinski <jwz@jwz.org>
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation.  No representations are made about the suitability of this
9  * software for any purpose.  It is provided "as is" without express or 
10  * implied warranty.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <X11/Xlib.h>
21 #include <X11/Xutil.h>
22 #include <GL/gl.h>      /* only for GLfloat */
23
24 extern char *progname;
25
26 #include <X11/Xutil.h>
27
28 #undef MAX
29 #define MAX(a,b) ((a)>(b)?(a):(b))
30
31 #undef countof
32 #define countof(x) (sizeof((x))/sizeof((*x)))
33
34 static Bool
35 bigendian (void)
36 {
37   union { int i; char c[sizeof(int)]; } u;
38   u.i = 1;
39   return !u.c[0];
40 }
41
42 /* return the next larger power of 2. */
43 static int
44 to_pow2 (int i)
45 {
46   static unsigned int pow2[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024,
47                                  2048, 4096, 8192, 16384, 32768, 65536 };
48   int j;
49   for (j = 0; j < countof(pow2); j++)
50     if (pow2[j] >= i) return pow2[j];
51   abort();  /* too big! */
52 }
53
54
55 /* Returns an XImage structure containing the string rendered in the font.
56    This XImage will be 32 bits per pixel, 8 each per R, G, and B, with the
57    extra byte set to 0xFF.
58
59    Foregroune and background are GL-style color specifiers: 4 floats from
60    0.0-1.0.
61  */
62 XImage *
63 text_to_ximage (Screen *screen, Visual *visual,
64                 const char *font,
65                 const char *text_lines,
66                 GLfloat *texture_fg,
67                 GLfloat *texture_bg)
68 {
69   Display *dpy = DisplayOfScreen (screen);
70   int width, height;
71   XFontStruct *f;
72   Pixmap bitmap;
73
74   f = XLoadQueryFont(dpy, font);
75   if (!f)
76     {
77       f = XLoadQueryFont(dpy, "fixed");
78       if (f)
79         fprintf (stderr, "%s: unable to load font \"%s\"; using \"fixed\".\n",
80                  progname, font);
81       else
82         {
83           fprintf (stderr, "%s: unable to load fonts \"%s\" or \"fixed\"!\n",
84                    progname, font);
85           exit (1);
86         }
87     }
88
89   /* Parse the text, and render it to `bitmap'
90    */
91   {
92     char *text, *text2, *line, *token;
93     int lines;
94     XCharStruct overall;
95     XGCValues gcv;
96     GC gc;
97
98     int margin = 2;
99     int fg = 1;
100     int bg = 0;
101     int xoff, yoff;
102
103     text  = strdup (text_lines);
104     while (*text &&
105            (text[strlen(text)-1] == '\r' ||
106             text[strlen(text)-1] == '\n'))
107       text[strlen(text)-1] = 0;
108
109     text2 = strdup (text);
110
111     memset(&overall, 0, sizeof(overall));
112     token = text;
113     lines = 0;
114     while ((line = strtok (token, "\r\n")))
115       {
116         XCharStruct o2;
117         int ascent, descent, direction;
118         token = 0;
119         XTextExtents (f, line, strlen(line),
120                       &direction, &ascent, &descent, &o2);
121         overall.lbearing = MAX(overall.lbearing, o2.lbearing);
122         overall.rbearing = MAX(overall.rbearing, o2.rbearing);
123         lines++;
124       }
125
126     width = overall.lbearing + overall.rbearing + margin + margin + 1;
127     height = ((f->ascent + f->descent) * lines) + margin + margin;
128
129     /* GL texture sizes must be powers of two. */
130     {
131       int w2 = to_pow2(width);
132       int h2 = to_pow2(height);
133       xoff = (w2 - width)  / 2;
134       yoff = (h2 - height) / 2;
135       width  = w2;
136       height = h2;
137     }
138
139     bitmap = XCreatePixmap(dpy, RootWindowOfScreen (screen), width, height, 1);
140
141     gcv.font = f->fid;
142     gcv.foreground = bg;
143     gc = XCreateGC (dpy, bitmap, (GCFont | GCForeground), &gcv);
144     XFillRectangle(dpy, bitmap, gc, 0, 0, width, height);
145     XSetForeground(dpy, gc, fg);
146
147     token = text2;
148     lines = 0;
149     while ((line = strtok(token, "\r\n")))
150       {
151         XCharStruct o2;
152         int ascent, descent, direction, xoff2;
153         token = 0;
154
155         XTextExtents(f, line, strlen(line),
156                      &direction, &ascent, &descent, &o2);
157         xoff2 = (xoff +
158                  ((overall.lbearing + overall.rbearing) -
159                   (o2.lbearing + o2.rbearing)) / 2);
160
161         XDrawString(dpy, bitmap, gc,
162                     overall.lbearing + margin + xoff,
163                     ((f->ascent * (lines + 1)) +
164                      (f->descent * lines) +
165                      margin +
166                      yoff),
167                     line, strlen(line));
168         lines++;
169       }
170     free(text2);
171
172     XUnloadFont(dpy, f->fid);
173     XFree((XPointer) f);
174     XFreeGC(dpy, gc);
175   }
176
177   /* Convert the server-side Pixmap to a client-side GL-ordered XImage.
178    */
179   {
180     XImage *ximage1, *ximage2;
181     unsigned long fg, bg;
182     int x, y;
183
184     ximage1 = XGetImage (dpy, bitmap, 0, 0, width, height, ~0L, ZPixmap);
185     XFreePixmap(dpy, bitmap);
186     ximage2 = XCreateImage (dpy, visual, 32, ZPixmap, 0, 0,
187                             width, height, 32, 0);
188
189     ximage2->data = (char *) malloc (height * ximage2->bytes_per_line);
190
191     /* Translate the 1-bit image to a deep image:
192        first figure out what the colors are.
193      */
194     {
195       int rpos, gpos, bpos, apos;  /* bitfield positions */
196
197       /* Note that unlike X, which is endianness-agnostic (since any XImage
198          can have its own specific bit ordering, with the server reversing
199          things as necessary) OpenGL pretends everything is client-side, so
200          we need to pack things in the right order for the client machine.
201        */
202       if (bigendian())
203         rpos = 24, gpos = 16, bpos =  8, apos =  0;
204       else
205         rpos =  0, gpos =  8, bpos = 16, apos = 24;
206
207       fg = (((unsigned long) (texture_fg[0] * 255.0) << rpos) |
208             ((unsigned long) (texture_fg[1] * 255.0) << gpos) |
209             ((unsigned long) (texture_fg[2] * 255.0) << bpos) |
210             ((unsigned long) (texture_fg[3] * 255.0) << apos));
211       bg = (((unsigned long) (texture_bg[0] * 255.0) << rpos) |
212             ((unsigned long) (texture_bg[1] * 255.0) << gpos) |
213             ((unsigned long) (texture_bg[2] * 255.0) << bpos) |
214             ((unsigned long) (texture_bg[3] * 255.0) << apos));
215     }
216
217     for (y = 0; y < height; y++)
218       {
219         int y2 = (height-1-y); /* Texture maps are upside down. */
220         for (x = 0; x < width; x++)
221           XPutPixel (ximage2, x, y, 
222                      XGetPixel (ximage1, x, y2) ? fg : bg);
223       }
224
225     free (ximage1->data);
226     ximage1->data = 0;
227     XDestroyImage (ximage1);
228
229 #if 0
230     for (y = 0; y < height; y++)
231       {
232         int y2 = (height-1-y); /* Texture maps are upside down. */
233         for (x = 0; x < width; x++)
234           fputc ((XGetPixel (ximage2, x, y2) == fg ? '#' : ' '), stdout);
235         fputc ('\n', stdout);
236       }
237     fputc ('\n', stdout);
238 #endif /* 0 */
239
240     return ximage2;
241   }
242 }