http://packetstormsecurity.org/UNIX/admin/xscreensaver-4.14.tar.gz
[xscreensaver] / hacks / glx / spheremonics.c
1 /* xscreensaver, Copyright (c) 2002 Jamie Zawinski <jwz@jwz.org>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or 
9  * implied warranty.
10  *
11  * Algorithm by Paul Bourke <pbourke@swin.edu.au>
12  * http://astronomy.swin.edu.au/~pbourke/geometry/sphericalh/
13  * Screensaver veneer and parameter selection by jwz.
14  *
15  *  Paul says:
16  *
17  * These closed objects are commonly called spherical harmonics,
18  * although they are only remotely related to the mathematical
19  * definition found in the solution to certain wave functions, most
20  * notable the eigenfunctions of angular momentum operators.
21  *
22  * The formula is quite simple: the form used here is based upon
23  * spherical (polar) coordinates (radius, theta, phi).
24  *
25  *    r = sin(m0 phi)   ^ m1 + 
26  *        cos(m2 phi)   ^ m3 + 
27  *        sin(m4 theta) ^ m5 + 
28  *        cos(m6 theta) ^ m7 
29  *
30  * Where phi ranges from 0 to pi (lines of latitude), and theta ranges
31  * from 0 to 2 pi (lines of longitude), and r is the radius.  The
32  * parameters m0, m1, m2, m3, m4, m5, m6, and m7 are all integers
33  * greater than or equal to 0.
34  *
35  * As the degree increases, the objects become increasingly "pointed"
36  * and a large number of polygons are required to represent the surface
37  * faithfully.
38  *
39  * jwz adds:
40  * 
41  * The eight parameters live in the `cc->m' array.
42  * Each time we permute the image, we alter *one* of those eight parameters.
43  * Each time we alter a parameter, we move it in the same direction (either
44  * toward larger or smaller values) in the range [0, 3].
45  *
46  * By altering only one parameter at a time, and only by small amounts,
47  * we tend to produce successive objects that are pretty similar to each
48  * other, so you can see a progression.
49  *
50  * It'd be nice if they were even closer together, so that it looked more
51  * like a morph, but, well, that's not how it works.
52  *
53  * There tends to be a dark stripe in the colormaps.  I don't know why.
54  * Perhaps utils/colors.c is at fault?
55  *
56  * Note that this equation sometimes generates faces that are inside out:
57  *     -parameters 01210111
58  * To make this work, we need to render back-faces with two-sided lighting:
59  * figuring out how to correct the winding and normals on those inside out
60  * surfaces would be too hard.
61  */
62
63 #include <X11/Intrinsic.h>
64
65 extern XtAppContext app;
66
67 #define PROGCLASS       "Spheremonics"
68 #define HACK_INIT       init_spheremonics
69 #define HACK_DRAW       draw_spheremonics
70 #define HACK_RESHAPE    reshape_spheremonics
71 #define HACK_HANDLE_EVENT spheremonics_handle_event
72 #define EVENT_MASK      PointerMotionMask
73 #define ccs_opts        xlockmore_opts
74
75 #define DEF_DURATION    "100"
76 #define DEF_SPIN        "XYZ"
77 #define DEF_WANDER      "False"
78 #define DEF_RESOLUTION  "64"
79 #define DEF_BBOX        "False"
80 #define DEF_GRID        "True"
81 #define DEF_SMOOTH      "True"
82 #define DEF_PARMS       "(default)"
83
84 #define DEFAULTS        "*delay:        30000       \n" \
85                         "*resolution: " DEF_RESOLUTION "\n" \
86                         "*showFPS:      False       \n" \
87                         "*wireframe:    False       \n" \
88                         "*duration:   " DEF_DURATION "\n" \
89                         "*spin:       " DEF_SPIN   "\n" \
90                         "*wander:     " DEF_WANDER "\n" \
91                         "*bbox:       " DEF_BBOX   "\n" \
92                         "*grid:       " DEF_GRID   "\n" \
93                         "*smooth:     " DEF_SMOOTH "\n" \
94                         "*parameters: " DEF_PARMS  "\n" \
95
96 #undef countof
97 #define countof(x) (sizeof((x))/sizeof((*x)))
98
99 #include "xlockmore.h"
100 #include "colors.h"
101 #include "rotator.h"
102 #include "gltrackball.h"
103 #include <ctype.h>
104
105 #ifdef USE_GL /* whole file */
106
107 #include <GL/glu.h>
108
109 typedef struct {
110    double x,y,z;
111 } XYZ;
112
113 typedef struct {
114   GLXContext *glx_context;
115   rotator *rot;
116   trackball_state *trackball;
117   Bool button_down_p;
118
119   GLuint dlist, dlist2;
120   GLfloat scale;
121   XYZ bbox[2];
122
123   int resolution;
124   int ncolors;
125   XColor *colors;
126
127   int m[8];
128   int dm[8];
129   int m_max;
130
131   int tracer;
132   int mesher;
133   int polys1, polys2;  /* polygon counts */
134
135   XFontStruct *font;
136   GLuint font_list;
137
138 } spheremonics_configuration;
139
140 static spheremonics_configuration *ccs = NULL;
141
142 static char *do_spin;
143 static Bool do_wander;
144 static Bool do_bbox;
145 static Bool do_grid;
146 static int smooth_p;
147 static char *static_parms;
148 static int res;
149 static int duration;
150
151 static XrmOptionDescRec opts[] = {
152   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
153   { "+spin",   ".spin",   XrmoptionNoArg, "" },
154   { "-wander", ".wander", XrmoptionNoArg, "True" },
155   { "+wander", ".wander", XrmoptionNoArg, "False" },
156   { "-resolution", ".resolution", XrmoptionSepArg, 0 },
157   { "-duration",   ".duration",   XrmoptionSepArg, 0 },
158   { "-bbox",   ".bbox",  XrmoptionNoArg, "True" },
159   { "+bbox",   ".bbox",  XrmoptionNoArg, "False" },
160   { "-grid",   ".grid",  XrmoptionNoArg, "True" },
161   { "+grid",   ".grid",  XrmoptionNoArg, "False" },
162   {"-smooth",  ".smooth", XrmoptionNoArg, "True" },
163   {"+smooth",  ".smooth", XrmoptionNoArg, "False" },
164   { "-parameters", ".parameters", XrmoptionSepArg, 0 },
165 };
166
167 static argtype vars[] = {
168   {(caddr_t *) &do_spin,   "spin",   "Spin",   DEF_SPIN,   t_String},
169   {(caddr_t *) &do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
170   {(caddr_t *) &res,       "resolution", "Resolution", DEF_RESOLUTION, t_Int},
171   {(caddr_t *) &duration,  "duration",   "Duration",   DEF_DURATION,   t_Int},
172   {(caddr_t *) &do_bbox,   "bbox",   "BBox",   DEF_BBOX,   t_Bool},
173   {(caddr_t *) &do_grid,   "grid",   "Grid",   DEF_GRID,   t_Bool},
174   {(caddr_t *) &smooth_p,  "smooth", "Smooth", DEF_SMOOTH, t_Bool},
175   {(caddr_t *) &static_parms, "parameters", "Parameters", DEF_PARMS, t_String},
176 };
177
178 ModeSpecOpt ccs_opts = {countof(opts), opts, countof(vars), vars, NULL};
179
180
181 /* Window management, etc
182  */
183 void
184 reshape_spheremonics (ModeInfo *mi, int width, int height)
185 {
186   GLfloat h = (GLfloat) height / (GLfloat) width;
187
188   glViewport (0, 0, (GLint) width, (GLint) height);
189
190   glMatrixMode(GL_PROJECTION);
191   glLoadIdentity();
192   gluPerspective (30.0, 1/h, 1.0, 100.0);
193
194   glMatrixMode(GL_MODELVIEW);
195   glLoadIdentity();
196   gluLookAt( 0.0, 0.0, 30.0,
197              0.0, 0.0, 0.0,
198              0.0, 1.0, 0.0);
199
200   glClear(GL_COLOR_BUFFER_BIT);
201 }
202
203
204 static void
205 gl_init (ModeInfo *mi)
206 {
207 /*  spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)]; */
208   int wire = MI_IS_WIREFRAME(mi);
209
210   static GLfloat pos[4] = {5.0, 5.0, 10.0, 1.0};
211
212   glEnable(GL_NORMALIZE);
213
214   if (!wire)
215     {
216       glLightfv(GL_LIGHT0, GL_POSITION, pos);
217       glEnable(GL_LIGHTING);
218       glEnable(GL_LIGHT0);
219       glEnable(GL_DEPTH_TEST);
220
221       /* With objects that have proper winding and normals set up on all
222          their faces, one can cull back-faces; however, these equations
223          generate objects that are sometimes "inside out", and determining
224          whether a facet has been inverted like that is really hard.
225          So we render both front and back faces, at a probable performance
226          penalty on non-accelerated systems.
227
228          When rendering back faces, we also need to do two-sided lighting,
229          or the fact that the normals are flipped gives us too-dark surfaces
230          on the inside-out surfaces.
231
232          This isn't generally something you'd want, because you end up
233          with half the lighting dynamic range (kind of.)  So if you had
234          a sphere with correctly pointing normals, and a single light
235          source, it would be illuminated from two sides.  In this case,
236          though, it saves us from a difficult and time consuming
237          inside/outside test.  And we don't really care about a precise
238          lighting effect.
239        */
240       glDisable(GL_CULL_FACE);
241       glLightModeli (GL_LIGHT_MODEL_TWO_SIDE, TRUE);
242     }
243 }
244
245
246 \f
247 /* generate the object */
248
249 static XYZ
250 sphere_eval (double theta, double phi, int *m)
251 {
252   double r = 0;
253   XYZ p;
254
255   r += pow (sin(m[0] * phi),  (double)m[1]);
256   r += pow (cos(m[2] * phi),  (double)m[3]);
257   r += pow (sin(m[4] * theta),(double)m[5]);
258   r += pow (cos(m[6] * theta),(double)m[7]);
259
260   p.x = r * sin(phi) * cos(theta);
261   p.y = r * cos(phi);
262   p.z = r * sin(phi) * sin(theta);
263
264   return (p);
265 }
266
267
268 /* Normalise a vector */
269 static void
270 normalize (XYZ *p)
271 {
272   double length;
273   length = sqrt(p->x * p->x + p->y * p->y + p->z * p->z);
274   if (length != 0) {
275     p->x /= length;
276     p->y /= length;
277     p->z /= length;
278   } else {
279     p->x = 0;
280     p->y = 0;
281     p->z = 0;
282   }       
283 }
284
285 /*-------------------------------------------------------------------------
286         Calculate the unit normal at p given two other points 
287         p1,p2 on the surface. The normal points in the direction 
288         of p1 crossproduct p2
289  */
290 static XYZ
291 calc_normal (XYZ p, XYZ p1, XYZ p2)
292 {
293   XYZ n, pa, pb;
294   pa.x = p1.x - p.x;
295   pa.y = p1.y - p.y;
296   pa.z = p1.z - p.z;
297   pb.x = p2.x - p.x;
298   pb.y = p2.y - p.y;
299   pb.z = p2.z - p.z;
300   n.x = pa.y * pb.z - pa.z * pb.y;
301   n.y = pa.z * pb.x - pa.x * pb.z;
302   n.z = pa.x * pb.y - pa.y * pb.x;
303   normalize (&n);
304   return (n);
305 }
306
307
308 static void
309 do_color (int i, XColor *colors)
310 {
311   GLfloat c[4];
312   c[0] = colors[i].red   / 65535.0;
313   c[1] = colors[i].green / 65535.0;
314   c[2] = colors[i].blue  / 65535.0;
315   c[3] = 1.0;
316   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, c);
317   glColor3f (c[0], c[1], c[2]);
318 }
319
320
321 static void
322 draw_circle (ModeInfo *mi, Bool teeth_p)
323 {
324   GLfloat th;
325   int tick = 0;
326   GLfloat x, y;
327   GLfloat step = (M_PI / 180);
328
329   glBegin(GL_LINE_LOOP);
330   for (th = 0; th < M_PI*2; th += step*5)
331     {
332       GLfloat r1 = 0.5;
333       x = cos (th);
334       y = sin (th);
335       glVertex3f(x*r1, y*r1,  0);
336     }
337   glEnd();
338
339   if (!teeth_p) return;
340
341   glBegin(GL_LINES);
342   for (th = 0; th < M_PI*2; th += step)
343     {
344       GLfloat r1 = 0.5;
345       GLfloat r2 = r1 - 0.01;
346       if (! (tick % 10))
347         r2 -= 0.02;
348       else if (! (tick % 5))
349         r2 -= 0.01;
350       tick++;
351
352       x = cos (th);
353       y = sin (th);
354       glVertex3f(x*r1, y*r1,  0);
355       glVertex3f(x*r2, y*r2,  0);
356     }
357   glEnd();
358 }
359
360
361 static void
362 draw_bounding_box (ModeInfo *mi)
363 {
364   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
365
366   static GLfloat c1[4] = { 0.2, 0.2, 0.6, 1.0 };
367   static GLfloat c2[4] = { 1.0, 0.0, 0.0, 1.0 };
368   int wire = MI_IS_WIREFRAME(mi);
369
370   GLfloat x1 = cc->bbox[0].x;
371   GLfloat y1 = cc->bbox[0].y;
372   GLfloat z1 = cc->bbox[0].z;
373   GLfloat x2 = cc->bbox[1].x;
374   GLfloat y2 = cc->bbox[1].y;
375   GLfloat z2 = cc->bbox[1].z;
376
377 #if 1
378   x1 = y1 = z1 = -0.5;
379   x2 = y2 = z2 =  0.5;
380 #endif
381
382   if (do_bbox && !wire)
383     {
384       glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, c1);
385       glFrontFace(GL_CCW);
386
387       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
388       glNormal3f(0, 1, 0);
389       glVertex3f(x1, y1, z1); glVertex3f(x1, y1, z2);
390       glVertex3f(x2, y1, z2); glVertex3f(x2, y1, z1);
391       glEnd();
392       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
393       glNormal3f(0, -1, 0);
394       glVertex3f(x2, y2, z1); glVertex3f(x2, y2, z2);
395       glVertex3f(x1, y2, z2); glVertex3f(x1, y2, z1);
396       glEnd();
397       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
398       glNormal3f(0, 0, 1);
399       glVertex3f(x1, y1, z1); glVertex3f(x2, y1, z1);
400       glVertex3f(x2, y2, z1); glVertex3f(x1, y2, z1);
401       glEnd();
402       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
403       glNormal3f(0, 0, -1);
404       glVertex3f(x1, y2, z2); glVertex3f(x2, y2, z2);
405       glVertex3f(x2, y1, z2); glVertex3f(x1, y1, z2);
406       glEnd();
407       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
408       glNormal3f(1, 0, 0);
409       glVertex3f(x1, y2, z1); glVertex3f(x1, y2, z2);
410       glVertex3f(x1, y1, z2); glVertex3f(x1, y1, z1);
411       glEnd();
412       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
413       glNormal3f(-1, 0, 0);
414       glVertex3f(x2, y1, z1); glVertex3f(x2, y1, z2);
415       glVertex3f(x2, y2, z2); glVertex3f(x2, y2, z1);
416       glEnd();
417     }
418
419   glPushAttrib (GL_LIGHTING);
420   glDisable (GL_LIGHTING);
421
422   glColor3f (c2[0], c2[1], c2[2]);
423
424   if (do_grid)
425     {
426       glPushMatrix();
427       glBegin(GL_LINES);
428       glVertex3f(0, -0.66, 0);
429       glVertex3f(0,  0.66, 0); 
430       glEnd();
431       draw_circle (mi, True);
432       glRotatef(90, 1, 0, 0);
433       draw_circle (mi, True);
434       glRotatef(90, 0, 1, 0);
435       draw_circle (mi, True);
436       glPopMatrix();
437     }
438   else
439     {
440       glBegin(GL_LINES);
441       if (x1 > 0) x1 = 0; if (x2 < 0) x2 = 0;
442       if (y1 > 0) y1 = 0; if (y2 < 0) y2 = 0;
443       if (z1 > 0) z1 = 0; if (z2 < 0) z2 = 0;
444       glVertex3f(x1, 0,  0);  glVertex3f(x2, 0,  0); 
445       glVertex3f(0 , y1, 0);  glVertex3f(0,  y2, 0); 
446       glVertex3f(0,  0,  z1); glVertex3f(0,  0,  z2); 
447       glEnd();
448     }
449
450   glPopAttrib();
451 }
452
453
454 static void
455 do_tracer (ModeInfo *mi)
456 {
457   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
458
459   if (cc->tracer == -1 &&
460       cc->mesher == -1 &&
461       !(random() % (duration * 4)))
462     {
463       if (random() & 1)
464         cc->tracer = ((random() & 1) ? 0 : 180);
465       else
466         cc->mesher = ((random() % ((duration / 3) + 1)) +
467                       (random() % ((duration / 3) + 1)));
468     }
469
470   if (cc->tracer >= 0)
471     {
472       int d = (90 - cc->tracer);
473       GLfloat th = d * (M_PI / 180);
474       GLfloat x = cos (th);
475       GLfloat y = sin (th);
476       GLfloat s = 1.5 / cc->scale;
477
478       if (s > 0.001)
479         {
480           static GLfloat c[4] = { 0.6, 0.5, 1.0, 1.0 };
481
482           glPushAttrib (GL_LIGHTING);
483           glDisable (GL_LIGHTING);
484
485           glPushMatrix();
486           glRotatef (90, 1, 0, 0);
487           glTranslatef (0, 0, y*s/2);
488           s *= x;
489           glScalef(s, s, s);
490           glColor3f (c[0], c[1], c[2]);
491           draw_circle (mi, False);
492           glPopMatrix();
493
494           glPopAttrib();
495         }
496
497       cc->tracer += 5;
498       if (cc->tracer == 180 || cc->tracer == 360)
499         cc->tracer = -1;
500     }
501 }
502
503
504 static int
505 unit_spheremonics (ModeInfo *mi,
506                    int resolution, Bool wire, int *m, XColor *colors)
507 {
508   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
509   int polys = 0;
510   int i, j;
511   double du, dv;
512   XYZ q[4];
513   XYZ n[4];
514   int res = (wire == 2
515              ? resolution / 2
516              : resolution);
517
518   cc->bbox[0].x = cc->bbox[0].y = cc->bbox[0].z = 0;
519   cc->bbox[1].x = cc->bbox[1].y = cc->bbox[1].z = 0;
520
521   du = (M_PI+M_PI) / (double)res; /* Theta */
522   dv = M_PI        / (double)res; /* Phi   */
523
524   if (wire)
525     glColor3f (1, 1, 1);
526
527   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);
528
529   for (i = 0; i < res; i++) {
530     double u = i * du;
531     for (j = 0; j < res; j++) {
532       double v = j * dv;
533       q[0] = sphere_eval (u, v, m);
534       n[0] = calc_normal(q[0],
535                          sphere_eval (u+du/10, v, m),
536                          sphere_eval (u, v+dv/10, m));
537       glNormal3f(n[0].x,n[0].y,n[0].z);
538       if (!wire) do_color (i, colors);
539       glVertex3f(q[0].x,q[0].y,q[0].z);
540
541       q[1] = sphere_eval (u+du, v, m);
542       n[1] = calc_normal(q[1],
543                          sphere_eval (u+du+du/10, v, m),
544                          sphere_eval (u+du, v+dv/10, m));
545       glNormal3f(n[1].x,n[1].y,n[1].z);
546       if (!wire) do_color ((i+1)%res, colors);
547       glVertex3f(q[1].x,q[1].y,q[1].z);
548
549       q[2] = sphere_eval (u+du, v+dv, m);
550       n[2] = calc_normal(q[2],
551                          sphere_eval (u+du+du/10, v+dv, m),
552                          sphere_eval (u+du, v+dv+dv/10, m));
553       glNormal3f(n[2].x,n[2].y,n[2].z);
554       if (!wire) do_color ((i+1)%res, colors);
555       glVertex3f(q[2].x,q[2].y,q[2].z);
556
557       q[3] = sphere_eval (u,v+dv, m);
558       n[3] = calc_normal(q[3],
559                          sphere_eval (u+du/10, v+dv, m),
560                          sphere_eval (u, v+dv+dv/10, m));
561       glNormal3f(n[3].x,n[3].y,n[3].z);
562       if (!wire) do_color (i, colors);
563       glVertex3f(q[3].x,q[3].y,q[3].z);
564
565       polys++;
566
567 # define CHECK_BBOX(N) \
568          if (q[(N)].x < cc->bbox[0].x) cc->bbox[0].x = q[(N)].x; \
569          if (q[(N)].y < cc->bbox[0].y) cc->bbox[0].y = q[(N)].y; \
570          if (q[(N)].z < cc->bbox[0].z) cc->bbox[0].z = q[(N)].z; \
571          if (q[(N)].x > cc->bbox[1].x) cc->bbox[1].x = q[(N)].x; \
572          if (q[(N)].y > cc->bbox[1].y) cc->bbox[1].y = q[(N)].y; \
573          if (q[(N)].z > cc->bbox[1].z) cc->bbox[1].z = q[(N)].z
574
575       CHECK_BBOX(0);
576       CHECK_BBOX(1);
577       CHECK_BBOX(2);
578       CHECK_BBOX(3);
579 # undef CHECK_BBOX
580     }
581   }
582   glEnd();
583
584   {
585     GLfloat w = cc->bbox[1].x - cc->bbox[0].x;
586     GLfloat h = cc->bbox[1].y - cc->bbox[0].y;
587     GLfloat d = cc->bbox[1].z - cc->bbox[0].z;
588     GLfloat wh = (w > h ? w : h);
589     GLfloat hd = (h > d ? h : d);
590     GLfloat scale = (wh > hd ? wh : hd);
591
592     cc->scale = 1/scale;
593
594     if (wire < 2 && (do_bbox || do_grid))
595       {
596         GLfloat s = scale * 1.5;
597         glPushMatrix();
598         glScalef(s, s, s);
599         draw_bounding_box (mi);
600         glPopMatrix();
601       }
602   }
603   return polys;
604 }
605
606
607 static void
608 init_colors (ModeInfo *mi)
609 {
610   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
611   int i;
612   cc->ncolors = cc->resolution;
613   cc->colors = (XColor *) calloc(cc->ncolors, sizeof(XColor));
614   make_smooth_colormap (0, 0, 0,
615                         cc->colors, &cc->ncolors, 
616                         False, 0, False);
617
618   /* brighter colors, please... */
619   for (i = 0; i < cc->ncolors; i++)
620     {
621       cc->colors[i].red   = (cc->colors[i].red   / 2) + 32767;
622       cc->colors[i].green = (cc->colors[i].green / 2) + 32767;
623       cc->colors[i].blue  = (cc->colors[i].blue  / 2) + 32767;
624     }
625 }
626
627
628 /* Pick one of the parameters to the function and tweak it up or down.
629  */
630 static void
631 tweak_parameters (ModeInfo *mi)
632 {
633   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
634
635   /* If the -parameters command line option was specified, just use that
636      all the time.
637    */
638   if (static_parms &&
639       *static_parms &&
640       !!strcasecmp (static_parms, "(default)"))
641     {
642       unsigned long n;
643       char dummy;
644       if (8 == sscanf (static_parms, "%d %d %d %d %d %d %d %d %c",
645                        &cc->m[0], &cc->m[1], &cc->m[2], &cc->m[3],
646                        &cc->m[4], &cc->m[5], &cc->m[6], &cc->m[7],
647                        &dummy))
648         return;
649       else if (strlen (static_parms) == 8 &&
650                1 == sscanf (static_parms, "%lu %c", &n, &dummy))
651         {
652           const char *s = static_parms;
653           int i = 0;
654           while (*s)
655             cc->m[i++] = (*s++)-'0';
656           return;
657         }
658       fprintf (stderr,
659                "%s: -parameters must be a string of 8 ints (not \"%s\")\n",
660                progname, static_parms);
661       exit (1);
662     }
663
664   static_parms = 0;
665
666
667 # define SHIFT(N) do { \
668     int n = (N); \
669     cc->m[n] += cc->dm[n]; \
670     if (cc->m[n] <= 0) \
671       cc->m[n] = 0, cc->dm[n] = -cc->dm[n]; \
672     else if (cc->m[n] >= cc->m_max) \
673       cc->m[n] = cc->m_max, cc->dm[n] = -cc->dm[n]; \
674   } while(0)
675
676 /*    else if (cc->m[n] >= cc->m_max/2 && (! (random() % 3))) \
677       cc->m[n] = cc->m_max/2, cc->dm[n] = -cc->dm[n]; \
678 */
679
680   switch(random() % 8)
681     {
682     case 0: SHIFT(0); break;
683     case 1: SHIFT(1); break;
684     case 2: SHIFT(2); break;
685     case 3: SHIFT(3); break;
686     case 4: SHIFT(4); break;
687     case 5: SHIFT(5); break;
688     case 6: SHIFT(6); break;
689     case 7: SHIFT(7); break;
690     default: abort(); break;
691     }
692 # undef SHIFT
693
694 #if 0
695     printf ("%s: state: %d %d %d %d %d %d %d %d\n",
696             progname,
697             cc->m[0], cc->m[1], cc->m[2], cc->m[3],
698             cc->m[4], cc->m[5], cc->m[6], cc->m[7]);
699 #endif
700
701 }
702
703
704 static void
705 generate_spheremonics (ModeInfo *mi)
706 {
707   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
708   int wire = MI_IS_WIREFRAME(mi);
709
710   tweak_parameters (mi);
711
712   {
713     static Bool done = False;
714     if (!done || (0 == (random() % 20)))
715       {
716         init_colors (mi);
717         done = True;
718       }
719   }
720
721   {
722     glNewList(cc->dlist, GL_COMPILE);
723     cc->polys1 = unit_spheremonics (mi, cc->resolution, wire,cc->m,cc->colors);
724     glEndList();
725
726     glNewList(cc->dlist2, GL_COMPILE);
727     glPushAttrib (GL_LIGHTING);
728     glDisable (GL_LIGHTING);
729     glPushMatrix();
730     glScalef (1.05, 1.05, 1.05);
731     cc->polys2 = unit_spheremonics (mi, cc->resolution, 2, cc->m, cc->colors);
732     glPopMatrix();
733     glPopAttrib();
734     glEndList();
735   }
736 }
737
738
739 \f
740
741 static void
742 load_font (ModeInfo *mi, char *res, XFontStruct **fontP, GLuint *dlistP)
743 {
744   const char *font = get_string_resource (res, "Font");
745   XFontStruct *f;
746   Font id;
747   int first, last;
748
749   if (!font) font = "-*-times-bold-r-normal-*-140-*";
750
751   f = XLoadQueryFont(mi->dpy, font);
752   if (!f) f = XLoadQueryFont(mi->dpy, "fixed");
753
754   id = f->fid;
755   first = f->min_char_or_byte2;
756   last = f->max_char_or_byte2;
757   
758   clear_gl_error ();
759   *dlistP = glGenLists ((GLuint) last+1);
760   check_gl_error ("glGenLists");
761   glXUseXFont(id, first, last-first+1, *dlistP + first);
762   check_gl_error ("glXUseXFont");
763
764   *fontP = f;
765 }
766
767 static void
768 draw_label (ModeInfo *mi, const char *s)
769 {
770   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
771   unsigned int i;
772   
773   glPushAttrib(GL_TRANSFORM_BIT | GL_ENABLE_BIT);
774   glDisable(GL_LIGHTING);
775   glDisable(GL_DEPTH_TEST);
776   glMatrixMode(GL_PROJECTION);
777   glPushMatrix();
778   glLoadIdentity();
779   glMatrixMode(GL_MODELVIEW);
780   glPushMatrix();
781   glLoadIdentity();
782   gluOrtho2D(0, mi->xgwa.width, 0, mi->xgwa.height);
783   glColor3f(1.0, 1.0, 0.0);
784
785   glRasterPos2f (10,
786                  (mi->xgwa.height
787                   - 10
788                   - (cc->font->ascent + cc->font->descent)));
789   for (i = 0; i < strlen(s); i++)
790     glCallList (cc->font_list + (int)s[i]);
791
792   glPopMatrix();
793   glMatrixMode(GL_PROJECTION);
794   glPopMatrix();
795   glPopAttrib();
796 }
797
798
799 \f
800
801 void 
802 init_spheremonics (ModeInfo *mi)
803 {
804   spheremonics_configuration *cc;
805
806   if (!ccs) {
807     ccs = (spheremonics_configuration *)
808       calloc (MI_NUM_SCREENS(mi), sizeof (spheremonics_configuration));
809     if (!ccs) {
810       fprintf(stderr, "%s: out of memory\n", progname);
811       exit(1);
812     }
813
814     cc = &ccs[MI_SCREEN(mi)];
815   }
816
817   cc = &ccs[MI_SCREEN(mi)];
818
819   if ((cc->glx_context = init_GL(mi)) != NULL) {
820     gl_init(mi);
821     reshape_spheremonics (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
822   }
823
824   if (smooth_p) 
825     {
826       glEnable (GL_LINE_SMOOTH);
827       glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);
828       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 
829       glEnable (GL_BLEND);
830     }
831
832   {
833     Bool spinx=False, spiny=False, spinz=False;
834     double spin_speed   = 1.0;
835     double wander_speed = 0.03;
836
837     char *s = do_spin;
838     while (*s)
839       {
840         if      (*s == 'x' || *s == 'X') spinx = True;
841         else if (*s == 'y' || *s == 'Y') spiny = True;
842         else if (*s == 'z' || *s == 'Z') spinz = True;
843         else
844           {
845             fprintf (stderr,
846          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
847                      progname, do_spin);
848             exit (1);
849           }
850         s++;
851       }
852
853     cc->rot = make_rotator (spinx ? spin_speed : 0,
854                             spinz ? spin_speed : 0,
855                             spiny ? spin_speed : 0,
856                             1.0,
857                             do_wander ? wander_speed : 0,
858                             (spinx && spiny && spinz));
859     cc->trackball = gltrackball_init ();
860   }
861
862   cc->tracer = -1;
863   cc->mesher = -1;
864
865   cc->resolution = res;
866
867   load_font (mi, "labelfont", &cc->font, &cc->font_list);
868
869   cc->dlist = glGenLists(1);
870   cc->dlist2 = glGenLists(1);
871
872   cc->m_max = 4; /* 9? */
873   {
874     unsigned int i;
875     for (i = 0; i < countof(cc->dm); i++)
876       cc->dm[i] = 1;  /* going up! */
877
878     /* Generate a few more times so we don't always start off with a sphere */
879     for (i = 0; i < 5; i++)
880       tweak_parameters (mi);
881   }
882
883   generate_spheremonics(mi);
884 }
885
886
887 Bool
888 spheremonics_handle_event (ModeInfo *mi, XEvent *event)
889 {
890   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
891
892   if (event->xany.type == ButtonPress &&
893       event->xbutton.button & Button1)
894     {
895       cc->button_down_p = True;
896       gltrackball_start (cc->trackball,
897                          event->xbutton.x, event->xbutton.y,
898                          MI_WIDTH (mi), MI_HEIGHT (mi));
899       return True;
900     }
901   else if (event->xany.type == ButtonRelease &&
902            event->xbutton.button & Button1)
903     {
904       cc->button_down_p = False;
905       return True;
906     }
907   else if (event->xany.type == MotionNotify &&
908            cc->button_down_p)
909     {
910       gltrackball_track (cc->trackball,
911                          event->xmotion.x, event->xmotion.y,
912                          MI_WIDTH (mi), MI_HEIGHT (mi));
913       return True;
914     }
915
916   return False;
917 }
918
919
920 void
921 draw_spheremonics (ModeInfo *mi)
922 {
923   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
924   Display *dpy = MI_DISPLAY(mi);
925   Window window = MI_WINDOW(mi);
926
927   if (!cc->glx_context)
928     return;
929
930   glShadeModel(GL_SMOOTH);
931
932   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
933
934   glPushMatrix ();
935
936   glScalef(1.1, 1.1, 1.1);
937
938   {
939     double x, y, z;
940     get_position (cc->rot, &x, &y, &z, !cc->button_down_p);
941     glTranslatef((x - 0.5) * 8,
942                  (y - 0.5) * 6,
943                  (z - 0.5) * 8);
944
945     gltrackball_rotate (cc->trackball);
946
947     get_rotation (cc->rot, &x, &y, &z, !cc->button_down_p);
948     glRotatef (x * 360, 1.0, 0.0, 0.0);
949     glRotatef (y * 360, 0.0, 1.0, 0.0);
950     glRotatef (z * 360, 0.0, 0.0, 1.0);
951   }
952
953   glScalef(7,7,7);
954
955   mi->polygon_count = 0;
956
957   glScalef (cc->scale, cc->scale, cc->scale);
958   glCallList (cc->dlist);
959   mi->polygon_count += cc->polys1;
960
961   if (cc->mesher >= 0 /* || mouse_p */)
962     {
963       glCallList (cc->dlist2);
964       mi->polygon_count += cc->polys2;
965       if (cc->mesher >= 0)
966         cc->mesher--;
967     }
968   do_tracer(mi);
969
970
971   if (cc->button_down_p)
972     {
973       char buf[200];
974       sprintf (buf,
975                ((cc->m[0]<10 && cc->m[1]<10 && cc->m[2]<10 && cc->m[3]<10 &&
976                  cc->m[4]<10 && cc->m[5]<10 && cc->m[6]<10 && cc->m[7]<10)
977                 ? "%d%d%d%d%d%d%d%d"
978                 : "%d %d %d %d %d %d %d %d"),
979                cc->m[0], cc->m[1], cc->m[2], cc->m[3],
980                cc->m[4], cc->m[5], cc->m[6], cc->m[7]);
981       draw_label (mi, buf);
982     }
983
984   if (!static_parms)
985     {
986       static int tick = 0;
987       if (tick++ >= duration && !cc->button_down_p)
988         {
989           generate_spheremonics(mi);
990           tick = 0;
991           cc->mesher = -1;  /* turn off the mesh when switching objects */
992         }
993     }
994
995   glPopMatrix();
996
997   if (mi->fps_p) do_fps (mi);
998   glFinish();
999
1000   glXSwapBuffers(dpy, window);
1001 }
1002
1003 #endif /* USE_GL */