From http://www.jwz.org/xscreensaver/xscreensaver-5.37.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 # define release_projectiveplane 0
224 # include "xlockmore.h"         /* from the xscreensaver distribution */
225 #else  /* !STANDALONE */
226 # include "xlock.h"             /* from the xlockmore distribution */
227 #endif /* !STANDALONE */
228
229 #ifdef USE_GL
230
231 #ifndef HAVE_JWXYZ
232 # include <X11/keysym.h>
233 #endif
234
235 #include "gltrackball.h"
236
237 #include <float.h>
238
239
240 #ifdef USE_MODULES
241 ModStruct projectiveplane_description =
242 {"projectiveplane", "init_projectiveplane", "draw_projectiveplane",
243  NULL, "draw_projectiveplane", "change_projectiveplane",
244  NULL, &projectiveplane_opts, 25000, 1, 1, 1, 1.0, 4, "",
245  "Rotate a 4d embedding of the real projective plane in 4d or walk on it",
246  0, NULL};
247
248 #endif
249
250
251 static char *mode;
252 static char *appear;
253 static char *color_mode;
254 static char *view_mode;
255 static Bool marks;
256 static char *proj_3d;
257 static char *proj_4d;
258 static float speed_wx;
259 static float speed_wy;
260 static float speed_wz;
261 static float speed_xy;
262 static float speed_xz;
263 static float speed_yz;
264 static float walk_direction;
265 static float walk_speed;
266
267
268 static XrmOptionDescRec opts[] =
269 {
270   {"-mode",              ".displayMode",   XrmoptionSepArg, 0 },
271   {"-wireframe",         ".displayMode",   XrmoptionNoArg,  "wireframe" },
272   {"-surface",           ".displayMode",   XrmoptionNoArg,  "surface" },
273   {"-transparent",       ".displayMode",   XrmoptionNoArg,  "transparent" },
274   {"-appearance",        ".appearance",    XrmoptionSepArg, 0 },
275   {"-solid",             ".appearance",    XrmoptionNoArg,  "solid" },
276   {"-distance-bands",    ".appearance",    XrmoptionNoArg,  "distance-bands" },
277   {"-direction-bands",   ".appearance",    XrmoptionNoArg,  "direction-bands" },
278   {"-colors",            ".colors",        XrmoptionSepArg, 0 },
279   {"-twosided-colors",   ".colors",        XrmoptionNoArg,  "two-sided" },
280   {"-distance-colors",   ".colors",        XrmoptionNoArg,  "distance" },
281   {"-direction-colors",  ".colors",        XrmoptionNoArg,  "direction" },
282   {"-depth-colors",      ".colors",        XrmoptionNoArg,  "depth" },
283   {"-view-mode",         ".viewMode",      XrmoptionSepArg, 0 },
284   {"-walk",              ".viewMode",      XrmoptionNoArg,  "walk" },
285   {"-turn",              ".viewMode",      XrmoptionNoArg,  "turn" },
286   {"-walk-turn",         ".viewMode",      XrmoptionNoArg,  "walk-turn" },
287   {"-orientation-marks", ".marks",         XrmoptionNoArg, "on"},
288   {"+orientation-marks", ".marks",         XrmoptionNoArg, "off"},
289   {"-projection-3d",     ".projection3d",  XrmoptionSepArg, 0 },
290   {"-perspective-3d",    ".projection3d",  XrmoptionNoArg,  "perspective" },
291   {"-orthographic-3d",   ".projection3d",  XrmoptionNoArg,  "orthographic" },
292   {"-projection-4d",     ".projection4d",  XrmoptionSepArg, 0 },
293   {"-perspective-4d",    ".projection4d",  XrmoptionNoArg,  "perspective" },
294   {"-orthographic-4d",   ".projection4d",  XrmoptionNoArg,  "orthographic" },
295   {"-speed-wx",          ".speedwx",       XrmoptionSepArg, 0 },
296   {"-speed-wy",          ".speedwy",       XrmoptionSepArg, 0 },
297   {"-speed-wz",          ".speedwz",       XrmoptionSepArg, 0 },
298   {"-speed-xy",          ".speedxy",       XrmoptionSepArg, 0 },
299   {"-speed-xz",          ".speedxz",       XrmoptionSepArg, 0 },
300   {"-speed-yz",          ".speedyz",       XrmoptionSepArg, 0 },
301   {"-walk-direction",    ".walkDirection", XrmoptionSepArg, 0 },
302   {"-walk-speed",        ".walkSpeed",     XrmoptionSepArg, 0 }
303 };
304
305 static argtype vars[] =
306 {
307   { &mode,           "displayMode",   "DisplayMode",   DEF_DISPLAY_MODE,   t_String },
308   { &appear,         "appearance",    "Appearance",    DEF_APPEARANCE,     t_String },
309   { &color_mode,     "colors",        "Colors",        DEF_COLORS,         t_String },
310   { &view_mode,      "viewMode",      "ViewMode",      DEF_VIEW_MODE,      t_String },
311   { &marks,          "marks",         "Marks",         DEF_MARKS,          t_Bool },
312   { &proj_3d,        "projection3d",  "Projection3d",  DEF_PROJECTION_3D,  t_String },
313   { &proj_4d,        "projection4d",  "Projection4d",  DEF_PROJECTION_4D,  t_String },
314   { &speed_wx,       "speedwx",       "Speedwx",       DEF_SPEEDWX,        t_Float},
315   { &speed_wy,       "speedwy",       "Speedwy",       DEF_SPEEDWY,        t_Float},
316   { &speed_wz,       "speedwz",       "Speedwz",       DEF_SPEEDWZ,        t_Float},
317   { &speed_xy,       "speedxy",       "Speedxy",       DEF_SPEEDXY,        t_Float},
318   { &speed_xz,       "speedxz",       "Speedxz",       DEF_SPEEDXZ,        t_Float},
319   { &speed_yz,       "speedyz",       "Speedyz",       DEF_SPEEDYZ,        t_Float},
320   { &walk_direction, "walkDirection", "WalkDirection", DEF_WALK_DIRECTION, t_Float},
321   { &walk_speed,     "walkSpeed",     "WalkSpeed",     DEF_WALK_SPEED,     t_Float}
322 };
323
324 ENTRYPOINT ModeSpecOpt projectiveplane_opts =
325 {sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, NULL};
326
327
328 /* Offset by which we walk above the projective plane */
329 #define DELTAY  0.01
330
331 /* Number of subdivisions of the projective plane */
332 #define NUMU 128
333 #define NUMV 128
334
335 /* Number of subdivisions per band */
336 #define NUMB 8
337
338
339 typedef struct {
340   GLint      WindH, WindW;
341   GLXContext *glx_context;
342   /* Options */
343   int display_mode;
344   int appearance;
345   int colors;
346   int view;
347   Bool marks;
348   int projection_3d;
349   int projection_4d;
350   /* 4D rotation angles */
351   float alpha, beta, delta, zeta, eta, theta;
352   /* Movement parameters */
353   float umove, vmove, dumove, dvmove;
354   int side, dir;
355   /* The viewing offset in 4d */
356   float offset4d[4];
357   /* The viewing offset in 3d */
358   float offset3d[4];
359   /* The 4d coordinates of the projective plane and their derivatives */
360   float x[(NUMU+1)*(NUMV+1)][4];
361   float xu[(NUMU+1)*(NUMV+1)][4];
362   float xv[(NUMU+1)*(NUMV+1)][4];
363   float pp[(NUMU+1)*(NUMV+1)][3];
364   float pn[(NUMU+1)*(NUMV+1)][3];
365   /* The precomputed colors of the projective plane */
366   float col[(NUMU+1)*(NUMV+1)][4];
367   /* The precomputed texture coordinates of the projective plane */
368   float tex[(NUMU+1)*(NUMV+1)][2];
369   /* The "curlicue" texture */
370   GLuint tex_name;
371   /* Aspect ratio of the current window */
372   float aspect;
373   /* Trackball states */
374   trackball_state *trackballs[2];
375   int current_trackball;
376   Bool button_pressed;
377   /* A random factor to modify the rotation speeds */
378   float speed_scale;
379 } projectiveplanestruct;
380
381 static projectiveplanestruct *projectiveplane = (projectiveplanestruct *) NULL;
382
383
384 /* Add a rotation around the wx-plane to the matrix m. */
385 static void rotatewx(float m[4][4], float phi)
386 {
387   float c, s, u, v;
388   int i;
389
390   phi *= M_PI/180.0;
391   c = cos(phi);
392   s = sin(phi);
393   for (i=0; i<4; i++)
394   {
395     u = m[i][1];
396     v = m[i][2];
397     m[i][1] = c*u+s*v;
398     m[i][2] = -s*u+c*v;
399   }
400 }
401
402
403 /* Add a rotation around the wy-plane to the matrix m. */
404 static void rotatewy(float m[4][4], float phi)
405 {
406   float c, s, u, v;
407   int i;
408
409   phi *= M_PI/180.0;
410   c = cos(phi);
411   s = sin(phi);
412   for (i=0; i<4; i++)
413   {
414     u = m[i][0];
415     v = m[i][2];
416     m[i][0] = c*u-s*v;
417     m[i][2] = s*u+c*v;
418   }
419 }
420
421
422 /* Add a rotation around the wz-plane to the matrix m. */
423 static void rotatewz(float m[4][4], float phi)
424 {
425   float c, s, u, v;
426   int i;
427
428   phi *= M_PI/180.0;
429   c = cos(phi);
430   s = sin(phi);
431   for (i=0; i<4; i++)
432   {
433     u = m[i][0];
434     v = m[i][1];
435     m[i][0] = c*u+s*v;
436     m[i][1] = -s*u+c*v;
437   }
438 }
439
440
441 /* Add a rotation around the xy-plane to the matrix m. */
442 static void rotatexy(float m[4][4], float phi)
443 {
444   float c, s, u, v;
445   int i;
446
447   phi *= M_PI/180.0;
448   c = cos(phi);
449   s = sin(phi);
450   for (i=0; i<4; i++)
451   {
452     u = m[i][2];
453     v = m[i][3];
454     m[i][2] = c*u+s*v;
455     m[i][3] = -s*u+c*v;
456   }
457 }
458
459
460 /* Add a rotation around the xz-plane to the matrix m. */
461 static void rotatexz(float m[4][4], float phi)
462 {
463   float c, s, u, v;
464   int i;
465
466   phi *= M_PI/180.0;
467   c = cos(phi);
468   s = sin(phi);
469   for (i=0; i<4; i++)
470   {
471     u = m[i][1];
472     v = m[i][3];
473     m[i][1] = c*u-s*v;
474     m[i][3] = s*u+c*v;
475   }
476 }
477
478
479 /* Add a rotation around the yz-plane to the matrix m. */
480 static void rotateyz(float m[4][4], float phi)
481 {
482   float c, s, u, v;
483   int i;
484
485   phi *= M_PI/180.0;
486   c = cos(phi);
487   s = sin(phi);
488   for (i=0; i<4; i++)
489   {
490     u = m[i][0];
491     v = m[i][3];
492     m[i][0] = c*u-s*v;
493     m[i][3] = s*u+c*v;
494   }
495 }
496
497
498 /* Compute the rotation matrix m from the rotation angles. */
499 static void rotateall(float al, float be, float de, float ze, float et,
500                       float th, float m[4][4])
501 {
502   int i, j;
503
504   for (i=0; i<4; i++)
505     for (j=0; j<4; j++)
506       m[i][j] = (i==j);
507   rotatewx(m,al);
508   rotatewy(m,be);
509   rotatewz(m,de);
510   rotatexy(m,ze);
511   rotatexz(m,et);
512   rotateyz(m,th);
513 }
514
515
516 /* Compute the rotation matrix m from the 4d rotation angles. */
517 static void rotateall4d(float ze, float et, float th, float m[4][4])
518 {
519   int i, j;
520
521   for (i=0; i<4; i++)
522     for (j=0; j<4; j++)
523       m[i][j] = (i==j);
524   rotatexy(m,ze);
525   rotatexz(m,et);
526   rotateyz(m,th);
527 }
528
529
530 /* Multiply two rotation matrices: o=m*n. */
531 static void mult_rotmat(float m[4][4], float n[4][4], float o[4][4])
532 {
533   int i, j, k;
534
535   for (i=0; i<4; i++)
536   {
537     for (j=0; j<4; j++)
538     {
539       o[i][j] = 0.0;
540       for (k=0; k<4; k++)
541         o[i][j] += m[i][k]*n[k][j];
542     }
543   }
544 }
545
546
547 /* Compute a 4D rotation matrix from two unit quaternions. */
548 static void quats_to_rotmat(float p[4], float q[4], float m[4][4])
549 {
550   double al, be, de, ze, et, th;
551   double r00, r01, r02, r12, r22;
552
553   r00 = 1.0-2.0*(p[1]*p[1]+p[2]*p[2]);
554   r01 = 2.0*(p[0]*p[1]+p[2]*p[3]);
555   r02 = 2.0*(p[2]*p[0]-p[1]*p[3]);
556   r12 = 2.0*(p[1]*p[2]+p[0]*p[3]);
557   r22 = 1.0-2.0*(p[1]*p[1]+p[0]*p[0]);
558
559   al = atan2(-r12,r22)*180.0/M_PI;
560   be = atan2(r02,sqrt(r00*r00+r01*r01))*180.0/M_PI;
561   de = atan2(-r01,r00)*180.0/M_PI;
562
563   r00 = 1.0-2.0*(q[1]*q[1]+q[2]*q[2]);
564   r01 = 2.0*(q[0]*q[1]+q[2]*q[3]);
565   r02 = 2.0*(q[2]*q[0]-q[1]*q[3]);
566   r12 = 2.0*(q[1]*q[2]+q[0]*q[3]);
567   r22 = 1.0-2.0*(q[1]*q[1]+q[0]*q[0]);
568
569   et = atan2(-r12,r22)*180.0/M_PI;
570   th = atan2(r02,sqrt(r00*r00+r01*r01))*180.0/M_PI;
571   ze = atan2(-r01,r00)*180.0/M_PI;
572
573   rotateall(al,be,de,ze,et,-th,m);
574 }
575
576
577 /* Compute a fully saturated and bright color based on an angle. */
578 static void color(projectiveplanestruct *pp, double angle, float col[4])
579 {
580   int s;
581   double t;
582
583   if (pp->colors == COLORS_TWOSIDED)
584     return;
585
586   if (angle >= 0.0)
587     angle = fmod(angle,2.0*M_PI);
588   else
589     angle = fmod(angle,-2.0*M_PI);
590   s = floor(angle/(M_PI/3));
591   t = angle/(M_PI/3)-s;
592   if (s >= 6)
593     s = 0;
594   switch (s)
595   {
596     case 0:
597       col[0] = 1.0;
598       col[1] = t;
599       col[2] = 0.0;
600       break;
601     case 1:
602       col[0] = 1.0-t;
603       col[1] = 1.0;
604       col[2] = 0.0;
605       break;
606     case 2:
607       col[0] = 0.0;
608       col[1] = 1.0;
609       col[2] = t;
610       break;
611     case 3:
612       col[0] = 0.0;
613       col[1] = 1.0-t;
614       col[2] = 1.0;
615       break;
616     case 4:
617       col[0] = t;
618       col[1] = 0.0;
619       col[2] = 1.0;
620       break;
621     case 5:
622       col[0] = 1.0;
623       col[1] = 0.0;
624       col[2] = 1.0-t;
625       break;
626   }
627   if (pp->display_mode == DISP_TRANSPARENT)
628     col[3] = 0.7;
629   else
630     col[3] = 1.0;
631 }
632
633
634 /* Set up the projective plane coordinates, colors, and texture. */
635 static void setup_projective_plane(ModeInfo *mi, double umin, double umax,
636                                    double vmin, double vmax)
637 {
638   int i, j, k;
639   double u, v, ur, vr;
640   double cu, su, cv2, sv2, cv4, sv4, c2u, s2u;
641   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
642
643   ur = umax-umin;
644   vr = vmax-vmin;
645   for (i=0; i<=NUMV; i++)
646   {
647     for (j=0; j<=NUMU; j++)
648     {
649       k = i*(NUMU+1)+j;
650       if (pp->appearance != APPEARANCE_DIRECTION_BANDS)
651         u = -ur*j/NUMU+umin;
652       else
653         u = ur*j/NUMU+umin;
654       v = vr*i/NUMV+vmin;
655       cu = cos(u);
656       su = sin(u);
657       c2u = cos(2.0*u);
658       s2u = sin(2.0*u);
659       sv2 = sin(0.5*v);
660       cv4 = cos(0.25*v);
661       sv4 = sin(0.25*v);
662       if (pp->colors == COLORS_DEPTH)
663         color(pp,((su*su*sv4*sv4-cv4*cv4)+1.0)*M_PI*2.0/3.0,pp->col[k]);
664       else if (pp->colors == COLORS_DIRECTION)
665         color(pp,2.0*M_PI+fmod(2.0*u,2.0*M_PI),pp->col[k]);
666       else /* pp->colors == COLORS_DISTANCE */
667         color(pp,v*(5.0/6.0),pp->col[k]);
668       pp->tex[k][0] = -32*u/(2.0*M_PI);
669       if (pp->appearance != APPEARANCE_DISTANCE_BANDS)
670         pp->tex[k][1] = 32*v/(2.0*M_PI);
671       else
672         pp->tex[k][1] = 32*v/(2.0*M_PI)-0.5;
673       pp->x[k][0] = 0.5*s2u*sv4*sv4;
674       pp->x[k][1] = 0.5*su*sv2;
675       pp->x[k][2] = 0.5*cu*sv2;
676       pp->x[k][3] = 0.5*(su*su*sv4*sv4-cv4*cv4);
677       /* Avoid degenerate tangential plane basis vectors. */
678       if (v < FLT_EPSILON)
679         v = FLT_EPSILON;
680       cv2 = cos(0.5*v);
681       sv2 = sin(0.5*v);
682       sv4 = sin(0.25*v);
683       pp->xu[k][0] = c2u*sv4*sv4;
684       pp->xu[k][1] = 0.5*cu*sv2;
685       pp->xu[k][2] = -0.5*su*sv2;
686       pp->xu[k][3] = 0.5*s2u*sv4*sv4;
687       pp->xv[k][0] = 0.125*s2u*sv2;
688       pp->xv[k][1] = 0.25*su*cv2;
689       pp->xv[k][2] = 0.25*cu*cv2;
690       pp->xv[k][3] = 0.125*(su*su+1.0)*sv2;
691     }
692   }
693 }
694
695
696 /* Draw a 4d embedding of the projective plane projected into 3D. */
697 static int projective_plane(ModeInfo *mi, double umin, double umax,
698                             double vmin, double vmax)
699 {
700   int polys = 0;
701   static const GLfloat mat_diff_red[]         = { 1.0, 0.0, 0.0, 1.0 };
702   static const GLfloat mat_diff_green[]       = { 0.0, 1.0, 0.0, 1.0 };
703   static const GLfloat mat_diff_trans_red[]   = { 1.0, 0.0, 0.0, 0.7 };
704   static const GLfloat mat_diff_trans_green[] = { 0.0, 1.0, 0.0, 0.7 };
705   float p[3], pu[3], pv[3], pm[3], n[3], b[3], mat[4][4];
706   int i, j, k, l, m, o;
707   double u, v;
708   double xx[4], xxu[4], xxv[4], y[4], yu[4], yv[4];
709   double q, r, s, t;
710   double cu, su, cv2, sv2, cv4, sv4, c2u, s2u;
711   float q1[4], q2[4], r1[4][4], r2[4][4];
712   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
713
714   if (pp->view == VIEW_WALK || pp->view == VIEW_WALKTURN)
715   {
716     /* Compute the rotation that rotates the projective plane in 4D without
717        the trackball rotations. */
718     rotateall4d(pp->zeta,pp->eta,pp->theta,mat);
719
720     u = pp->umove;
721     v = pp->vmove;
722     cu = cos(u);
723     su = sin(u);
724     c2u = cos(2.0*u);
725     s2u = sin(2.0*u);
726     sv2 = sin(0.5*v);
727     cv4 = cos(0.25*v);
728     sv4 = sin(0.25*v);
729     xx[0] = 0.5*s2u*sv4*sv4;
730     xx[1] = 0.5*su*sv2;
731     xx[2] = 0.5*cu*sv2;
732     xx[3] = 0.5*(su*su*sv4*sv4-cv4*cv4);
733     /* Avoid degenerate tangential plane basis vectors. */
734     if (v < FLT_EPSILON)
735       v = FLT_EPSILON;
736     cv2 = cos(0.5*v);
737     sv2 = sin(0.5*v);
738     sv4 = sin(0.25*v);
739     xxu[0] = c2u*sv4*sv4;
740     xxu[1] = 0.5*cu*sv2;
741     xxu[2] = -0.5*su*sv2;
742     xxu[3] = 0.5*s2u*sv4*sv4;
743     xxv[0] = 0.125*s2u*sv2;
744     xxv[1] = 0.25*su*cv2;
745     xxv[2] = 0.25*cu*cv2;
746     xxv[3] = 0.125*(su*su+1.0)*sv2;
747     for (l=0; l<4; l++)
748     {
749       y[l] = (mat[l][0]*xx[0]+mat[l][1]*xx[1]+
750               mat[l][2]*xx[2]+mat[l][3]*xx[3]);
751       yu[l] = (mat[l][0]*xxu[0]+mat[l][1]*xxu[1]+
752                mat[l][2]*xxu[2]+mat[l][3]*xxu[3]);
753       yv[l] = (mat[l][0]*xxv[0]+mat[l][1]*xxv[1]+
754                mat[l][2]*xxv[2]+mat[l][3]*xxv[3]);
755     }
756     if (pp->projection_4d == DISP_4D_ORTHOGRAPHIC)
757     {
758       for (l=0; l<3; l++)
759       {
760         p[l] = y[l]+pp->offset4d[l];
761         pu[l] = yu[l];
762         pv[l] = yv[l];
763       }
764     }
765     else
766     {
767       s = y[3]+pp->offset4d[3];
768       q = 1.0/s;
769       t = q*q;
770       for (l=0; l<3; l++)
771       {
772         r = y[l]+pp->offset4d[l];
773         p[l] = r*q;
774         pu[l] = (yu[l]*s-r*yu[3])*t;
775         pv[l] = (yv[l]*s-r*yv[3])*t;
776       }
777     }
778     n[0] = pu[1]*pv[2]-pu[2]*pv[1];
779     n[1] = pu[2]*pv[0]-pu[0]*pv[2];
780     n[2] = pu[0]*pv[1]-pu[1]*pv[0];
781     t = 1.0/(pp->side*4.0*sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]));
782     n[0] *= t;
783     n[1] *= t;
784     n[2] *= t;
785     pm[0] = pu[0]*pp->dumove+pv[0]*pp->dvmove;
786     pm[1] = pu[1]*pp->dumove+pv[1]*pp->dvmove;
787     pm[2] = pu[2]*pp->dumove+pv[2]*pp->dvmove;
788     t = 1.0/(4.0*sqrt(pm[0]*pm[0]+pm[1]*pm[1]+pm[2]*pm[2]));
789     pm[0] *= t;
790     pm[1] *= t;
791     pm[2] *= t;
792     b[0] = n[1]*pm[2]-n[2]*pm[1];
793     b[1] = n[2]*pm[0]-n[0]*pm[2];
794     b[2] = n[0]*pm[1]-n[1]*pm[0];
795     t = 1.0/(4.0*sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]));
796     b[0] *= t;
797     b[1] *= t;
798     b[2] *= t;
799
800     /* Compute alpha, beta, delta from the three basis vectors.
801            |  -b[0]  -b[1]  -b[2] |
802        m = |   n[0]   n[1]   n[2] |
803            | -pm[0] -pm[1] -pm[2] |
804     */
805     pp->alpha = atan2(-n[2],-pm[2])*180/M_PI;
806     pp->beta = atan2(-b[2],sqrt(b[0]*b[0]+b[1]*b[1]))*180/M_PI;
807     pp->delta = atan2(b[1],-b[0])*180/M_PI;
808
809     /* Compute the rotation that rotates the projective plane in 4D. */
810     rotateall(pp->alpha,pp->beta,pp->delta,pp->zeta,pp->eta,pp->theta,mat);
811
812     u = pp->umove;
813     v = pp->vmove;
814     cu = cos(u);
815     su = sin(u);
816     s2u = sin(2.0*u);
817     sv2 = sin(0.5*v);
818     cv4 = cos(0.25*v);
819     sv4 = sin(0.25*v);
820     xx[0] = 0.5*s2u*sv4*sv4;
821     xx[1] = 0.5*su*sv2;
822     xx[2] = 0.5*cu*sv2;
823     xx[3] = 0.5*(su*su*sv4*sv4-cv4*cv4);
824     for (l=0; l<4; l++)
825     {
826       r = 0.0;
827       for (m=0; m<4; m++)
828         r += mat[l][m]*xx[m];
829       y[l] = r;
830     }
831     if (pp->projection_4d == DISP_4D_ORTHOGRAPHIC)
832     {
833       for (l=0; l<3; l++)
834         p[l] = y[l]+pp->offset4d[l];
835     }
836     else
837     {
838       s = y[3]+pp->offset4d[3];
839       for (l=0; l<3; l++)
840         p[l] = (y[l]+pp->offset4d[l])/s;
841     }
842
843     pp->offset3d[0] = -p[0];
844     pp->offset3d[1] = -p[1]-DELTAY;
845     pp->offset3d[2] = -p[2];
846   }
847   else
848   {
849     /* Compute the rotation that rotates the projective plane in 4D,
850        including the trackball rotations. */
851     rotateall(pp->alpha,pp->beta,pp->delta,pp->zeta,pp->eta,pp->theta,r1);
852
853     gltrackball_get_quaternion(pp->trackballs[0],q1);
854     gltrackball_get_quaternion(pp->trackballs[1],q2);
855     quats_to_rotmat(q1,q2,r2);
856
857     mult_rotmat(r2,r1,mat);
858   }
859
860   /* Project the points from 4D to 3D. */
861   for (i=0; i<=NUMV; i++)
862   {
863     for (j=0; j<=NUMU; j++)
864     {
865       o = i*(NUMU+1)+j;
866       for (l=0; l<4; l++)
867       {
868         y[l] = (mat[l][0]*pp->x[o][0]+mat[l][1]*pp->x[o][1]+
869                 mat[l][2]*pp->x[o][2]+mat[l][3]*pp->x[o][3]);
870         yu[l] = (mat[l][0]*pp->xu[o][0]+mat[l][1]*pp->xu[o][1]+
871                  mat[l][2]*pp->xu[o][2]+mat[l][3]*pp->xu[o][3]);
872         yv[l] = (mat[l][0]*pp->xv[o][0]+mat[l][1]*pp->xv[o][1]+
873                  mat[l][2]*pp->xv[o][2]+mat[l][3]*pp->xv[o][3]);
874       }
875       if (pp->projection_4d == DISP_4D_ORTHOGRAPHIC)
876       {
877         for (l=0; l<3; l++)
878         {
879           pp->pp[o][l] = (y[l]+pp->offset4d[l])+pp->offset3d[l];
880           pu[l] = yu[l];
881           pv[l] = yv[l];
882         }
883       }
884       else
885       {
886         s = y[3]+pp->offset4d[3];
887         q = 1.0/s;
888         t = q*q;
889         for (l=0; l<3; l++)
890         {
891           r = y[l]+pp->offset4d[l];
892           pp->pp[o][l] = r*q+pp->offset3d[l];
893           pu[l] = (yu[l]*s-r*yu[3])*t;
894           pv[l] = (yv[l]*s-r*yv[3])*t;
895         }
896       }
897       pp->pn[o][0] = pu[1]*pv[2]-pu[2]*pv[1];
898       pp->pn[o][1] = pu[2]*pv[0]-pu[0]*pv[2];
899       pp->pn[o][2] = pu[0]*pv[1]-pu[1]*pv[0];
900       t = 1.0/sqrt(pp->pn[o][0]*pp->pn[o][0]+pp->pn[o][1]*pp->pn[o][1]+
901                    pp->pn[o][2]*pp->pn[o][2]);
902       pp->pn[o][0] *= t;
903       pp->pn[o][1] *= t;
904       pp->pn[o][2] *= t;
905     }
906   }
907
908   if (pp->colors == COLORS_TWOSIDED)
909   {
910     glColor3fv(mat_diff_red);
911     if (pp->display_mode == DISP_TRANSPARENT)
912     {
913       glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,mat_diff_trans_red);
914       glMaterialfv(GL_BACK,GL_AMBIENT_AND_DIFFUSE,mat_diff_trans_green);
915     }
916     else
917     {
918       glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,mat_diff_red);
919       glMaterialfv(GL_BACK,GL_AMBIENT_AND_DIFFUSE,mat_diff_green);
920     }
921   }
922   glBindTexture(GL_TEXTURE_2D,pp->tex_name);
923
924   if (pp->appearance != APPEARANCE_DIRECTION_BANDS)
925   {
926     for (i=0; i<NUMV; i++)
927     {
928       if (pp->appearance == APPEARANCE_DISTANCE_BANDS &&
929           ((i & (NUMB-1)) >= NUMB/4) && ((i & (NUMB-1)) < 3*NUMB/4))
930         continue;
931       if (pp->display_mode == DISP_WIREFRAME)
932         glBegin(GL_QUAD_STRIP);
933       else
934         glBegin(GL_TRIANGLE_STRIP);
935       for (j=0; j<=NUMU; j++)
936       {
937         for (k=0; k<=1; k++)
938         {
939           l = (i+k);
940           m = j;
941           o = l*(NUMU+1)+m;
942           glNormal3fv(pp->pn[o]);
943           glTexCoord2fv(pp->tex[o]);
944           if (pp->colors != COLORS_TWOSIDED)
945           {
946             glColor3fv(pp->col[o]);
947             glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,pp->col[o]);
948           }
949           glVertex3fv(pp->pp[o]);
950           polys++;
951         }
952       }
953       glEnd();
954     }
955   }
956   else /* pp->appearance == APPEARANCE_DIRECTION_BANDS */
957   {
958     for (j=0; j<NUMU; j++)
959     {
960       if ((j & (NUMB-1)) >= NUMB/2)
961         continue;
962       if (pp->display_mode == DISP_WIREFRAME)
963         glBegin(GL_QUAD_STRIP);
964       else
965         glBegin(GL_TRIANGLE_STRIP);
966       for (i=0; i<=NUMV; i++)
967       {
968         for (k=0; k<=1; k++)
969         {
970           l = i;
971           m = (j+k);
972           o = l*(NUMU+1)+m;
973           glNormal3fv(pp->pn[o]);
974           glTexCoord2fv(pp->tex[o]);
975           if (pp->colors != COLORS_TWOSIDED)
976           {
977             glColor3fv(pp->col[o]);
978             glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,pp->col[o]);
979           }
980           glVertex3fv(pp->pp[o]);
981           polys++;
982         }
983       }
984       glEnd();
985     }
986   }
987
988   polys /= 2;
989   return polys;
990 }
991
992
993 /* Generate a texture image that shows the orientation reversal. */
994 static void gen_texture(ModeInfo *mi)
995 {
996   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
997
998   glGenTextures(1,&pp->tex_name);
999   glBindTexture(GL_TEXTURE_2D,pp->tex_name);
1000   glPixelStorei(GL_UNPACK_ALIGNMENT,1);
1001   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
1002   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
1003   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
1004   glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
1005   glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
1006   glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,TEX_DIMENSION,TEX_DIMENSION,0,
1007                GL_LUMINANCE,GL_UNSIGNED_BYTE,texture);
1008 }
1009
1010
1011 static void init(ModeInfo *mi)
1012 {
1013   static const GLfloat light_ambient[]  = { 0.0, 0.0, 0.0, 1.0 };
1014   static const GLfloat light_diffuse[]  = { 1.0, 1.0, 1.0, 1.0 };
1015   static const GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
1016   static const GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
1017   static const GLfloat mat_specular[]   = { 1.0, 1.0, 1.0, 1.0 };
1018   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
1019
1020   if (walk_speed == 0.0)
1021     walk_speed = 20.0;
1022
1023   if (pp->view == VIEW_TURN)
1024   {
1025     pp->alpha = frand(360.0);
1026     pp->beta = frand(360.0);
1027     pp->delta = frand(360.0);
1028     pp->zeta = 0.0;
1029     pp->eta = 0.0;
1030     pp->theta = 0.0;
1031   }
1032   else
1033   {
1034     pp->alpha = 0.0;
1035     pp->beta = 0.0;
1036     pp->delta = 0.0;
1037     pp->zeta = 120.0;
1038     pp->eta = 180.0;
1039     pp->theta = 90.0;
1040   }
1041   pp->umove = frand(2.0*M_PI);
1042   pp->vmove = frand(2.0*M_PI);
1043   pp->dumove = 0.0;
1044   pp->dvmove = 0.0;
1045   pp->side = 1;
1046   if (sin(walk_direction*M_PI/180.0) >= 0.0)
1047     pp->dir = 1;
1048   else
1049     pp->dir = -1;
1050
1051   pp->offset4d[0] = 0.0;
1052   pp->offset4d[1] = 0.0;
1053   pp->offset4d[2] = 0.0;
1054   pp->offset4d[3] = 1.2;
1055   pp->offset3d[0] = 0.0;
1056   pp->offset3d[1] = 0.0;
1057   pp->offset3d[2] = -1.2;
1058   pp->offset3d[3] = 0.0;
1059
1060   gen_texture(mi);
1061   setup_projective_plane(mi,0.0,2.0*M_PI,0.0,2.0*M_PI);
1062
1063   if (pp->marks)
1064     glEnable(GL_TEXTURE_2D);
1065   else
1066     glDisable(GL_TEXTURE_2D);
1067
1068   glMatrixMode(GL_PROJECTION);
1069   glLoadIdentity();
1070   if (pp->projection_3d == DISP_3D_PERSPECTIVE ||
1071       pp->view == VIEW_WALK || pp->view == VIEW_WALKTURN)
1072   {
1073     if (pp->view == VIEW_WALK || pp->view == VIEW_WALKTURN)
1074       gluPerspective(60.0,1.0,0.01,10.0);
1075     else
1076       gluPerspective(60.0,1.0,0.1,10.0);
1077   }
1078   else
1079   {
1080     glOrtho(-0.6,0.6,-0.6,0.6,0.1,10.0);
1081   }
1082   glMatrixMode(GL_MODELVIEW);
1083   glLoadIdentity();
1084
1085 # ifdef HAVE_JWZGLES /* #### glPolygonMode other than GL_FILL unimplemented */
1086   if (pp->display_mode == DISP_WIREFRAME)
1087     pp->display_mode = DISP_SURFACE;
1088 # endif
1089
1090   if (pp->display_mode == DISP_SURFACE)
1091   {
1092     glEnable(GL_DEPTH_TEST);
1093     glDepthFunc(GL_LESS);
1094     glShadeModel(GL_SMOOTH);
1095     glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
1096     glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
1097     glEnable(GL_LIGHTING);
1098     glEnable(GL_LIGHT0);
1099     glLightfv(GL_LIGHT0,GL_AMBIENT,light_ambient);
1100     glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);
1101     glLightfv(GL_LIGHT0,GL_SPECULAR,light_specular);
1102     glLightfv(GL_LIGHT0,GL_POSITION,light_position);
1103     glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,mat_specular);
1104     glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,50.0);
1105     glDepthMask(GL_TRUE);
1106     glDisable(GL_BLEND);
1107   }
1108   else if (pp->display_mode == DISP_TRANSPARENT)
1109   {
1110     glDisable(GL_DEPTH_TEST);
1111     glShadeModel(GL_SMOOTH);
1112     glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
1113     glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
1114     glEnable(GL_LIGHTING);
1115     glEnable(GL_LIGHT0);
1116     glLightfv(GL_LIGHT0,GL_AMBIENT,light_ambient);
1117     glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);
1118     glLightfv(GL_LIGHT0,GL_SPECULAR,light_specular);
1119     glLightfv(GL_LIGHT0,GL_POSITION,light_position);
1120     glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,mat_specular);
1121     glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,50.0);
1122     glDepthMask(GL_FALSE);
1123     glEnable(GL_BLEND);
1124     glBlendFunc(GL_SRC_ALPHA,GL_ONE);
1125   }
1126   else  /* pp->display_mode == DISP_WIREFRAME */
1127   {
1128     glDisable(GL_DEPTH_TEST);
1129     glShadeModel(GL_FLAT);
1130     glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
1131     glDisable(GL_LIGHTING);
1132     glDisable(GL_LIGHT0);
1133     glDisable(GL_BLEND);
1134   }
1135 }
1136
1137
1138 /* Redisplay the Klein bottle. */
1139 static void display_projectiveplane(ModeInfo *mi)
1140 {
1141   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
1142
1143   if (!pp->button_pressed)
1144   {
1145     if (pp->view == VIEW_TURN)
1146     {
1147       pp->alpha += speed_wx * pp->speed_scale;
1148       if (pp->alpha >= 360.0)
1149         pp->alpha -= 360.0;
1150       pp->beta += speed_wy * pp->speed_scale;
1151       if (pp->beta >= 360.0)
1152         pp->beta -= 360.0;
1153       pp->delta += speed_wz * pp->speed_scale;
1154       if (pp->delta >= 360.0)
1155         pp->delta -= 360.0;
1156       pp->zeta += speed_xy * pp->speed_scale;
1157       if (pp->zeta >= 360.0)
1158         pp->zeta -= 360.0;
1159       pp->eta += speed_xz * pp->speed_scale;
1160       if (pp->eta >= 360.0)
1161         pp->eta -= 360.0;
1162       pp->theta += speed_yz * pp->speed_scale;
1163       if (pp->theta >= 360.0)
1164         pp->theta -= 360.0;
1165     }
1166     if (pp->view == VIEW_WALKTURN)
1167     {
1168       pp->zeta += speed_xy * pp->speed_scale;
1169       if (pp->zeta >= 360.0)
1170         pp->zeta -= 360.0;
1171       pp->eta += speed_xz * pp->speed_scale;
1172       if (pp->eta >= 360.0)
1173         pp->eta -= 360.0;
1174       pp->theta += speed_yz * pp->speed_scale;
1175       if (pp->theta >= 360.0)
1176         pp->theta -= 360.0;
1177     }
1178     if (pp->view == VIEW_WALK || pp->view == VIEW_WALKTURN)
1179     {
1180       pp->dvmove = (pp->dir*sin(walk_direction*M_PI/180.0)*
1181                     walk_speed*M_PI/4096.0);
1182       pp->vmove += pp->dvmove;
1183       if (pp->vmove > 2.0*M_PI)
1184       {
1185         pp->vmove = 4.0*M_PI-pp->vmove;
1186         pp->umove = pp->umove-M_PI;
1187         if (pp->umove < 0.0)
1188           pp->umove += 2.0*M_PI;
1189         pp->side = -pp->side;
1190         pp->dir = -pp->dir;
1191         pp->dvmove = -pp->dvmove;
1192       }
1193       if (pp->vmove < 0.0)
1194       {
1195         pp->vmove = -pp->vmove;
1196         pp->umove = pp->umove-M_PI;
1197         if (pp->umove < 0.0)
1198           pp->umove += 2.0*M_PI;
1199         pp->dir = -pp->dir;
1200         pp->dvmove = -pp->dvmove;
1201       }
1202       pp->dumove = cos(walk_direction*M_PI/180.0)*walk_speed*M_PI/4096.0;
1203       pp->umove += pp->dumove;
1204       if (pp->umove >= 2.0*M_PI)
1205         pp->umove -= 2.0*M_PI;
1206       if (pp->umove < 0.0)
1207         pp->umove += 2.0*M_PI;
1208     }
1209   }
1210
1211   glMatrixMode(GL_PROJECTION);
1212   glLoadIdentity();
1213   if (pp->projection_3d == DISP_3D_PERSPECTIVE ||
1214       pp->view == VIEW_WALK || pp->view == VIEW_WALKTURN)
1215   {
1216     if (pp->view == VIEW_WALK || pp->view == VIEW_WALKTURN)
1217       gluPerspective(60.0,pp->aspect,0.01,10.0);
1218     else
1219       gluPerspective(60.0,pp->aspect,0.1,10.0);
1220   }
1221   else
1222   {
1223     if (pp->aspect >= 1.0)
1224       glOrtho(-0.6*pp->aspect,0.6*pp->aspect,-0.6,0.6,0.1,10.0);
1225     else
1226       glOrtho(-0.6,0.6,-0.6/pp->aspect,0.6/pp->aspect,0.1,10.0);
1227   }
1228   glMatrixMode(GL_MODELVIEW);
1229   glLoadIdentity();
1230
1231   mi->polygon_count = projective_plane(mi,0.0,2.0*M_PI,0.0,2.0*M_PI);
1232 }
1233
1234
1235 ENTRYPOINT void reshape_projectiveplane(ModeInfo *mi, int width, int height)
1236 {
1237   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
1238
1239   pp->WindW = (GLint)width;
1240   pp->WindH = (GLint)height;
1241   glViewport(0,0,width,height);
1242   pp->aspect = (GLfloat)width/(GLfloat)height;
1243 }
1244
1245
1246 ENTRYPOINT Bool projectiveplane_handle_event(ModeInfo *mi, XEvent *event)
1247 {
1248   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
1249   KeySym  sym = 0;
1250   char c = 0;
1251
1252   if (event->xany.type == KeyPress || event->xany.type == KeyRelease)
1253     XLookupString (&event->xkey, &c, 1, &sym, 0);
1254
1255   if (event->xany.type == ButtonPress &&
1256       event->xbutton.button == Button1)
1257   {
1258     pp->button_pressed = True;
1259     gltrackball_start(pp->trackballs[pp->current_trackball],
1260                       event->xbutton.x, event->xbutton.y,
1261                       MI_WIDTH(mi), MI_HEIGHT(mi));
1262     return True;
1263   }
1264   else if (event->xany.type == ButtonRelease &&
1265            event->xbutton.button == Button1)
1266   {
1267     pp->button_pressed = False;
1268     return True;
1269   }
1270   else if (event->xany.type == KeyPress)
1271   {
1272     if (sym == XK_Shift_L || sym == XK_Shift_R)
1273     {
1274       pp->current_trackball = 1;
1275       if (pp->button_pressed)
1276         gltrackball_start(pp->trackballs[pp->current_trackball],
1277                           event->xbutton.x, event->xbutton.y,
1278                           MI_WIDTH(mi), MI_HEIGHT(mi));
1279       return True;
1280     }
1281   }
1282   else if (event->xany.type == KeyRelease)
1283   {
1284     if (sym == XK_Shift_L || sym == XK_Shift_R)
1285     {
1286       pp->current_trackball = 0;
1287       if (pp->button_pressed)
1288         gltrackball_start(pp->trackballs[pp->current_trackball],
1289                           event->xbutton.x, event->xbutton.y,
1290                           MI_WIDTH(mi), MI_HEIGHT(mi));
1291       return True;
1292     }
1293   }
1294   else if (event->xany.type == MotionNotify && pp->button_pressed)
1295   {
1296     gltrackball_track(pp->trackballs[pp->current_trackball],
1297                       event->xmotion.x, event->xmotion.y,
1298                       MI_WIDTH(mi), MI_HEIGHT(mi));
1299     return True;
1300   }
1301
1302   return False;
1303 }
1304
1305
1306 /*
1307  *-----------------------------------------------------------------------------
1308  *-----------------------------------------------------------------------------
1309  *    Xlock hooks.
1310  *-----------------------------------------------------------------------------
1311  *-----------------------------------------------------------------------------
1312  */
1313
1314 /*
1315  *-----------------------------------------------------------------------------
1316  *    Initialize projectiveplane.  Called each time the window changes.
1317  *-----------------------------------------------------------------------------
1318  */
1319
1320 ENTRYPOINT void init_projectiveplane(ModeInfo *mi)
1321 {
1322   projectiveplanestruct *pp;
1323
1324   MI_INIT(mi, projectiveplane, NULL);
1325   pp = &projectiveplane[MI_SCREEN(mi)];
1326
1327   
1328   pp->trackballs[0] = gltrackball_init(True);
1329   pp->trackballs[1] = gltrackball_init(True);
1330   pp->current_trackball = 0;
1331   pp->button_pressed = False;
1332
1333   /* Set the display mode. */
1334   if (!strcasecmp(mode,"random"))
1335   {
1336     pp->display_mode = random() % NUM_DISPLAY_MODES;
1337   }
1338   else if (!strcasecmp(mode,"wireframe"))
1339   {
1340     pp->display_mode = DISP_WIREFRAME;
1341   }
1342   else if (!strcasecmp(mode,"surface"))
1343   {
1344     pp->display_mode = DISP_SURFACE;
1345   }
1346   else if (!strcasecmp(mode,"transparent"))
1347   {
1348     pp->display_mode = DISP_TRANSPARENT;
1349   }
1350   else
1351   {
1352     pp->display_mode = random() % NUM_DISPLAY_MODES;
1353   }
1354
1355   /* Orientation marks don't make sense in wireframe mode. */
1356   pp->marks = marks;
1357   if (pp->display_mode == DISP_WIREFRAME)
1358     pp->marks = False;
1359
1360   /* Set the appearance. */
1361   if (!strcasecmp(appear,"random"))
1362   {
1363     pp->appearance = random() % NUM_APPEARANCES;
1364   }
1365   else if (!strcasecmp(appear,"solid"))
1366   {
1367     pp->appearance = APPEARANCE_SOLID;
1368   }
1369   else if (!strcasecmp(appear,"distance-bands"))
1370   {
1371     pp->appearance = APPEARANCE_DISTANCE_BANDS;
1372   }
1373   else if (!strcasecmp(appear,"direction-bands"))
1374   {
1375     pp->appearance = APPEARANCE_DIRECTION_BANDS;
1376   }
1377   else
1378   {
1379     pp->appearance = random() % NUM_APPEARANCES;
1380   }
1381
1382   /* Set the color mode. */
1383   if (!strcasecmp(color_mode,"random"))
1384   {
1385     pp->colors = random() % NUM_COLORS;
1386   }
1387   else if (!strcasecmp(color_mode,"two-sided"))
1388   {
1389     pp->colors = COLORS_TWOSIDED;
1390   }
1391   else if (!strcasecmp(color_mode,"distance"))
1392   {
1393     pp->colors = COLORS_DISTANCE;
1394   }
1395   else if (!strcasecmp(color_mode,"direction"))
1396   {
1397     pp->colors = COLORS_DIRECTION;
1398   }
1399   else if (!strcasecmp(color_mode,"depth"))
1400   {
1401     pp->colors = COLORS_DEPTH;
1402   }
1403   else
1404   {
1405     pp->colors = random() % NUM_COLORS;
1406   }
1407
1408   /* Set the view mode. */
1409   if (!strcasecmp(view_mode,"random"))
1410   {
1411     pp->view = random() % NUM_VIEW_MODES;
1412   }
1413   else if (!strcasecmp(view_mode,"walk"))
1414   {
1415     pp->view = VIEW_WALK;
1416   }
1417   else if (!strcasecmp(view_mode,"turn"))
1418   {
1419     pp->view = VIEW_TURN;
1420   }
1421   else if (!strcasecmp(view_mode,"walk-turn"))
1422   {
1423     pp->view = VIEW_WALKTURN;
1424   }
1425   else
1426   {
1427     pp->view = random() % NUM_VIEW_MODES;
1428   }
1429
1430   /* Set the 3d projection mode. */
1431   if (!strcasecmp(proj_3d,"random"))
1432   {
1433     /* Orthographic projection only makes sense in turn mode. */
1434     if (pp->view == VIEW_TURN)
1435       pp->projection_3d = random() % NUM_DISP_3D_MODES;
1436     else
1437       pp->projection_3d = DISP_3D_PERSPECTIVE;
1438   }
1439   else if (!strcasecmp(proj_3d,"perspective"))
1440   {
1441     pp->projection_3d = DISP_3D_PERSPECTIVE;
1442   }
1443   else if (!strcasecmp(proj_3d,"orthographic"))
1444   {
1445     pp->projection_3d = DISP_3D_ORTHOGRAPHIC;
1446   }
1447   else
1448   {
1449     /* Orthographic projection only makes sense in turn mode. */
1450     if (pp->view == VIEW_TURN)
1451       pp->projection_3d = random() % NUM_DISP_3D_MODES;
1452     else
1453       pp->projection_3d = DISP_3D_PERSPECTIVE;
1454   }
1455
1456   /* Set the 4d projection mode. */
1457   if (!strcasecmp(proj_4d,"random"))
1458   {
1459     pp->projection_4d = random() % NUM_DISP_4D_MODES;
1460   }
1461   else if (!strcasecmp(proj_4d,"perspective"))
1462   {
1463     pp->projection_4d = DISP_4D_PERSPECTIVE;
1464   }
1465   else if (!strcasecmp(proj_4d,"orthographic"))
1466   {
1467     pp->projection_4d = DISP_4D_ORTHOGRAPHIC;
1468   }
1469   else
1470   {
1471     pp->projection_4d = random() % NUM_DISP_4D_MODES;
1472   }
1473
1474   /* Modify the speeds to a useful range in walk-and-turn mode. */
1475   if (pp->view == VIEW_WALKTURN)
1476   {
1477     speed_wx *= 0.2;
1478     speed_wy *= 0.2;
1479     speed_wz *= 0.2;
1480     speed_xy *= 0.2;
1481     speed_xz *= 0.2;
1482     speed_yz *= 0.2;
1483   }
1484
1485   /* make multiple screens rotate at slightly different rates. */
1486   pp->speed_scale = 0.9 + frand(0.3);
1487
1488   if ((pp->glx_context = init_GL(mi)) != NULL)
1489   {
1490     reshape_projectiveplane(mi,MI_WIDTH(mi),MI_HEIGHT(mi));
1491     glDrawBuffer(GL_BACK);
1492     init(mi);
1493   }
1494   else
1495   {
1496     MI_CLEARWINDOW(mi);
1497   }
1498 }
1499
1500 /*
1501  *-----------------------------------------------------------------------------
1502  *    Called by the mainline code periodically to update the display.
1503  *-----------------------------------------------------------------------------
1504  */
1505 ENTRYPOINT void draw_projectiveplane(ModeInfo *mi)
1506 {
1507   Display          *display = MI_DISPLAY(mi);
1508   Window           window = MI_WINDOW(mi);
1509   projectiveplanestruct *pp;
1510
1511   if (projectiveplane == NULL)
1512     return;
1513   pp = &projectiveplane[MI_SCREEN(mi)];
1514
1515   MI_IS_DRAWN(mi) = True;
1516   if (!pp->glx_context)
1517     return;
1518
1519   glXMakeCurrent(display,window,*(pp->glx_context));
1520
1521   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
1522   glLoadIdentity();
1523
1524   display_projectiveplane(mi);
1525
1526   if (MI_IS_FPS(mi))
1527     do_fps (mi);
1528
1529   glFlush();
1530
1531   glXSwapBuffers(display,window);
1532 }
1533
1534
1535 #ifndef STANDALONE
1536 ENTRYPOINT void change_projectiveplane(ModeInfo *mi)
1537 {
1538   projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];
1539
1540   if (!pp->glx_context)
1541     return;
1542
1543   glXMakeCurrent(MI_DISPLAY(mi),MI_WINDOW(mi),*(pp->glx_context));
1544   init(mi);
1545 }
1546 #endif /* !STANDALONE */
1547
1548 XSCREENSAVER_MODULE ("ProjectivePlane", projectiveplane)
1549
1550 #endif /* USE_GL */