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