From http://www.jwz.org/xscreensaver/xscreensaver-5.33.tar.gz
[xscreensaver] / hacks / glx / romanboy.c
1 /* romanboy --- Shows a 3d immersion of the real projective plane
2    that rotates in 3d or on which you can walk and that can deform
3    smoothly between the Roman surface and the Boy surface. */
4
5 #if 0
6 static const char sccsid[] = "@(#)romanboy.c  1.1 14/10/03 xlockmore";
7 #endif
8
9 /* Copyright (c) 2013-2014 Carsten Steger <carsten@mirsanmir.org>. */
10
11 /*
12  * Permission to use, copy, modify, and distribute this software and its
13  * documentation for any purpose and without fee is hereby granted,
14  * provided that the above copyright notice appear in all copies and that
15  * both that copyright notice and this permission notice appear in
16  * supporting documentation.
17  *
18  * This file is provided AS IS with no warranties of any kind.  The author
19  * shall have no liability with respect to the infringement of copyrights,
20  * trade secrets or any patents by this file or any part thereof.  In no
21  * event will the author be liable for any lost revenue or profits or
22  * other special, indirect and consequential damages.
23  *
24  * REVISION HISTORY:
25  * C. Steger - 14/10/03: Initial version
26  */
27
28 /*
29  * This program shows a 3d immersion of the real projective plane
30  * that smoothly deforms between the Roman surface and the Boy
31  * surface.  You can walk on the projective plane or turn in 3d.  The
32  * smooth deformation (homotopy) between these two famous immersions
33  * of the real projective plane was constructed by François Apéry.
34  *
35  * The real projective plane is a non-orientable surface.  To make
36  * this apparent, the two-sided color mode can be used.
37  * Alternatively, orientation markers (curling arrows) can be drawn as
38  * a texture map on the surface of the projective plane.  While
39  * walking on the projective plane, you will notice that the
40  * orientation of the curling arrows changes (which it must because
41  * the projective plane is non-orientable).
42  *
43  * The real projective plane is a model for the projective geometry in
44  * 2d space.  One point can be singled out as the origin.  A line can
45  * be singled out as the line at infinity, i.e., a line that lies at
46  * an infinite distance to the origin.  The line at infinity is
47  * topologically a circle.  Points on the line at infinity are also
48  * used to model directions in projective geometry.  The origin can be
49  * visualized in different manners.  When using distance colors, the
50  * origin is the point that is displayed as fully saturated red, which
51  * is easier to see as the center of the reddish area on the
52  * projective plane.  Alternatively, when using distance bands, the
53  * origin is the center of the only band that projects to a disk.
54  * When using direction bands, the origin is the point where all
55  * direction bands collapse to a point.  Finally, when orientation
56  * markers are being displayed, the origin the the point where all
57  * orientation markers are compressed to a point.  The line at
58  * infinity can also be visualized in different ways.  When using
59  * distance colors, the line at infinity is the line that is displayed
60  * as fully saturated magenta.  When two-sided colors are used, the
61  * line at infinity lies at the points where the red and green "sides"
62  * of the projective plane meet (of course, the real projective plane
63  * only has one side, so this is a design choice of the
64  * visualization).  Alternatively, when orientation markers are being
65  * displayed, the line at infinity is the place where the orientation
66  * markers change their orientation.
67  *
68  * Note that when the projective plane is displayed with bands, the
69  * orientation markers are placed in the middle of the bands.  For
70  * distance bands, the bands are chosen in such a way that the band at
71  * the origin is only half as wide as the remaining bands, which
72  * results in a disk being displayed at the origin that has the same
73  * diameter as the remaining bands.  This choice, however, also
74  * implies that the band at infinity is half as wide as the other
75  * bands.  Since the projective plane is attached to itself (in a
76  * complicated fashion) at the line at infinity, effectively the band
77  * at infinity is again as wide as the remaining bands.  However,
78  * since the orientation markers are displayed in the middle of the
79  * bands, this means that only one half of the orientation markers
80  * will be displayed twice at the line at infinity if distance bands
81  * are used.  If direction bands are used or if the projective plane
82  * is displayed as a solid surface, the orientation markers are
83  * displayed fully at the respective sides of the line at infinity.
84  *
85  * The immersed projective plane can be projected to the screen either
86  * perspectively or orthographically.  When using the walking modes,
87  * perspective projection to the screen will be used.
88  *
89  * There are three display modes for the projective plane: mesh
90  * (wireframe), solid, or transparent.  Furthermore, the appearance of
91  * the projective plane can be as a solid object or as a set of
92  * see-through bands.  The bands can be distance bands, i.e., bands
93  * that lie at increasing distances from the origin, or direction
94  * bands, i.e., bands that lie at increasing angles with respect to
95  * the origin.
96  *
97  * When the projective plane is displayed with direction bands, you
98  * will be able to see that each direction band (modulo the "pinching"
99  * at the origin) is a Moebius strip, which also shows that the
100  * projective plane is non-orientable.
101  *
102  * Finally, the colors with with the projective plane is drawn can be
103  * set to two-sided, distance, or direction.  In two-sided mode, the
104  * projective plane is drawn with red on one "side" and green on the
105  * "other side".  As described above, the projective plane only has
106  * one side, so the color jumps from red to green along the line at
107  * infinity.  This mode enables you to see that the projective plane
108  * is non-orientable.  In distance mode, the projective plane is
109  * displayed with fully saturated colors that depend on the distance
110  * of the points on the projective plane to the origin.  The origin is
111  * displayed in red, the line at infinity is displayed in magenta.  If
112  * the projective plane is displayed as distance bands, each band will
113  * be displayed with a different color.  In direction mode, the
114  * projective plane is displayed with fully saturated colors that
115  * depend on the angle of the points on the projective plane with
116  * respect to the origin.  Angles in opposite directions to the origin
117  * (e.g., 15 and 205 degrees) are displayed in the same color since
118  * they are projectively equivalent.  If the projective plane is
119  * displayed as direction bands, each band will be displayed with a
120  * different color.
121  *
122  * The rotation speed for each of the three coordinate axes around
123  * which the projective plane rotates can be chosen.
124  *
125  * Furthermore, in the walking mode the walking direction in the 2d
126  * base square of the projective plane and the walking speed can be
127  * chosen.  The walking direction is measured as an angle in degrees
128  * in the 2d square that forms the coordinate system of the surface of
129  * the projective plane.  A value of 0 or 180 means that the walk is
130  * along a circle at a randomly chosen distance from the origin
131  * (parallel to a distance band).  A value of 90 or 270 means that the
132  * walk is directly from the origin to the line at infinity and back
133  * (analogous to a direction band).  Any other value results in a
134  * curved path from the origin to the line at infinity and back.
135  *
136  * By default, the immersion of the real projective plane smoothly
137  * deforms between the Roman and Boy surfaces.  It is possible to
138  * choose the speed of the deformation.  Furthermore, it is possible
139  * to switch the deformation off.  It is also possible to determine
140  * the initial deformation of the immersion.  This is mostly useful if
141  * the deformation is switched off, in which case it will determine
142  * the appearance of the surface.
143  *
144  * As a final option, it is possible to display generalized versions
145  * of the immersion discussed above by specifying the order of the
146  * surface.  The default surface order of 3 results in the immersion
147  * of the real projective described above.  The surface order can be
148  * chosen between 2 and 9.  Odd surface orders result in generalized
149  * immersions of the real projective plane, while even numbers result
150  * in a immersion of a topological sphere (which is orientable).  The
151  * most interesting even case is a surface order of 2, which results
152  * in an immersion of the halfway model of Morin's sphere eversion (if
153  * the deformation is switched off).
154  *
155  * This program is inspired by François Apéry's book "Models of the
156  * Real Projective Plane", Vieweg, 1987.
157  */
158
159 #include "curlicue.h"
160
161 #ifndef M_PI
162 #define M_PI 3.14159265358979323846
163 #endif
164
165 #define DISP_WIREFRAME             0
166 #define DISP_SURFACE               1
167 #define DISP_TRANSPARENT           2
168 #define NUM_DISPLAY_MODES          3
169
170 #define APPEARANCE_SOLID           0
171 #define APPEARANCE_DISTANCE_BANDS  1
172 #define APPEARANCE_DIRECTION_BANDS 2
173 #define NUM_APPEARANCES            3
174
175 #define COLORS_TWOSIDED            0
176 #define COLORS_DISTANCE            1
177 #define COLORS_DIRECTION           2
178 #define NUM_COLORS                 3
179
180 #define VIEW_WALK                  0
181 #define VIEW_TURN                  1
182 #define NUM_VIEW_MODES             2
183
184 #define DISP_PERSPECTIVE           0
185 #define DISP_ORTHOGRAPHIC          1
186 #define NUM_DISP_MODES             2
187
188 #define DEF_DISPLAY_MODE           "random"
189 #define DEF_APPEARANCE             "random"
190 #define DEF_COLORS                 "random"
191 #define DEF_VIEW_MODE              "random"
192 #define DEF_MARKS                  "False"
193 #define DEF_DEFORM                 "True"
194 #define DEF_PROJECTION             "random"
195 #define DEF_SPEEDX                 "1.1"
196 #define DEF_SPEEDY                 "1.3"
197 #define DEF_SPEEDZ                 "1.5"
198 #define DEF_WALK_DIRECTION         "83.0"
199 #define DEF_WALK_SPEED             "20.0"
200 #define DEF_DEFORM_SPEED           "10.0"
201 #define DEF_INIT_DEFORM            "1000.0"
202 #define DEF_SURFACE_ORDER          "3"
203
204 #ifdef STANDALONE
205 # define DEFAULTS           "*delay:      10000 \n" \
206                             "*showFPS:    False \n" \
207
208 # define refresh_romanboy 0
209 # include "xlockmore.h"         /* from the xscreensaver distribution */
210 #else  /* !STANDALONE */
211 # include "xlock.h"             /* from the xlockmore distribution */
212 #endif /* !STANDALONE */
213
214 #ifdef USE_GL
215
216 #ifndef HAVE_COCOA
217 # include <X11/keysym.h>
218 #endif
219
220 #include "gltrackball.h"
221
222 #include <float.h>
223
224
225 #ifdef USE_MODULES
226 ModStruct romanboy_description =
227 {"romanboy", "init_romanboy", "draw_romanboy",
228  "release_romanboy", "draw_romanboy", "change_romanboy",
229  NULL, &romanboy_opts, 25000, 1, 1, 1, 1.0, 4, "",
230  "Rotate a 3d immersion of the real projective plane in 3d or walk on it",
231  0, NULL};
232
233 #endif
234
235
236 static char *mode;
237 static int display_mode;
238 static char *appear;
239 static int appearance;
240 static char *color_mode;
241 static int colors;
242 static char *view_mode;
243 static int view;
244 static Bool marks;
245 static Bool deform;
246 static char *proj;
247 static int projection;
248 static float speed_x;
249 static float speed_y;
250 static float speed_z;
251 static float walk_direction;
252 static float walk_speed;
253 static float deform_speed;
254 static float init_deform;
255 static int surface_order;
256
257
258 static XrmOptionDescRec opts[] =
259 {
260   {"-mode",                ".displayMode",   XrmoptionSepArg, 0 },
261   {"-wireframe",           ".displayMode",   XrmoptionNoArg,  "wireframe" },
262   {"-surface",             ".displayMode",   XrmoptionNoArg,  "surface" },
263   {"-transparent",         ".displayMode",   XrmoptionNoArg,  "transparent" },
264   {"-appearance",          ".appearance",    XrmoptionSepArg, 0 },
265   {"-solid",               ".appearance",    XrmoptionNoArg,  "solid" },
266   {"-distance-bands",      ".appearance",    XrmoptionNoArg,  "distance-bands" },
267   {"-direction-bands",     ".appearance",    XrmoptionNoArg,  "direction-bands" },
268   {"-colors",              ".colors",        XrmoptionSepArg, 0 },
269   {"-twosided-colors",     ".colors",        XrmoptionNoArg,  "two-sided" },
270   {"-distance-colors",     ".colors",        XrmoptionNoArg,  "distance" },
271   {"-direction-colors",    ".colors",        XrmoptionNoArg,  "direction" },
272   {"-view-mode",           ".viewMode",      XrmoptionSepArg, 0 },
273   {"-walk",                ".viewMode",      XrmoptionNoArg,  "walk" },
274   {"-turn",                ".viewMode",      XrmoptionNoArg,  "turn" },
275   {"-deform",              ".deform",        XrmoptionNoArg, "on"},
276   {"+deform",              ".deform",        XrmoptionNoArg, "off"},
277   {"-orientation-marks",   ".marks",         XrmoptionNoArg, "on"},
278   {"+orientation-marks",   ".marks",         XrmoptionNoArg, "off"},
279   {"-projection",          ".projection",    XrmoptionSepArg, 0 },
280   {"-perspective",         ".projection",    XrmoptionNoArg,  "perspective" },
281   {"-orthographic",        ".projection",    XrmoptionNoArg,  "orthographic" },
282   {"-speed-x",             ".speedx",        XrmoptionSepArg, 0 },
283   {"-speed-y",             ".speedy",        XrmoptionSepArg, 0 },
284   {"-speed-z",             ".speedz",        XrmoptionSepArg, 0 },
285   {"-walk-direction",      ".walkDirection", XrmoptionSepArg, 0 },
286   {"-walk-speed",          ".walkSpeed",     XrmoptionSepArg, 0 },
287   {"-deformation-speed",   ".deformSpeed",   XrmoptionSepArg, 0 },
288   {"-initial-deformation", ".initDeform",    XrmoptionSepArg, 0 },
289   {"-roman",               ".initDeform",    XrmoptionNoArg,  "0.0" },
290   {"-boy",                 ".initDeform",    XrmoptionNoArg,  "1000.0" },
291   {"-surface-order",       ".surfaceOrder",  XrmoptionSepArg, 0 },
292 };
293
294 static argtype vars[] =
295 {
296   { &mode,           "displayMode",   "DisplayMode",   DEF_DISPLAY_MODE,   t_String },
297   { &appear,         "appearance",    "Appearance",    DEF_APPEARANCE,     t_String },
298   { &color_mode,     "colors",        "Colors",        DEF_COLORS,         t_String },
299   { &view_mode,      "viewMode",      "ViewMode",      DEF_VIEW_MODE,      t_String },
300   { &deform,         "deform",        "Deform",        DEF_DEFORM,         t_Bool },
301   { &marks,          "marks",         "Marks",         DEF_MARKS,          t_Bool },
302   { &proj,           "projection",    "Projection",    DEF_PROJECTION,     t_String },
303   { &speed_x,        "speedx",        "Speedx",        DEF_SPEEDX,         t_Float},
304   { &speed_y,        "speedy",        "Speedy",        DEF_SPEEDY,         t_Float},
305   { &speed_z,        "speedz",        "Speedz",        DEF_SPEEDZ,         t_Float},
306   { &walk_direction, "walkDirection", "WalkDirection", DEF_WALK_DIRECTION, t_Float},
307   { &walk_speed,     "walkSpeed",     "WalkSpeed",     DEF_WALK_SPEED,     t_Float},
308   { &deform_speed,   "deformSpeed",   "DeformSpeed",   DEF_DEFORM_SPEED,   t_Float},
309   { &init_deform,    "initDeform",    "InitDeform",    DEF_INIT_DEFORM,    t_Float },
310   { &surface_order,  "surfaceOrder",  "SurfaceOrder",  DEF_SURFACE_ORDER,  t_Int }
311 };
312
313 ENTRYPOINT ModeSpecOpt romanboy_opts =
314 {sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, NULL};
315
316
317 /* Offset by which we walk above the projective plane */
318 #define DELTAY  0.01
319
320 /* Number of subdivisions of the projective plane */
321 #define NUMU 64
322 #define NUMV 128
323
324 /* Number of subdivisions per band */
325 #define NUMB 8
326
327
328 typedef struct {
329   GLint WindH, WindW;
330   GLXContext *glx_context;
331   /* 3D rotation angles */
332   float alpha, beta, delta;
333   /* Movement parameters */
334   float umove, vmove, dumove, dvmove;
335   int side, dir;
336   /* Deformation parameters */
337   float dd;
338   int defdir;
339   /* The type of the generalized Roman-Boy surface */
340   int g;
341   /* The viewing offset in 3d */
342   float offset3d[3];
343   /* The 3d coordinates of the projective plane and their derivatives */
344   float *pp;
345   float *pn;
346   /* The precomputed colors of the projective plane */
347   float *col;
348   /* The precomputed texture coordinates of the projective plane */
349   float *tex;
350   /* The "curlicue" texture */
351   GLuint tex_name;
352   /* Aspect ratio of the current window */
353   float aspect;
354   /* Trackball states */
355   trackball_state *trackball;
356   Bool button_pressed;
357   /* A random factor to modify the rotation speeds */
358   float speed_scale;
359 } romanboystruct;
360
361 static romanboystruct *romanboy = (romanboystruct *) NULL;
362
363
364 /* Add a rotation around the x-axis to the matrix m. */
365 static void rotatex(float m[3][3], float phi)
366 {
367   float c, s, u, v;
368   int i;
369
370   phi *= M_PI/180.0;
371   c = cos(phi);
372   s = sin(phi);
373   for (i=0; i<3; i++)
374   {
375     u = m[i][1];
376     v = m[i][2];
377     m[i][1] = c*u+s*v;
378     m[i][2] = -s*u+c*v;
379   }
380 }
381
382
383 /* Add a rotation around the y-axis to the matrix m. */
384 static void rotatey(float m[3][3], float phi)
385 {
386   float c, s, u, v;
387   int i;
388
389   phi *= M_PI/180.0;
390   c = cos(phi);
391   s = sin(phi);
392   for (i=0; i<3; i++)
393   {
394     u = m[i][0];
395     v = m[i][2];
396     m[i][0] = c*u-s*v;
397     m[i][2] = s*u+c*v;
398   }
399 }
400
401
402 /* Add a rotation around the z-axis to the matrix m. */
403 static void rotatez(float m[3][3], float phi)
404 {
405   float c, s, u, v;
406   int i;
407
408   phi *= M_PI/180.0;
409   c = cos(phi);
410   s = sin(phi);
411   for (i=0; i<3; i++)
412   {
413     u = m[i][0];
414     v = m[i][1];
415     m[i][0] = c*u+s*v;
416     m[i][1] = -s*u+c*v;
417   }
418 }
419
420
421 /* Compute the rotation matrix m from the rotation angles. */
422 static void rotateall(float al, float be, float de, float m[3][3])
423 {
424   int i, j;
425
426   for (i=0; i<3; i++)
427     for (j=0; j<3; j++)
428       m[i][j] = (i==j);
429   rotatex(m,al);
430   rotatey(m,be);
431   rotatez(m,de);
432 }
433
434
435 /* Multiply two rotation matrices: o=m*n. */
436 static void mult_rotmat(float m[3][3], float n[3][3], float o[3][3])
437 {
438   int i, j, k;
439
440   for (i=0; i<3; i++)
441   {
442     for (j=0; j<3; j++)
443     {
444       o[i][j] = 0.0;
445       for (k=0; k<3; k++)
446         o[i][j] += m[i][k]*n[k][j];
447     }
448   }
449 }
450
451
452 /* Compute a 3D rotation matrix from a unit quaternion. */
453 static void quat_to_rotmat(float p[4], float m[3][3])
454 {
455   double al, be, de;
456   double r00, r01, r02, r12, r22;
457
458   r00 = 1.0-2.0*(p[1]*p[1]+p[2]*p[2]);
459   r01 = 2.0*(p[0]*p[1]+p[2]*p[3]);
460   r02 = 2.0*(p[2]*p[0]-p[1]*p[3]);
461   r12 = 2.0*(p[1]*p[2]+p[0]*p[3]);
462   r22 = 1.0-2.0*(p[1]*p[1]+p[0]*p[0]);
463
464   al = atan2(-r12,r22)*180.0/M_PI;
465   be = atan2(r02,sqrt(r00*r00+r01*r01))*180.0/M_PI;
466   de = atan2(-r01,r00)*180.0/M_PI;
467
468   rotateall(al,be,de,m);
469 }
470
471
472 /* Compute a fully saturated and bright color based on an angle. */
473 static void color(double angle, float col[4])
474 {
475   int s;
476   double t;
477
478   if (colors == COLORS_TWOSIDED)
479     return;
480
481   if (angle >= 0.0)
482     angle = fmod(angle,2.0*M_PI);
483   else
484     angle = fmod(angle,-2.0*M_PI);
485   s = floor(angle/(M_PI/3));
486   t = angle/(M_PI/3)-s;
487   if (s >= 6)
488     s = 0;
489   switch (s)
490   {
491     case 0:
492       col[0] = 1.0;
493       col[1] = t;
494       col[2] = 0.0;
495       break;
496     case 1:
497       col[0] = 1.0-t;
498       col[1] = 1.0;
499       col[2] = 0.0;
500       break;
501     case 2:
502       col[0] = 0.0;
503       col[1] = 1.0;
504       col[2] = t;
505       break;
506     case 3:
507       col[0] = 0.0;
508       col[1] = 1.0-t;
509       col[2] = 1.0;
510       break;
511     case 4:
512       col[0] = t;
513       col[1] = 0.0;
514       col[2] = 1.0;
515       break;
516     case 5:
517       col[0] = 1.0;
518       col[1] = 0.0;
519       col[2] = 1.0-t;
520       break;
521   }
522   if (display_mode == DISP_TRANSPARENT)
523     col[3] = 0.7;
524   else
525     col[3] = 1.0;
526 }
527
528
529 /* Set up the projective plane colors and texture. */
530 static void setup_roman_boy_color_texture(ModeInfo *mi, double umin,
531                                           double umax, double vmin,
532                                           double vmax, int numu, int numv)
533 {
534   int i, j, k, g;
535   double u, v, ur, vr;
536   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
537
538   g = pp->g;
539   ur = umax-umin;
540   vr = vmax-vmin;
541   for (i=0; i<=numv; i++)
542   {
543     for (j=0; j<=numu; j++)
544     {
545       k = i*(numu+1)+j;
546       if (appearance != APPEARANCE_DIRECTION_BANDS)
547         u = -ur*j/numu+umin;
548       else
549         u = ur*j/numu+umin;
550       v = vr*i/numv+vmin;
551       if (colors == COLORS_DIRECTION)
552         color(2.0*M_PI-fmod(2.0*u,2.0*M_PI),&pp->col[4*k]);
553       else /* colors == COLORS_DISTANCE */
554         color(v*(5.0/6.0),&pp->col[4*k]);
555       pp->tex[2*k+0] = -16*g*u/(2.0*M_PI);
556       if (appearance == APPEARANCE_DISTANCE_BANDS)
557         pp->tex[2*k+1] = 32*v/(2.0*M_PI)-0.5;
558       else
559         pp->tex[2*k+1] = 32*v/(2.0*M_PI);
560     }
561   }
562 }
563
564
565 /* Draw a 3d immersion of the projective plane. */
566 static int roman_boy(ModeInfo *mi, double umin, double umax,
567                      double vmin, double vmax, int numu, int numv)
568 {
569   int polys = 0;
570   static const GLfloat mat_diff_red[]         = { 1.0, 0.0, 0.0, 1.0 };
571   static const GLfloat mat_diff_green[]       = { 0.0, 1.0, 0.0, 1.0 };
572   static const GLfloat mat_diff_trans_red[]   = { 1.0, 0.0, 0.0, 0.7 };
573   static const GLfloat mat_diff_trans_green[] = { 0.0, 1.0, 0.0, 0.7 };
574   float p[3], pu[3], pv[3], pm[3], n[3], b[3], mat[3][3];
575   int i, j, k, l, m, o, g;
576   double u, v, ur, vr, oz;
577   double xx[3], xxu[3], xxv[3];
578   double r, s, t;
579   double d, dd, radius;
580   double cu, su, cgu, sgu, cgm1u, sgm1u, cv, c2v, s2v, cv2;
581   double sqrt2og, h1m1og, gm1, nomx, nomy, nomux, nomuy, nomvx, nomvy;
582   double den, den2, denu, denv;
583   float qu[4], r1[3][3], r2[3][3];
584   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
585
586   g = pp->g;
587   dd = pp->dd;
588   d = ((6.0*dd-15.0)*dd+10.0)*dd*dd*dd;
589   r = 1.0+d*d*(1.0/2.0+d*d*(1.0/6.0+d*d*(1.0/3.0)));
590   radius = 1.0/r;
591   oz = 0.5*r;
592   if (view == VIEW_WALK)
593   {
594     u = pp->umove;
595     v = pp->vmove;
596     if (g & 1)
597       v = 0.5*M_PI-0.25*v;
598     else
599       v = 0.5*M_PI-0.5*v;
600     sqrt2og = M_SQRT2/g;
601     h1m1og = 0.5*(1.0-1.0/g);
602     gm1 = g-1.0;
603     cu = cos(u);
604     su = sin(u);
605     cgu = cos(g*u);
606     sgu = sin(g*u);
607     cgm1u = cos(gm1*u);
608     sgm1u = sin(gm1*u);
609     cv = cos(v);
610     c2v = cos(2.0*v);
611     s2v = sin(2.0*v);
612     cv2 = cv*cv;
613     nomx = sqrt2og*cv2*cgm1u+h1m1og*s2v*cu;
614     nomy = sqrt2og*cv2*sgm1u-h1m1og*s2v*su;
615     nomux = -sqrt2og*cv2*gm1*sgm1u-h1m1og*s2v*su;
616     nomuy = sqrt2og*cv2*gm1*cgm1u-h1m1og*s2v*cu;
617     nomvx = -sqrt2og*s2v*cgm1u+2.0*h1m1og*c2v*cu;
618     nomvy = -sqrt2og*s2v*sgm1u-2.0*h1m1og*c2v*su;
619     den = 1.0/(1.0-0.5*M_SQRT2*d*s2v*sgu);
620     den2 = den*den;
621     denu = 0.5*M_SQRT2*d*g*cgu*s2v;
622     denv = M_SQRT2*d*sgu*c2v;
623     xx[0] = nomx*den;
624     xx[1] = nomy*den;
625     xx[2] = cv2*den-oz;
626     /* Avoid degenerate tangential plane basis vectors. */
627     if (0.5*M_PI-fabs(v) < FLT_EPSILON)
628     {
629       if (0.5*M_PI-v < FLT_EPSILON)
630         v = 0.5*M_PI-FLT_EPSILON;
631       else
632         v = -0.5*M_PI+FLT_EPSILON;
633       cv = cos(v);
634       c2v = cos(2.0*v);
635       s2v = sin(2.0*v);
636       cv2 = cv*cv;
637       nomx = sqrt2og*cv2*cgm1u+h1m1og*s2v*cu;
638       nomy = sqrt2og*cv2*sgm1u-h1m1og*s2v*su;
639       nomux = -sqrt2og*cv2*gm1*sgm1u-h1m1og*s2v*su;
640       nomuy = sqrt2og*cv2*gm1*cgm1u-h1m1og*s2v*cu;
641       nomvx = -sqrt2og*s2v*cgm1u+2.0*h1m1og*c2v*cu;
642       nomvy = -sqrt2og*s2v*sgm1u-2.0*h1m1og*c2v*su;
643       den = 1.0/(1.0-0.5*M_SQRT2*d*s2v*sgu);
644       den2 = den*den;
645       denu = 0.5*M_SQRT2*d*g*cgu*s2v;
646       denv = M_SQRT2*d*sgu*c2v;
647     }
648     xxu[0] = nomux*den+nomx*denu*den2;
649     xxu[1] = nomuy*den+nomy*denu*den2;
650     xxu[2] = cv2*denu*den2;
651     xxv[0] = nomvx*den+nomx*denv*den2;
652     xxv[1] = nomvy*den+nomy*denv*den2;
653     xxv[2] = -s2v*den+cv2*denv*den2;
654     for (l=0; l<3; l++)
655     {
656       p[l] = xx[l]*radius;
657       pu[l] = xxu[l]*radius;
658       pv[l] = xxv[l]*radius;
659     }
660     n[0] = pu[1]*pv[2]-pu[2]*pv[1];
661     n[1] = pu[2]*pv[0]-pu[0]*pv[2];
662     n[2] = pu[0]*pv[1]-pu[1]*pv[0];
663     t = 1.0/(pp->side*4.0*sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]));
664     n[0] *= t;
665     n[1] *= t;
666     n[2] *= t;
667     pm[0] = pu[0]*pp->dumove-pv[0]*0.25*pp->dvmove;
668     pm[1] = pu[1]*pp->dumove-pv[1]*0.25*pp->dvmove;
669     pm[2] = pu[2]*pp->dumove-pv[2]*0.25*pp->dvmove;
670     t = 1.0/(4.0*sqrt(pm[0]*pm[0]+pm[1]*pm[1]+pm[2]*pm[2]));
671     pm[0] *= t;
672     pm[1] *= t;
673     pm[2] *= t;
674     b[0] = n[1]*pm[2]-n[2]*pm[1];
675     b[1] = n[2]*pm[0]-n[0]*pm[2];
676     b[2] = n[0]*pm[1]-n[1]*pm[0];
677     t = 1.0/(4.0*sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]));
678     b[0] *= t;
679     b[1] *= t;
680     b[2] *= t;
681
682     /* Compute alpha, beta, gamma from the three basis vectors.
683            |  -b[0]  -b[1]  -b[2] |
684        m = |   n[0]   n[1]   n[2] |
685            | -pm[0] -pm[1] -pm[2] |
686     */
687     pp->alpha = atan2(-n[2],-pm[2])*180/M_PI;
688     pp->beta = atan2(-b[2],sqrt(b[0]*b[0]+b[1]*b[1]))*180/M_PI;
689     pp->delta = atan2(b[1],-b[0])*180/M_PI;
690
691     /* Compute the rotation that rotates the projective plane in 3D. */
692     rotateall(pp->alpha,pp->beta,pp->delta,mat);
693
694     u = pp->umove;
695     v = pp->vmove;
696     if (g & 1)
697       v = 0.5*M_PI-0.25*v;
698     else
699       v = 0.5*M_PI-0.5*v;
700     sqrt2og = M_SQRT2/g;
701     h1m1og = 0.5*(1.0-1.0/g);
702     gm1 = g-1.0;
703     cu = cos(u);
704     su = sin(u);
705     sgu = sin(g*u);
706     cgm1u = cos(gm1*u);
707     sgm1u = sin(gm1*u);
708     cv = cos(v);
709     s2v = sin(2.0*v);
710     cv2 = cv*cv;
711     nomx = sqrt2og*cv2*cgm1u+h1m1og*s2v*cu;
712     nomy = sqrt2og*cv2*sgm1u-h1m1og*s2v*su;
713     den = 1.0/(1.0-0.5*M_SQRT2*d*s2v*sgu);
714     xx[0] = nomx*den;
715     xx[1] = nomy*den;
716     xx[2] = cv2*den-oz;
717     for (l=0; l<3; l++)
718     {
719       r = 0.0;
720       for (m=0; m<3; m++)
721         r += mat[l][m]*xx[m];
722       p[l] = r*radius;
723     }
724
725     pp->offset3d[0] = -p[0];
726     pp->offset3d[1] = -p[1]-DELTAY;
727     pp->offset3d[2] = -p[2];
728   }
729   else
730   {
731     /* Compute the rotation that rotates the projective plane in 3D,
732        including the trackball rotations. */
733     rotateall(pp->alpha,pp->beta,pp->delta,r1);
734
735     gltrackball_get_quaternion(pp->trackball,qu);
736     quat_to_rotmat(qu,r2);
737
738     mult_rotmat(r2,r1,mat);
739   }
740
741   if (colors == COLORS_TWOSIDED)
742   {
743     glColor3fv(mat_diff_red);
744     if (display_mode == DISP_TRANSPARENT)
745     {
746       glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,mat_diff_trans_red);
747       glMaterialfv(GL_BACK,GL_AMBIENT_AND_DIFFUSE,mat_diff_trans_green);
748     }
749     else
750     {
751       glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,mat_diff_red);
752       glMaterialfv(GL_BACK,GL_AMBIENT_AND_DIFFUSE,mat_diff_green);
753     }
754   }
755   glBindTexture(GL_TEXTURE_2D,pp->tex_name);
756
757   ur = umax-umin;
758   vr = vmax-vmin;
759
760   /* Set up the projective plane coordinates and normals. */
761   if (appearance != APPEARANCE_DIRECTION_BANDS)
762   {
763     for (i=0; i<=numv; i++)
764     {
765       if (appearance == APPEARANCE_DISTANCE_BANDS &&
766           ((i & (NUMB-1)) >= NUMB/4+1) && ((i & (NUMB-1)) < 3*NUMB/4))
767         continue;
768       for (j=0; j<=numu; j++)
769       {
770         l = i;
771         m = j;
772         o = i*(numu+1)+j;
773         u = ur*j/numu+umin;
774         v = vr*i/numv+vmin;
775         if (g & 1)
776           v = 0.5*M_PI-0.25*v;
777         else
778           v = 0.5*M_PI-0.5*v;
779         sqrt2og = M_SQRT2/g;
780         h1m1og = 0.5*(1.0-1.0/g);
781         gm1 = g-1.0;
782         cu = cos(u);
783         su = sin(u);
784         cgu = cos(g*u);
785         sgu = sin(g*u);
786         cgm1u = cos(gm1*u);
787         sgm1u = sin(gm1*u);
788         cv = cos(v);
789         c2v = cos(2.0*v);
790         s2v = sin(2.0*v);
791         cv2 = cv*cv;
792         nomx = sqrt2og*cv2*cgm1u+h1m1og*s2v*cu;
793         nomy = sqrt2og*cv2*sgm1u-h1m1og*s2v*su;
794         nomux = -sqrt2og*cv2*gm1*sgm1u-h1m1og*s2v*su;
795         nomuy = sqrt2og*cv2*gm1*cgm1u-h1m1og*s2v*cu;
796         nomvx = -sqrt2og*s2v*cgm1u+2.0*h1m1og*c2v*cu;
797         nomvy = -sqrt2og*s2v*sgm1u-2.0*h1m1og*c2v*su;
798         den = 1.0/(1.0-0.5*M_SQRT2*d*s2v*sgu);
799         den2 = den*den;
800         denu = 0.5*M_SQRT2*d*g*cgu*s2v;
801         denv = M_SQRT2*d*sgu*c2v;
802         xx[0] = nomx*den;
803         xx[1] = nomy*den;
804         xx[2] = cv2*den-oz;
805         /* Avoid degenerate tangential plane basis vectors. */
806         if (0.5*M_PI-fabs(v) < FLT_EPSILON)
807         {
808           if (0.5*M_PI-v < FLT_EPSILON)
809             v = 0.5*M_PI-FLT_EPSILON;
810           else
811             v = -0.5*M_PI+FLT_EPSILON;
812           cv = cos(v);
813           c2v = cos(2.0*v);
814           s2v = sin(2.0*v);
815           cv2 = cv*cv;
816           nomx = sqrt2og*cv2*cgm1u+h1m1og*s2v*cu;
817           nomy = sqrt2og*cv2*sgm1u-h1m1og*s2v*su;
818           nomux = -sqrt2og*cv2*gm1*sgm1u-h1m1og*s2v*su;
819           nomuy = sqrt2og*cv2*gm1*cgm1u-h1m1og*s2v*cu;
820           nomvx = -sqrt2og*s2v*cgm1u+2.0*h1m1og*c2v*cu;
821           nomvy = -sqrt2og*s2v*sgm1u-2.0*h1m1og*c2v*su;
822           den = 1.0/(1.0-0.5*M_SQRT2*d*s2v*sgu);
823           den2 = den*den;
824           denu = 0.5*M_SQRT2*d*g*cgu*s2v;
825           denv = M_SQRT2*d*sgu*c2v;
826         }
827         xxu[0] = nomux*den+nomx*denu*den2;
828         xxu[1] = nomuy*den+nomy*denu*den2;
829         xxu[2] = cv2*denu*den2;
830         xxv[0] = nomvx*den+nomx*denv*den2;
831         xxv[1] = nomvy*den+nomy*denv*den2;
832         xxv[2] = -s2v*den+cv2*denv*den2;
833         for (l=0; l<3; l++)
834         {
835           r = 0.0;
836           s = 0.0;
837           t = 0.0;
838           for (m=0; m<3; m++)
839           {
840             r += mat[l][m]*xx[m];
841             s += mat[l][m]*xxu[m];
842             t += mat[l][m]*xxv[m];
843           }
844           p[l] = r*radius+pp->offset3d[l];
845           pu[l] = s*radius;
846           pv[l] = t*radius;
847         }
848         n[0] = pu[1]*pv[2]-pu[2]*pv[1];
849         n[1] = pu[2]*pv[0]-pu[0]*pv[2];
850         n[2] = pu[0]*pv[1]-pu[1]*pv[0];
851         t = 1.0/sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);
852         n[0] *= t;
853         n[1] *= t;
854         n[2] *= t;
855         pp->pp[3*o+0] = p[0];
856         pp->pp[3*o+1] = p[1];
857         pp->pp[3*o+2] = p[2];
858         pp->pn[3*o+0] = n[0];
859         pp->pn[3*o+1] = n[1];
860         pp->pn[3*o+2] = n[2];
861       }
862     }
863   }
864   else /* appearance == APPEARANCE_DIRECTION_BANDS */
865   {
866     for (j=0; j<=numu; j++)
867     {
868       if ((j & (NUMB-1)) >= NUMB/2+1)
869         continue;
870       for (i=0; i<=numv; i++)
871       {
872         o = i*(numu+1)+j;
873         u = -ur*j/numu+umin;
874         v = vr*i/numv+vmin;
875         if (g & 1)
876           v = 0.5*M_PI-0.25*v;
877         else
878           v = 0.5*M_PI-0.5*v;
879         sqrt2og = M_SQRT2/g;
880         h1m1og = 0.5*(1.0-1.0/g);
881         gm1 = g-1.0;
882         cu = cos(u);
883         su = sin(u);
884         cgu = cos(g*u);
885         sgu = sin(g*u);
886         cgm1u = cos(gm1*u);
887         sgm1u = sin(gm1*u);
888         cv = cos(v);
889         c2v = cos(2.0*v);
890         s2v = sin(2.0*v);
891         cv2 = cv*cv;
892         nomx = sqrt2og*cv2*cgm1u+h1m1og*s2v*cu;
893         nomy = sqrt2og*cv2*sgm1u-h1m1og*s2v*su;
894         nomux = -sqrt2og*cv2*gm1*sgm1u-h1m1og*s2v*su;
895         nomuy = sqrt2og*cv2*gm1*cgm1u-h1m1og*s2v*cu;
896         nomvx = -sqrt2og*s2v*cgm1u+2.0*h1m1og*c2v*cu;
897         nomvy = -sqrt2og*s2v*sgm1u-2.0*h1m1og*c2v*su;
898         den = 1.0/(1.0-0.5*M_SQRT2*d*s2v*sgu);
899         den2 = den*den;
900         denu = 0.5*M_SQRT2*d*g*cgu*s2v;
901         denv = M_SQRT2*d*sgu*c2v;
902         xx[0] = nomx*den;
903         xx[1] = nomy*den;
904         xx[2] = cv2*den-oz;
905         /* Avoid degenerate tangential plane basis vectors. */
906         if (0.5*M_PI-fabs(v) < FLT_EPSILON)
907         {
908           if (0.5*M_PI-v < FLT_EPSILON)
909             v = 0.5*M_PI-FLT_EPSILON;
910           else
911             v = -0.5*M_PI+FLT_EPSILON;
912           cv = cos(v);
913           c2v = cos(2.0*v);
914           s2v = sin(2.0*v);
915           cv2 = cv*cv;
916           nomx = sqrt2og*cv2*cgm1u+h1m1og*s2v*cu;
917           nomy = sqrt2og*cv2*sgm1u-h1m1og*s2v*su;
918           nomux = -sqrt2og*cv2*gm1*sgm1u-h1m1og*s2v*su;
919           nomuy = sqrt2og*cv2*gm1*cgm1u-h1m1og*s2v*cu;
920           nomvx = -sqrt2og*s2v*cgm1u+2.0*h1m1og*c2v*cu;
921           nomvy = -sqrt2og*s2v*sgm1u-2.0*h1m1og*c2v*su;
922           den = 1.0/(1.0-0.5*M_SQRT2*d*s2v*sgu);
923           den2 = den*den;
924           denu = 0.5*M_SQRT2*d*g*cgu*s2v;
925           denv = M_SQRT2*d*sgu*c2v;
926         }
927         xxu[0] = nomux*den+nomx*denu*den2;
928         xxu[1] = nomuy*den+nomy*denu*den2;
929         xxu[2] = cv2*denu*den2;
930         xxv[0] = nomvx*den+nomx*denv*den2;
931         xxv[1] = nomvy*den+nomy*denv*den2;
932         xxv[2] = -s2v*den+cv2*denv*den2;
933         for (l=0; l<3; l++)
934         {
935           r = 0.0;
936           s = 0.0;
937           t = 0.0;
938           for (m=0; m<3; m++)
939           {
940             r += mat[l][m]*xx[m];
941             s += mat[l][m]*xxu[m];
942             t += mat[l][m]*xxv[m];
943           }
944           p[l] = r*radius+pp->offset3d[l];
945           pu[l] = s*radius;
946           pv[l] = t*radius;
947         }
948         n[0] = pu[1]*pv[2]-pu[2]*pv[1];
949         n[1] = pu[2]*pv[0]-pu[0]*pv[2];
950         n[2] = pu[0]*pv[1]-pu[1]*pv[0];
951         t = 1.0/sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);
952         n[0] *= t;
953         n[1] *= t;
954         n[2] *= t;
955         pp->pp[3*o+0] = p[0];
956         pp->pp[3*o+1] = p[1];
957         pp->pp[3*o+2] = p[2];
958         pp->pn[3*o+0] = n[0];
959         pp->pn[3*o+1] = n[1];
960         pp->pn[3*o+2] = n[2];
961       }
962     }
963   }
964
965   if (appearance != APPEARANCE_DIRECTION_BANDS)
966   {
967     for (i=0; i<numv; i++)
968     {
969       if (appearance == APPEARANCE_DISTANCE_BANDS &&
970           ((i & (NUMB-1)) >= NUMB/4) && ((i & (NUMB-1)) < 3*NUMB/4))
971         continue;
972       if (display_mode == DISP_WIREFRAME)
973         glBegin(GL_QUAD_STRIP);
974       else
975         glBegin(GL_TRIANGLE_STRIP);
976       for (j=0; j<=numu; j++)
977       {
978         for (k=0; k<=1; k++)
979         {
980           l = (i+k);
981           m = j;
982           o = l*(numu+1)+m;
983           glTexCoord2fv(&pp->tex[2*o]);
984           if (colors != COLORS_TWOSIDED)
985           {
986             glColor3fv(&pp->col[4*o]);
987             glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,
988                          &pp->col[4*o]);
989           }
990           glNormal3fv(&pp->pn[3*o]);
991           glVertex3fv(&pp->pp[3*o]);
992           polys++;
993         }
994       }
995       glEnd();
996     }
997   }
998   else /* appearance == APPEARANCE_DIRECTION_BANDS */
999   {
1000     for (j=0; j<numu; j++)
1001     {
1002       if ((j & (NUMB-1)) >= NUMB/2)
1003         continue;
1004       if (display_mode == DISP_WIREFRAME)
1005         glBegin(GL_QUAD_STRIP);
1006       else
1007         glBegin(GL_TRIANGLE_STRIP);
1008       for (i=0; i<=numv; i++)
1009       {
1010         for (k=0; k<=1; k++)
1011         {
1012           l = i;
1013           m = (j+k);
1014           o = l*(numu+1)+m;
1015           glTexCoord2fv(&pp->tex[2*o]);
1016           if (colors != COLORS_TWOSIDED)
1017           {
1018             glColor3fv(&pp->col[4*o]);
1019             glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,
1020                          &pp->col[4*o]);
1021           }
1022           glNormal3fv(&pp->pn[3*o]);
1023           glVertex3fv(&pp->pp[3*o]);
1024           polys++;
1025         }
1026       }
1027       glEnd();
1028     }
1029   }
1030
1031   polys /= 2;
1032   return polys;
1033 }
1034
1035
1036 /* Generate a texture image that shows the orientation reversal. */
1037 static void gen_texture(ModeInfo *mi)
1038 {
1039   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
1040
1041   glGenTextures(1,&pp->tex_name);
1042   glBindTexture(GL_TEXTURE_2D,pp->tex_name);
1043   glPixelStorei(GL_UNPACK_ALIGNMENT,1);
1044   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
1045   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
1046   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
1047   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
1048   glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
1049   glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,TEX_DIMENSION,TEX_DIMENSION,0,
1050                GL_LUMINANCE,GL_UNSIGNED_BYTE,texture);
1051 }
1052
1053
1054 static void init(ModeInfo *mi)
1055 {
1056   static const GLfloat light_ambient[]  = { 0.0, 0.0, 0.0, 1.0 };
1057   static const GLfloat light_diffuse[]  = { 1.0, 1.0, 1.0, 1.0 };
1058   static const GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
1059   static const GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
1060   static const GLfloat mat_specular[]   = { 1.0, 1.0, 1.0, 1.0 };
1061   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
1062
1063   if (deform_speed == 0.0)
1064     deform_speed = 10.0;
1065
1066   if (init_deform < 0.0)
1067     init_deform = 0.0;
1068   if (init_deform > 1000.0)
1069     init_deform = 1000.0;
1070
1071   if (walk_speed == 0.0)
1072     walk_speed = 20.0;
1073
1074   if (view == VIEW_TURN)
1075   {
1076     pp->alpha = frand(360.0);
1077     pp->beta = frand(360.0);
1078     pp->delta = frand(360.0);
1079   }
1080   else
1081   {
1082     pp->alpha = 0.0;
1083     pp->beta = 0.0;
1084     pp->delta = 0.0;
1085   }
1086   pp->umove = frand(2.0*M_PI);
1087   pp->vmove = frand(2.0*M_PI);
1088   pp->dumove = 0.0;
1089   pp->dvmove = 0.0;
1090   pp->side = 1;
1091   if (sin(walk_direction*M_PI/180.0) >= 0.0)
1092     pp->dir = 1;
1093   else
1094     pp->dir = -1;
1095
1096   pp->dd = init_deform*0.001;
1097   pp->defdir = -1;
1098
1099   pp->offset3d[0] = 0.0;
1100   pp->offset3d[1] = 0.0;
1101   pp->offset3d[2] = -1.8;
1102
1103   gen_texture(mi);
1104   setup_roman_boy_color_texture(mi,0.0,2.0*M_PI,0.0,2.0*M_PI,pp->g*NUMU,NUMV);
1105
1106   if (marks)
1107     glEnable(GL_TEXTURE_2D);
1108   else
1109     glDisable(GL_TEXTURE_2D);
1110
1111   glMatrixMode(GL_PROJECTION);
1112   glLoadIdentity();
1113   if (projection == DISP_PERSPECTIVE || view == VIEW_WALK)
1114   {
1115     if (view == VIEW_WALK)
1116       gluPerspective(60.0,1.0,0.01,10.0);
1117     else
1118       gluPerspective(60.0,1.0,0.1,10.0);
1119   }
1120   else
1121   {
1122     glOrtho(-1.0,1.0,-1.0,1.0,0.1,10.0);
1123   }
1124   glMatrixMode(GL_MODELVIEW);
1125   glLoadIdentity();
1126
1127 # ifdef HAVE_JWZGLES /* #### glPolygonMode other than GL_FILL unimplemented */
1128   if (display_mode == DISP_WIREFRAME)
1129     display_mode = DISP_SURFACE;
1130 # endif
1131
1132   if (display_mode == DISP_SURFACE)
1133   {
1134     glEnable(GL_DEPTH_TEST);
1135     glDepthFunc(GL_LESS);
1136     glShadeModel(GL_SMOOTH);
1137     glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
1138     glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
1139     glEnable(GL_LIGHTING);
1140     glEnable(GL_LIGHT0);
1141     glLightfv(GL_LIGHT0,GL_AMBIENT,light_ambient);
1142     glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);
1143     glLightfv(GL_LIGHT0,GL_SPECULAR,light_specular);
1144     glLightfv(GL_LIGHT0,GL_POSITION,light_position);
1145     glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,mat_specular);
1146     glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,50.0);
1147     glDepthMask(GL_TRUE);
1148     glDisable(GL_BLEND);
1149   }
1150   else if (display_mode == DISP_TRANSPARENT)
1151   {
1152     glDisable(GL_DEPTH_TEST);
1153     glShadeModel(GL_SMOOTH);
1154     glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
1155     glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
1156     glEnable(GL_LIGHTING);
1157     glEnable(GL_LIGHT0);
1158     glLightfv(GL_LIGHT0,GL_AMBIENT,light_ambient);
1159     glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);
1160     glLightfv(GL_LIGHT0,GL_SPECULAR,light_specular);
1161     glLightfv(GL_LIGHT0,GL_POSITION,light_position);
1162     glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,mat_specular);
1163     glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,50.0);
1164     glDepthMask(GL_FALSE);
1165     glEnable(GL_BLEND);
1166     glBlendFunc(GL_SRC_ALPHA,GL_ONE);
1167   }
1168   else  /* display_mode == DISP_WIREFRAME */
1169   {
1170     glDisable(GL_DEPTH_TEST);
1171     glShadeModel(GL_FLAT);
1172     glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
1173     glDisable(GL_LIGHTING);
1174     glDisable(GL_LIGHT0);
1175     glDisable(GL_BLEND);
1176   }
1177 }
1178
1179
1180 /* Redisplay the Klein bottle. */
1181 static void display_romanboy(ModeInfo *mi)
1182 {
1183   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
1184
1185   if (!pp->button_pressed)
1186   {
1187     if (deform)
1188     {
1189       pp->dd += pp->defdir*deform_speed*0.001;
1190       if (pp->dd < 0.0)
1191       {
1192         pp->dd = -pp->dd;
1193         pp->defdir = -pp->defdir;
1194       }
1195       if (pp->dd > 1.0)
1196       {
1197         pp->dd = 2.0-pp->dd;
1198         pp->defdir = -pp->defdir;
1199       }
1200     }
1201     if (view == VIEW_TURN)
1202     {
1203       pp->alpha += speed_x * pp->speed_scale;
1204       if (pp->alpha >= 360.0)
1205         pp->alpha -= 360.0;
1206       pp->beta += speed_y * pp->speed_scale;
1207       if (pp->beta >= 360.0)
1208         pp->beta -= 360.0;
1209       pp->delta += speed_z * pp->speed_scale;
1210       if (pp->delta >= 360.0)
1211         pp->delta -= 360.0;
1212     }
1213     if (view == VIEW_WALK)
1214     {
1215       pp->dvmove = (pp->dir*sin(walk_direction*M_PI/180.0)*
1216                     walk_speed*M_PI/4096.0);
1217       pp->vmove += pp->dvmove;
1218       if (pp->vmove > 2.0*M_PI)
1219       {
1220         pp->vmove = 4.0*M_PI-pp->vmove;
1221         pp->umove = pp->umove-M_PI;
1222         if (pp->umove < 0.0)
1223           pp->umove += 2.0*M_PI;
1224         pp->side = -pp->side;
1225         pp->dir = -pp->dir;
1226         pp->dvmove = -pp->dvmove;
1227       }
1228       if (pp->vmove < 0.0)
1229       {
1230         pp->vmove = -pp->vmove;
1231         pp->umove = pp->umove-M_PI;
1232         if (pp->umove < 0.0)
1233           pp->umove += 2.0*M_PI;
1234         pp->dir = -pp->dir;
1235         pp->dvmove = -pp->dvmove;
1236       }
1237       pp->dumove = cos(walk_direction*M_PI/180.0)*walk_speed*M_PI/4096.0;
1238       pp->umove += pp->dumove;
1239       if (pp->umove >= 2.0*M_PI)
1240         pp->umove -= 2.0*M_PI;
1241       if (pp->umove < 0.0)
1242         pp->umove += 2.0*M_PI;
1243     }
1244   }
1245
1246   glMatrixMode(GL_PROJECTION);
1247   glLoadIdentity();
1248   if (projection == DISP_PERSPECTIVE || view == VIEW_WALK)
1249   {
1250     if (view == VIEW_WALK)
1251       gluPerspective(60.0,pp->aspect,0.01,10.0);
1252     else
1253       gluPerspective(60.0,pp->aspect,0.1,10.0);
1254   }
1255   else
1256   {
1257     if (pp->aspect >= 1.0)
1258       glOrtho(-pp->aspect,pp->aspect,-1.0,1.0,0.1,10.0);
1259     else
1260       glOrtho(-1.0,1.0,-1.0/pp->aspect,1.0/pp->aspect,0.1,10.0);
1261   }
1262   glMatrixMode(GL_MODELVIEW);
1263   glLoadIdentity();
1264
1265   mi->polygon_count = roman_boy(mi,0.0,2.0*M_PI,0.0,2.0*M_PI,pp->g*NUMU,NUMV);
1266 }
1267
1268
1269 ENTRYPOINT void reshape_romanboy(ModeInfo *mi, int width, int height)
1270 {
1271   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
1272
1273   pp->WindW = (GLint)width;
1274   pp->WindH = (GLint)height;
1275   glViewport(0,0,width,height);
1276   pp->aspect = (GLfloat)width/(GLfloat)height;
1277 }
1278
1279
1280 ENTRYPOINT Bool romanboy_handle_event(ModeInfo *mi, XEvent *event)
1281 {
1282   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
1283
1284   if (event->xany.type == ButtonPress && event->xbutton.button == Button1)
1285   {
1286     pp->button_pressed = True;
1287     gltrackball_start(pp->trackball, event->xbutton.x, event->xbutton.y,
1288                       MI_WIDTH(mi), MI_HEIGHT(mi));
1289     return True;
1290   }
1291   else if (event->xany.type == ButtonRelease &&
1292            event->xbutton.button == Button1)
1293   {
1294     pp->button_pressed = False;
1295     return True;
1296   }
1297   else if (event->xany.type == MotionNotify && pp->button_pressed)
1298   {
1299     gltrackball_track(pp->trackball, event->xmotion.x, event->xmotion.y,
1300                       MI_WIDTH(mi), MI_HEIGHT(mi));
1301     return True;
1302   }
1303
1304   return False;
1305 }
1306
1307
1308 /*
1309  *-----------------------------------------------------------------------------
1310  *-----------------------------------------------------------------------------
1311  *    Xlock hooks.
1312  *-----------------------------------------------------------------------------
1313  *-----------------------------------------------------------------------------
1314  */
1315
1316 /*
1317  *-----------------------------------------------------------------------------
1318  *    Initialize romanboy.  Called each time the window changes.
1319  *-----------------------------------------------------------------------------
1320  */
1321
1322 ENTRYPOINT void init_romanboy(ModeInfo *mi)
1323 {
1324   romanboystruct *pp;
1325
1326   if (romanboy == NULL)
1327   {
1328     romanboy =
1329       (romanboystruct *)calloc(MI_NUM_SCREENS(mi),sizeof(romanboystruct));
1330     if (romanboy == NULL)
1331       return;
1332   }
1333   pp = &romanboy[MI_SCREEN(mi)];
1334
1335   if (surface_order < 2)
1336     pp->g = 2;
1337   else if (surface_order > 9)
1338     pp->g = 9;
1339   else
1340     pp->g = surface_order;
1341
1342   pp->pp = calloc(3*pp->g*(NUMU+1)*(NUMV+1),sizeof(float));
1343   pp->pn = calloc(3*pp->g*(NUMU+1)*(NUMV+1),sizeof(float));
1344   pp->col = calloc(4*pp->g*(NUMU+1)*(NUMV+1),sizeof(float));
1345   pp->tex = calloc(2*pp->g*(NUMU+1)*(NUMV+1),sizeof(float));
1346
1347   pp->trackball = gltrackball_init(True);
1348   pp->button_pressed = False;
1349
1350   /* Set the display mode. */
1351   if (!strcasecmp(mode,"random"))
1352   {
1353     display_mode = random() % NUM_DISPLAY_MODES;
1354   }
1355   else if (!strcasecmp(mode,"wireframe"))
1356   {
1357     display_mode = DISP_WIREFRAME;
1358   }
1359   else if (!strcasecmp(mode,"surface"))
1360   {
1361     display_mode = DISP_SURFACE;
1362   }
1363   else if (!strcasecmp(mode,"transparent"))
1364   {
1365     display_mode = DISP_TRANSPARENT;
1366   }
1367   else
1368   {
1369     display_mode = random() % NUM_DISPLAY_MODES;
1370   }
1371
1372   /* Orientation marks don't make sense in wireframe mode. */
1373   if (display_mode == DISP_WIREFRAME)
1374     marks = False;
1375
1376   /* Set the appearance. */
1377   if (!strcasecmp(appear,"random"))
1378   {
1379     appearance = random() % NUM_APPEARANCES;
1380   }
1381   else if (!strcasecmp(appear,"solid"))
1382   {
1383     appearance = APPEARANCE_SOLID;
1384   }
1385   else if (!strcasecmp(appear,"distance-bands"))
1386   {
1387     appearance = APPEARANCE_DISTANCE_BANDS;
1388   }
1389   else if (!strcasecmp(appear,"direction-bands"))
1390   {
1391     appearance = APPEARANCE_DIRECTION_BANDS;
1392   }
1393   else
1394   {
1395     appearance = random() % NUM_APPEARANCES;
1396   }
1397
1398   /* Set the color mode. */
1399   if (!strcasecmp(color_mode,"random"))
1400   {
1401     colors = random() % NUM_COLORS;
1402   }
1403   else if (!strcasecmp(color_mode,"two-sided"))
1404   {
1405     colors = COLORS_TWOSIDED;
1406   }
1407   else if (!strcasecmp(color_mode,"distance"))
1408   {
1409     colors = COLORS_DISTANCE;
1410   }
1411   else if (!strcasecmp(color_mode,"direction"))
1412   {
1413     colors = COLORS_DIRECTION;
1414   }
1415   else
1416   {
1417     colors = random() % NUM_COLORS;
1418   }
1419
1420   /* Set the view mode. */
1421   if (!strcasecmp(view_mode,"random"))
1422   {
1423     view = random() % NUM_VIEW_MODES;
1424   }
1425   else if (!strcasecmp(view_mode,"walk"))
1426   {
1427     view = VIEW_WALK;
1428   }
1429   else if (!strcasecmp(view_mode,"turn"))
1430   {
1431     view = VIEW_TURN;
1432   }
1433   else
1434   {
1435     view = random() % NUM_VIEW_MODES;
1436   }
1437
1438   /* Set the 3d projection mode. */
1439   if (!strcasecmp(proj,"random"))
1440   {
1441     /* Orthographic projection only makes sense in turn mode. */
1442     if (view == VIEW_TURN)
1443       projection = random() % NUM_DISP_MODES;
1444     else
1445       projection = DISP_PERSPECTIVE;
1446   }
1447   else if (!strcasecmp(proj,"perspective"))
1448   {
1449     projection = DISP_PERSPECTIVE;
1450   }
1451   else if (!strcasecmp(proj,"orthographic"))
1452   {
1453     projection = DISP_ORTHOGRAPHIC;
1454   }
1455   else
1456   {
1457     /* Orthographic projection only makes sense in turn mode. */
1458     if (view == VIEW_TURN)
1459       projection = random() % NUM_DISP_MODES;
1460     else
1461       projection = DISP_PERSPECTIVE;
1462   }
1463
1464   /* make multiple screens rotate at slightly different rates. */
1465   pp->speed_scale = 0.9 + frand(0.3);
1466
1467   if ((pp->glx_context = init_GL(mi)) != NULL)
1468   {
1469     reshape_romanboy(mi,MI_WIDTH(mi),MI_HEIGHT(mi));
1470     glDrawBuffer(GL_BACK);
1471     init(mi);
1472   }
1473   else
1474   {
1475     MI_CLEARWINDOW(mi);
1476   }
1477 }
1478
1479 /*
1480  *-----------------------------------------------------------------------------
1481  *    Called by the mainline code periodically to update the display.
1482  *-----------------------------------------------------------------------------
1483  */
1484 ENTRYPOINT void draw_romanboy(ModeInfo *mi)
1485 {
1486   Display *display = MI_DISPLAY(mi);
1487   Window window = MI_WINDOW(mi);
1488   romanboystruct *pp;
1489
1490   if (romanboy == NULL)
1491     return;
1492   pp = &romanboy[MI_SCREEN(mi)];
1493
1494   MI_IS_DRAWN(mi) = True;
1495   if (!pp->glx_context)
1496     return;
1497
1498   glXMakeCurrent(display,window,*(pp->glx_context));
1499
1500   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
1501   glLoadIdentity();
1502
1503   display_romanboy(mi);
1504
1505   if (MI_IS_FPS(mi))
1506     do_fps (mi);
1507
1508   glFlush();
1509
1510   glXSwapBuffers(display,window);
1511 }
1512
1513
1514 /*
1515  *-----------------------------------------------------------------------------
1516  *    The display is being taken away from us.  Free up malloc'ed 
1517  *      memory and X resources that we've alloc'ed.  Only called
1518  *      once, we must zap everything for every screen.
1519  *-----------------------------------------------------------------------------
1520  */
1521
1522 ENTRYPOINT void release_romanboy(ModeInfo *mi)
1523 {
1524   if (romanboy != NULL)
1525   {
1526     int screen;
1527
1528     for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++)
1529     {
1530       romanboystruct *pp = &romanboy[screen];
1531
1532       if (pp->glx_context)
1533         pp->glx_context = (GLXContext *)NULL;
1534       if (pp->pp)
1535         (void) free((void *)pp->pp);
1536       if (pp->pn)
1537         (void) free((void *)pp->pn);
1538       if (pp->col)
1539         (void) free((void *)pp->col);
1540       if (pp->tex)
1541         (void) free((void *)pp->tex);
1542     }
1543     (void) free((void *)romanboy);
1544     romanboy = (romanboystruct *)NULL;
1545   }
1546   FreeAllGL(mi);
1547 }
1548
1549 #ifndef STANDALONE
1550 ENTRYPOINT void change_romanboy(ModeInfo *mi)
1551 {
1552   romanboystruct *pp = &romanboy[MI_SCREEN(mi)];
1553
1554   if (!pp->glx_context)
1555     return;
1556
1557   glXMakeCurrent(MI_DISPLAY(mi),MI_WINDOW(mi),*(pp->glx_context));
1558   init(mi);
1559 }
1560 #endif /* !STANDALONE */
1561
1562 XSCREENSAVER_MODULE ("RomanBoy", romanboy)
1563
1564 #endif /* USE_GL */