http://www.tienza.es/crux/src/www.jwz.org/xscreensaver/xscreensaver-5.05.tar.gz
[xscreensaver] / hacks / glx / engine.c
1 /*
2  * engine.c - GL representation of a 4 stroke engine
3  *
4  * version 2.00
5  *
6  * Copyright (C) 2001 Ben Buxton (bb@cactii.net)
7  * modified by Ed Beroset (beroset@mindspring.com)
8  *  new to 2.0 version is:
9  *  - command line argument to specify number of cylinders
10  *  - command line argument to specify included angle of engine
11  *  - removed broken command line argument to specify rotation speed
12  *  - included crankshaft shapes and firing orders for real engines
13  *    verified using the Bosch _Automotive Handbook_, 5th edition, pp 402,403
14  *
15  * Permission to use, copy, modify, distribute, and sell this software and its
16  * documentation for any purpose is hereby granted without fee, provided that
17  * the above copyright notice appear in all copies and that both that
18  * copyright notice and this permission notice appear in supporting
19  * documentation.  No representations are made about the suitability of this
20  * software for any purpose.  It is provided "as is" without express or
21  * implied warranty.
22  */
23
24 #ifdef STANDALONE
25 #define DEFAULTS        "*delay:           30000        \n" \
26                         "*showFPS:         False        \n" \
27                         "*titleFont:  -*-times-bold-r-normal-*-180-*\n" \
28
29 # define refresh_engine 0
30 # include "xlockmore.h"              /* from the xscreensaver distribution */
31 #else  /* !STANDALONE */
32 # include "xlock.h"                  /* from the xlockmore distribution */
33 #endif /* !STANDALONE */
34
35 #include "glxfonts.h"
36 #include "rotator.h"
37 #include "gltrackball.h"
38
39 /* lifted from lament.c */
40 #define RAND(n) ((long) ((random() & 0x7fffffff) % ((long) (n))))
41 #define RANDSIGN() ((random() & 1) ? 1 : -1)
42
43
44 #ifdef USE_GL
45
46 #define DEF_ENGINE "(none)"
47 #define DEF_TITLES "False"
48 #define DEF_SPIN   "True"
49 #define DEF_WANDER "True"
50
51 #undef countof
52 #define countof(x) (sizeof((x))/sizeof((*x)))
53
54 static char *which_engine;
55 static int move;
56 static int spin;
57 static Bool do_titles;
58
59 static XrmOptionDescRec opts[] = {
60   {"-engine",  ".engine.engine", XrmoptionSepArg, DEF_ENGINE },
61   {"-move",    ".engine.move",   XrmoptionNoArg, "True"  },
62   {"+move",    ".engine.move",   XrmoptionNoArg, "False" },
63   {"-spin",    ".engine.spin",   XrmoptionNoArg, "True"  },
64   {"+spin",    ".engine.spin",   XrmoptionNoArg, "False" },
65   { "-titles", ".engine.titles", XrmoptionNoArg, "True"  },
66   { "+titles", ".engine.titles", XrmoptionNoArg, "False" },
67 };
68
69 static argtype vars[] = {
70   {&which_engine, "engine", "Engine", DEF_ENGINE, t_String},
71   {&move,         "move",   "Move",   DEF_WANDER, t_Bool},
72   {&spin,         "spin",   "Spin",   DEF_SPIN,   t_Bool},
73   {&do_titles,    "titles", "Titles", DEF_TITLES, t_Bool},
74 };
75
76 ENTRYPOINT ModeSpecOpt engine_opts = {countof(opts), opts, countof(vars), vars, NULL};
77
78 #ifdef USE_MODULES
79 ModStruct   engine_description =
80 {"engine", "init_engine", "draw_engine", "release_engine",
81  "draw_engine", "init_engine", NULL, &engine_opts,
82  1000, 1, 2, 1, 4, 1.0, "",
83  "A four stroke engine", 0, NULL};
84
85 #endif
86
87 /* these defines are used to provide symbolic means
88  * by which to refer to various portions or multiples
89  * of a cyle in degrees
90  */
91 #define HALFREV 180
92 #define ONEREV 360
93 #define TWOREV 720
94
95 #define MOVE_MULT 0.05
96
97 #define RAND_RANGE(min, max) ((min) + (max - min) * f_rand())
98
99
100 typedef struct {
101   GLXContext *glx_context;
102   Window window;
103   GLfloat x, y, z; /* position */
104   GLfloat dx, dy, dz; /* position */
105   GLfloat an1, an2, an3; /* internal angle */
106   GLfloat nx, ny, nz; /* spin vector */
107   GLfloat a; /* spin angle */
108   GLfloat da; /* spin speed */
109   rotator *rot;
110   trackball_state *trackball;
111   Bool button_down_p;
112   XFontStruct *xfont;
113   GLuint font_dlist;
114   char *engine_name;
115   int engineType;
116   int movepaused;
117
118   float crankOffset;
119   float crankWidth;
120
121   int win_w, win_h;
122
123   float sin_table[TWOREV];
124   float cos_table[TWOREV];
125   float tan_table[TWOREV];
126
127   GLfloat boom_red[4];
128   GLfloat boom_lpos[4];
129   GLfloat boom_d, boom_wd;
130   int boom_time;
131
132   GLfloat viewer[3], lookat[3];
133
134   int display_a;
135   GLfloat ln[730], yp[730], ang[730];
136   int ln_init;
137   int lastPlug;
138
139 } Engine;
140
141 static Engine *engine = NULL;
142
143 static const GLfloat lightpos[] = {7.0, 7.0, 12, 1.0};
144 static const GLfloat light_sp[] = {0.8, 0.8, 0.8, 0.5};
145 static const GLfloat red[] = {1.0, 0, 0, 1.0};
146 static const GLfloat green[] = {0.0, 1, 0, 1.0};
147 static const GLfloat blue[] = {0, 0, 1, 1.0};
148 static const GLfloat white[] = {1.0, 1, 1, 1.0};
149 static const GLfloat yellow_t[] = {1, 1, 0, 0.4};
150
151 static GLvoid normal(GLfloat [], GLfloat [], GLfloat [], 
152                   GLfloat *, GLfloat *, GLfloat *);
153
154 /* 
155  * this table represents both the firing order and included angle of engine.
156  * To simplify things, we always number from 0 starting at the flywheel and 
157  * moving down the crankshaft toward the back of the engine.  This doesn't
158  * always match manufacturer's schemes.  For example, the Porsche 911 engine
159  * is a flat six with the following configuration (Porsche's numbering):
160  *
161  *    3  2  1
162  *  |=            firing order is 1-6-2-4-3-5 in this diagram
163  *     6  5  4
164  *
165  * We renumber these using our scheme but preserve the effective firing order:
166  *
167  *   0  2  4
168  * |=             firing order is 4-1-2-5-0-3 in this diagram
169  *    1  3  5
170  *
171  * To avoid going completely insane, we also reorder these so the newly 
172  * renumbered cylinder 0 is always first: 0-3-4-1-2-5
173  *   
174  * For a flat 6, the included angle is 180 degrees (0 would be a inline
175  * engine).  Because these are all four-stroke engines, each piston goes
176  * through 720 degrees of rotation for each time the spark plug sparks,
177  * so in this case, we would use the following angles:
178  *
179  * cylinder     firing order     angle
180  * --------     ------------     -----
181  *    0               0             0
182  *    1               3           360
183  *    2               4           240
184  *    3               1           600
185  *    4               2           480
186  *    5               5           120
187  *
188  */
189
190 typedef struct 
191 {
192     int cylinders;
193     int includedAngle;
194     int pistonAngle[12];  /* twelve cylinders should suffice... */
195     int speed;          /*  step size in degrees for engine speed */
196     const char *engineName;  /* currently unused */
197 } engine_type;
198
199 static const engine_type engines[] = {
200     { 3,   0, { 0, 240, 480,   0,   0,   0,
201                 0,   0,   0,   0,   0,   0 }, 12,
202      "Honda Insight" },
203     { 4,   0, { 0, 180, 540, 360,   0,   0,
204                 0,   0,   0,   0,   0,   0 }, 12,
205      "BMW M3" },
206     { 4, 180, { 0, 360, 180, 540,   0,   0,
207                 0,   0,   0,   0,   0,   0 }, 12,
208      "VW Beetle" },
209     { 5,   0, { 0, 576, 144, 432, 288,   0,
210                 0,   0,   0,   0,   0,   0 }, 12,
211      "Audi Quattro" },
212     { 6,   0, { 0, 240, 480, 120, 600, 360,
213                 0,   0,   0,   0,   0,   0 }, 12,
214      "BMW M5" },
215     { 6,  90, { 0, 360, 480, 120, 240, 600,
216                 0,   0,   0,   0,   0,   0 }, 12,
217      "Subaru XT" },
218     { 6, 180, { 0, 360, 240, 600, 480, 120,
219                 0,   0,   0,   0,   0,   0 }, 12,
220      "Porsche 911" },
221     { 8,  90, { 0, 450,  90, 180, 270, 360,
222               540, 630,   0,   0,   0,   0 }, 15,
223      "Corvette Z06" },
224     {10,  90, { 0,  72, 432, 504, 288, 360,
225               144, 216, 576, 648,   0,   0 }, 12,
226      "Dodge Viper" },
227     {12,  60, { 0, 300, 240, 540, 480,  60,
228               120, 420, 600, 180, 360, 660 }, 12,
229      "Jaguar XKE" },
230 };
231
232 /* this define is just a little shorter way of referring to members of the 
233  * table above
234  */
235 #define ENG engines[e->engineType]
236
237 /* given a number of cylinders and an included angle, finds matching engine */
238 static int
239 find_engine(char *name)
240 {
241   unsigned int i;
242   char *s;
243
244   if (!name || !*name || !strcasecmp (name, "(none)"))
245     return (random() % countof(engines));
246
247   for (s = name; *s; s++)
248     if (*s == '-' || *s == '_') *s = ' ';
249
250   for (i = 0; i < countof(engines); i++) {
251     if (!strcasecmp(name, engines[i].engineName))
252       return i;
253   }
254
255   fprintf (stderr, "%s: unknown engine type \"%s\"\n", progname, name);
256   fprintf (stderr, "%s: available models are:\n", progname);
257   for (i = 0; i < countof(engines); i++) {
258     fprintf (stderr, "\t %-13s (%d cylinders",
259              engines[i].engineName, engines[i].cylinders);
260     if (engines[i].includedAngle == 0)
261       fprintf (stderr, ")\n");
262     else if (engines[i].includedAngle == 180)
263       fprintf (stderr, ", flat)\n");
264     else
265       fprintf (stderr, ", V)\n");
266   }
267   exit(1);
268 }
269
270 /* we use trig tables to speed things up - 200 calls to sin()
271  in one frame can be a bit harsh..
272 */
273
274 static void make_tables(Engine *e)
275 {
276   int i;
277   float f;
278
279   f = ONEREV / (M_PI * 2);
280   for (i = 0 ; i <= TWOREV ; i++) {
281     e->sin_table[i] = sin(i/f);
282   }
283   for (i = 0 ; i <= TWOREV ; i++) {
284     e->cos_table[i] = cos(i/f);
285   }
286   for (i = 0 ; i <= TWOREV ; i++) {
287     e->tan_table[i] = tan(i/f);
288   }
289 }
290
291 /* if inner and outer are the same, we draw a cylinder, not a tube */
292 /* for a tube, endcaps is 0 (none), 1 (left), 2 (right) or 3(both) */
293 /* angle is how far around the axis to go (up to 360) */
294
295 static void cylinder (Engine *e, GLfloat x, GLfloat y, GLfloat z, 
296     float length, float outer, float inner, int endcaps, int sang, int eang)
297 {
298   int a; /* current angle around cylinder */
299   int b = 0; /* previous */
300   int angle, norm, step, sangle;
301   float z1, y1, z2, y2, ex=0;
302   float y3, z3;
303   float Z1, Y1, Z2, Y2, xl, Y3, Z3;
304   GLfloat y2c[TWOREV], z2c[TWOREV];
305   GLfloat ony, onz; /* previous normals */
306   int nsegs, tube = 0;
307
308   glPushMatrix();
309   nsegs = outer*(MAX(e->win_w, e->win_h)/200);
310   nsegs = MAX(nsegs, 6);
311   nsegs = MAX(nsegs, 40);
312   if (nsegs % 2)
313      nsegs += 1;
314   sangle = sang;
315   angle = eang;
316   ony = onz = 0;
317   z1 = e->cos_table[sangle]*outer+z; y1 = e->sin_table[sangle] * outer+y;
318   Z1 = e->cos_table[sangle] * inner+z; Y1 = e->sin_table[sangle]*inner+y ; 
319   Z2 = z;
320   Y2 = y;
321   xl = x + length;
322   if (inner < outer && endcaps < 3) tube = 1;
323   step = ONEREV/nsegs;
324
325   glBegin(GL_QUADS);
326   for (a = sangle ; a <= angle || b <= angle ; a+= step) {
327     y2=outer*(float)e->sin_table[a]+y;
328     z2=outer*(float)e->cos_table[a]+z;
329     y3=outer*(float)e->sin_table[a+step]+y;
330     z3=outer*(float)e->cos_table[a+step]+z;
331     if (endcaps)
332        y2c[a] = y2; z2c[a] = z2; /* cache for later */
333     if (tube) {
334       Y2=inner*(float)e->sin_table[a]+y;
335       Z2=inner*(float)e->cos_table[a]+z;
336       Y3=inner*(float)e->sin_table[a+step]+y;
337       Z3=inner*(float)e->cos_table[a+step]+z;
338     }
339     glNormal3f(0, y1, z1);
340     glVertex3f(x,y1,z1);
341     glVertex3f(xl,y1,z1);
342     glNormal3f(0, y2, z2);
343     glVertex3f(xl,y2,z2);
344     glVertex3f(x,y2,z2);
345     if (a == sangle && angle - sangle < ONEREV) {
346       if (tube)
347         glVertex3f(x, Y1, Z1);
348       else
349         glVertex3f(x, y, z);
350       glVertex3f(x, y1, z1);
351       glVertex3f(xl, y1, z1);
352       if (tube)
353         glVertex3f(xl, Z1, Z1);
354       else
355         glVertex3f(xl, y, z);
356     }
357     if (tube) {
358       if (endcaps != 1) {
359         glNormal3f(-1, 0, 0); /* left end */
360         glVertex3f(x, y1, z1);
361         glVertex3f(x, y2, z2);
362         glVertex3f(x, Y2, Z2);
363         glVertex3f(x, Y1, Z1);
364       }
365
366       glNormal3f(0, -Y1, -Z1); /* inner surface */
367       glVertex3f(x, Y1, Z1);
368       glVertex3f(xl, Y1, Z1);
369       glNormal3f(0, -Y2, -Z2);
370       glVertex3f(xl, Y2, Z2);
371       glVertex3f(x, Y2, Z2);
372
373       if (endcaps != 2) {
374         glNormal3f(1, 0, 0); /* right end */
375         glVertex3f(xl, y1, z1);
376         glVertex3f(xl, y2, z2);
377         glVertex3f(xl, Y2, Z2);
378         glVertex3f(xl, Y1, Z1);
379       }
380     }
381
382     z1=z2; y1=y2;
383     Z1=Z2; Y1=Y2;
384     b = a;
385   }
386   glEnd();
387
388   if (angle - sangle < ONEREV) {
389     GLfloat nx, ny, nz;
390     GLfloat v1[3], v2[3], v3[3];
391     v1[0] = x; v1[1] = y; v1[2] = z;
392     v2[0] = x; v2[1] = y1; v2[2] = z1;
393     v3[0] = xl; v3[1] = y1; v3[2] = z1;
394     normal(&v2[0], &v1[0], &v3[0], &nx, &ny, &nz);
395     glBegin(GL_QUADS);
396     glNormal3f(nx, ny, nz);
397     glVertex3f(x, y, z);
398     glVertex3f(x, y1, z1);
399     glVertex3f(xl, y1, z1);
400     glVertex3f(xl, y, z);
401     glEnd();
402   }
403   if (endcaps) {
404     GLfloat end, start;
405     if (tube) {
406       if (endcaps == 1) {
407         end = 0;
408         start = 0;
409       } else if (endcaps == 2) {
410         start = end = length+0.01;
411       } else {
412         end = length+0.02; start = -0.01;
413       }
414       norm = (ex == length+0.01) ? -1 : 1;
415     } else  {
416       end = length;
417       start = 0;
418       norm = -1;
419     }
420
421     for(ex = start ; ex <= end ; ex += length) {
422       z1 = outer*e->cos_table[sangle]+z;
423       y1 = y+e->sin_table[sangle]*outer;
424       step = ONEREV/nsegs;
425       glBegin(GL_TRIANGLES);
426       b = 0;
427       for (a = sangle ; a <= angle || b <= angle; a+= step) {
428           glNormal3f(norm, 0, 0);
429           glVertex3f(x+ex,y, z);
430           glVertex3f(x+ex,y1,z1);
431           glVertex3f(x+ex,y2c[a],z2c[a]);
432         y1 = y2c[a]; z1 = z2c[a];
433         b = a;
434       }
435       if (!tube) norm = 1;
436       glEnd();
437     }
438   }
439   glPopMatrix();
440 }
441
442 /* this is just a convenience function to make a solid rod */
443 static void rod (Engine *e, GLfloat x, GLfloat y, GLfloat z, float length, float diameter)
444 {
445     cylinder(e, x, y, z, length, diameter, diameter, 3, 0, ONEREV);
446 }
447
448 static GLvoid normal(GLfloat v1[], GLfloat v2[], GLfloat v3[], 
449                   GLfloat *nx, GLfloat *ny, GLfloat *nz)
450 {
451    GLfloat x, y, z, X, Y, Z;
452
453    x = v2[0]-v1[0];
454    y = v2[1]-v1[1];
455    z = v2[2]-v1[2];
456    X = v3[0]-v1[0];
457    Y = v3[1]-v1[1];
458    Z = v3[2]-v1[2];
459
460    *nx = Y*z - Z*y;
461    *ny = Z*x - X*z;
462    *nz = X*y - Y*x;
463
464
465
466
467
468 static void Rect(GLfloat x, GLfloat y, GLfloat z, GLfloat w, GLfloat h,
469             GLfloat t)
470 {
471   GLfloat yh;
472   GLfloat xw;
473   GLfloat zt;
474
475   yh = y+h; xw = x+w; zt = z - t;
476
477   glBegin(GL_QUADS); /* front */
478     glNormal3f(0, 0, 1);
479     glVertex3f(x, y, z);
480     glVertex3f(x, yh, z);
481     glVertex3f(xw, yh, z);
482     glVertex3f(xw, y, z);
483   /* back */
484     glNormal3f(0, 0, -1);
485     glVertex3f(x, y, zt);
486     glVertex3f(x, yh, zt);
487     glVertex3f(xw, yh, zt);
488     glVertex3f(xw, y, zt);
489   /* top */
490     glNormal3f(0, 1, 0);
491     glVertex3f(x, yh, z);
492     glVertex3f(x, yh, zt);
493     glVertex3f(xw, yh, zt);
494     glVertex3f(xw, yh, z);
495   /* bottom */
496     glNormal3f(0, -1, 0);
497     glVertex3f(x, y, z);
498     glVertex3f(x, y, zt);
499     glVertex3f(xw, y, zt);
500     glVertex3f(xw, y, z);
501   /* left */
502     glNormal3f(-1, 0, 0);
503     glVertex3f(x, y, z);
504     glVertex3f(x, y, zt);
505     glVertex3f(x, yh, zt);
506     glVertex3f(x, yh, z);
507   /* right */
508     glNormal3f(1, 0, 0);
509     glVertex3f(xw, y, z);
510     glVertex3f(xw, y, zt);
511     glVertex3f(xw, yh, zt);
512     glVertex3f(xw, yh, z);
513   glEnd();
514 }
515
516 static void makepiston(Engine *e)
517 {
518   GLfloat colour[] = {0.6, 0.6, 0.6, 1.0};
519   int i;
520   
521   i = glGenLists(1);
522   glNewList(i, GL_COMPILE);
523   glRotatef(90, 0, 0, 1);
524   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colour);
525   glMaterialfv(GL_FRONT, GL_SPECULAR, colour);
526   glMateriali(GL_FRONT, GL_SHININESS, 20);
527   cylinder(e, 0, 0, 0, 2, 1, 0.7, 2, 0, ONEREV); /* body */
528   colour[0] = colour[1] = colour[2] = 0.2;
529   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colour);
530   cylinder(e, 1.6, 0, 0, 0.1, 1.05, 1.05, 0, 0, ONEREV); /* ring */
531   cylinder(e, 1.8, 0, 0, 0.1, 1.05, 1.05, 0, 0, ONEREV); /* ring */
532   glEndList();
533 }
534
535 static void CrankBit(Engine *e, GLfloat x)
536 {
537   Rect(x, -1.4, 0.5, 0.2, 1.8, 1);
538   cylinder(e, x, -0.5, 0, 0.2, 2, 2, 1, 60, 120);
539 }
540
541 static void boom(Engine *e, GLfloat x, GLfloat y, int s)
542 {
543   int flameOut = 720/ENG.speed/ENG.cylinders;
544
545   if (e->boom_time == 0 && s) {
546     e->boom_red[0] = e->boom_red[1] = 0;
547     e->boom_d = 0.05;
548     e->boom_time++;
549     glEnable(GL_LIGHT1); 
550   } else if (e->boom_time == 0 && !s) {
551     return;
552   } else if (e->boom_time >= 8 && e->boom_time < flameOut && !s) {
553     e->boom_time++;
554     e->boom_red[0] -= 0.2; e->boom_red[1] -= 0.1;
555     e->boom_d-= 0.04;
556   } else if (e->boom_time >= flameOut) {
557     e->boom_time = 0;
558     glDisable(GL_LIGHT1);
559     return;
560   } else {
561     e->boom_red[0] += 0.2; e->boom_red[1] += 0.1;
562     e->boom_d += 0.04;
563     e->boom_time++;
564   }
565   e->boom_lpos[0] = x-e->boom_d; e->boom_lpos[1] = y;
566   glLightfv(GL_LIGHT1, GL_POSITION, e->boom_lpos);
567   glLightfv(GL_LIGHT1, GL_DIFFUSE, e->boom_red);
568   glLightfv(GL_LIGHT1, GL_SPECULAR, e->boom_red);
569   glLighti(GL_LIGHT1, GL_LINEAR_ATTENUATION, 1.3);
570   glLighti(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 0);
571
572   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, e->boom_red);
573   e->boom_wd = e->boom_d*3;
574   if (e->boom_wd > 0.7) e->boom_wd = 0.7;
575   glEnable(GL_BLEND);
576   glDepthMask(GL_FALSE);
577   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
578   rod(e, x, y, 0, e->boom_d, e->boom_wd);
579   glDepthMask(GL_TRUE);
580   glDisable(GL_BLEND);
581 }
582
583 static void display(Engine *e)
584 {
585   GLfloat zb, yb;
586   float rightSide;
587   int half;
588   int sides;
589   int j, b;
590
591   glEnable(GL_LIGHTING);
592   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
593   glLoadIdentity();
594   gluLookAt(e->viewer[0], e->viewer[1], e->viewer[2], 
595             e->lookat[0], e->lookat[1], e->lookat[2], 
596             0.0, 1.0, 0.0);
597   glPushMatrix();
598   glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
599   glLightfv(GL_LIGHT0, GL_SPECULAR, light_sp);
600   glLightfv(GL_LIGHT0, GL_DIFFUSE, light_sp);
601
602   if (move) {
603     double x, y, z;
604     get_position (e->rot, &x, &y, &z, !e->button_down_p);
605     glTranslatef(x*16-9, y*14-7, z*16-10);
606   }
607   if (spin) {
608     double x, y, z;
609     gltrackball_rotate (e->trackball);
610     get_rotation(e->rot, &x, &y, &z, !e->button_down_p);
611     glRotatef(x*ONEREV, 1.0, 0.0, 0.0);
612     glRotatef(y*ONEREV, 0.0, 1.0, 0.0);
613     glRotatef(x*ONEREV, 0.0, 0.0, 1.0);
614   }
615
616 /* So the rotation appears around the centre of the engine */
617   glTranslatef(-5, 0, 0); 
618
619 /* crankshaft */
620   glPushMatrix();
621   glRotatef(e->display_a, 1, 0, 0);
622   glCallList(1);
623   glPopMatrix();
624
625   /* init the ln[] matrix for speed */
626   if (e->ln_init == 0) {
627     for (e->ln_init = 0 ; e->ln_init < 730 ; e->ln_init++) {
628       zb = e->sin_table[e->ln_init];
629       yb = e->cos_table[e->ln_init];
630       /* y ordinate of piston */
631       e->yp[e->ln_init] = yb + sqrt(25 - (zb*zb)); 
632       /* length of rod */
633       e->ln[e->ln_init] = sqrt(zb*zb + (yb-e->yp[e->ln_init])*(yb-e->yp[e->ln_init])); 
634       /* angle of connecting rod */
635       e->ang[e->ln_init] = asin(zb/5)*57; 
636       e->ang[e->ln_init] *= -1;
637     }
638   }
639
640   glPushMatrix();
641   sides = (ENG.includedAngle == 0) ? 1 : 2;
642   for (half = 0; half < sides; half++, glRotatef(ENG.includedAngle,1,0,0))
643   {
644     /* pistons */
645       /* glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, white); */
646       for (j = 0; j < ENG.cylinders; j += sides)
647       {
648         b = (e->display_a + ENG.pistonAngle[j+half]) % ONEREV;
649         glPushMatrix();
650         glTranslatef(e->crankWidth/2 + e->crankOffset*(j+half), e->yp[b]-0.3, 0);
651         glCallList(2);
652         glPopMatrix();
653       }
654     /* spark plugs */
655       glPushMatrix();
656       glRotatef(90, 0, 0, 1); 
657       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red);
658       for (j = 0; j < ENG.cylinders; j += sides) 
659       {
660         cylinder(e, 8.5, -e->crankWidth/2-e->crankOffset*(j+half), 0, 
661             0.5, 0.4, 0.3, 1, 0, ONEREV); 
662       }
663       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, white);
664       for (j = 0; j < ENG.cylinders; j += sides)
665       {
666         rod(e, 8, -e->crankWidth/2-e->crankOffset*(j+half), 0, 0.5, 0.2); 
667         rod(e, 9, -e->crankWidth/2-e->crankOffset*(j+half), 0, 1, 0.15); 
668       }   
669
670      /* rod */
671       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
672       for (j = 0; j < ENG.cylinders; j += sides)
673       {
674           b = (e->display_a+HALFREV+ENG.pistonAngle[j+half]) % TWOREV; 
675           glPushMatrix();
676           glRotatef(e->ang[b], 0, 1, 0);
677           rod(e, 
678               -e->cos_table[b],
679               -e->crankWidth/2-e->crankOffset*(j+half),
680               -e->sin_table[b], 
681               e->ln[b], 0.2);
682           glPopMatrix();
683       }
684       glPopMatrix();
685
686         /* engine block */
687       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, yellow_t);
688       glEnable(GL_BLEND);
689       glDepthMask(GL_FALSE);
690       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
691       rightSide = (sides > 1) ? 0 : 1.6;
692     /* left plate */
693       Rect(-e->crankWidth/2, -0.5,  1, 0.2, 9, 2);
694     /* right plate */
695       Rect(0.3+e->crankOffset*ENG.cylinders-rightSide, -0.5, 1, 0.2, 9, 2);
696     /* head plate */
697       Rect(-e->crankWidth/2+0.2, 8.3, 1, 
698             e->crankWidth/2+0.1+e->crankOffset*ENG.cylinders-rightSide, 0.2, 2);
699     /* front rail */
700       Rect(-e->crankWidth/2+0.2, 3, 1, 
701             e->crankWidth/2+0.1+e->crankOffset*ENG.cylinders-rightSide, 0.2, 0.2);
702     /* back rail */
703       Rect(-e->crankWidth/2+0.2, 3, -1+0.2, 
704             e->crankWidth/2+0.1+e->crankOffset*ENG.cylinders-rightSide, 0.2, 0.2);
705     /* plates between cylinders */
706       for (j=0; j < ENG.cylinders - (sides == 1); j += sides)
707         Rect(0.4+e->crankWidth+e->crankOffset*(j-half), 3, 1, 1, 5.3, 2);
708       glDepthMask(GL_TRUE);
709   }
710   glPopMatrix();
711
712         /* see which of our plugs should fire now, if any */
713   for (j = 0; j < ENG.cylinders; j++)
714   {
715     if (0 == ((e->display_a + ENG.pistonAngle[j]) % TWOREV))
716     {
717         glPushMatrix();
718         if (j & 1) 
719             glRotatef(ENG.includedAngle,1,0,0);
720         glRotatef(90, 0, 0, 1); 
721         boom(e, 8, -e->crankWidth/2-e->crankOffset*j, 1); 
722         e->lastPlug = j;
723         glPopMatrix();
724     }
725   }
726
727   if (e->lastPlug != j)
728   {
729     /* this code causes the last plug explosion to dim gradually */
730     if (e->lastPlug & 1) 
731       glRotatef(ENG.includedAngle, 1, 0, 0);
732     glRotatef(90, 0, 0, 1); 
733     boom(e, 8, -e->crankWidth/2-e->crankOffset*e->lastPlug, 0); 
734   }
735   glDisable(GL_BLEND);
736
737   e->display_a += ENG.speed; 
738   if (e->display_a >= TWOREV) 
739     e->display_a = 0;
740   glPopMatrix();
741   glFlush();
742 }
743
744 static void makeshaft (Engine *e)
745 {
746   int i;
747   int j;
748   float crankThick = 0.2;
749   float crankDiam = 0.3;
750
751   i = glGenLists(1);
752   glNewList(i, GL_COMPILE);
753
754   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
755   /* draw the flywheel */
756   cylinder(e, -2.5, 0, 0, 1, 3, 2.5, 0, 0, ONEREV);
757   Rect(-2, -0.3, 2.8, 0.5, 0.6, 5.6);
758   Rect(-2, -2.8, 0.3, 0.5, 5.6, 0.6);
759
760   /* now make each of the shaft bits between the cranks, 
761    * starting from the flywheel end which is at X-coord 0. 
762    * the first cranskhaft bit is always 2 units long 
763    */
764   rod(e, -2, 0, 0, 2, crankDiam);
765
766   /* Each crank is crankWidth units wide and the total width of a
767    * cylinder assembly is 3.3 units. For inline engines, there is just
768    * a single crank per cylinder width.  For other engine
769    * configurations, there is a crank between each pair of adjacent
770    * cylinders on one side of the engine, so the crankOffset length is
771    * halved.
772    */
773   e->crankOffset = 3.3;
774   if (ENG.includedAngle != 0)
775     e->crankOffset /= 2;
776   for (j = 0; j < ENG.cylinders - 1; j++)
777     rod(e,
778         e->crankWidth - crankThick + e->crankOffset*j, 0, 0, 
779         e->crankOffset - e->crankWidth + 2 * crankThick, crankDiam);
780   /* the last bit connects to the engine wall on the non-flywheel end */
781   rod(e, e->crankWidth - crankThick + e->crankOffset*j, 0, 0, 0.9, crankDiam);
782
783
784   for (j = 0; j < ENG.cylinders; j++)
785   {
786     glPushMatrix();
787     if (j & 1)
788         glRotatef(HALFREV+ENG.pistonAngle[j]+ENG.includedAngle,1,0,0);
789     else
790         glRotatef(HALFREV+ENG.pistonAngle[j],1,0,0);
791     /* draw wrist pin */
792     glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
793     rod(e, e->crankOffset*j, -1.0, 0.0, e->crankWidth, crankDiam);
794     glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green);
795     /* draw right part of crank */
796     CrankBit(e, e->crankOffset*j); 
797     /* draw left part of crank */
798     CrankBit(e, e->crankWidth-crankThick+e->crankOffset*j);
799     glPopMatrix();
800   }
801   glEndList();
802 }
803
804
805 ENTRYPOINT void reshape_engine(ModeInfo *mi, int width, int height)
806 {
807  Engine *e = &engine[MI_SCREEN(mi)];
808  glViewport(0,0,(GLint)width, (GLint) height);
809  glMatrixMode(GL_PROJECTION);
810  glLoadIdentity();
811  glFrustum(-1.0,1.0,-1.0,1.0,1.5,70.0);
812  glMatrixMode(GL_MODELVIEW);
813  e->win_h = height; 
814  e->win_w = width;
815 }
816
817
818 ENTRYPOINT void init_engine(ModeInfo *mi)
819 {
820   int screen = MI_SCREEN(mi);
821   Engine *e;
822
823  if (engine == NULL) {
824    if ((engine = (Engine *) calloc(MI_NUM_SCREENS(mi),
825                                         sizeof(Engine))) == NULL)
826           return;
827  }
828  e = &engine[screen];
829  e->window = MI_WINDOW(mi);
830
831  e->x = e->y = e->z = e->a = e->an1 = e->nx = e->ny = e->nz = 
832  e->dx = e->dy = e->dz = e->da = 0;
833
834  if (move) {
835    e->dx = (float)(random() % 1000)/30000;
836    e->dy = (float)(random() % 1000)/30000;
837    e->dz = (float)(random() % 1000)/30000;
838  } else {
839   e->viewer[0] = 0; e->viewer[1] = 2; e->viewer[2] = 18;
840   e->lookat[0] = 0; e->lookat[1] = 0; e->lookat[2] = 0; 
841
842  }
843  if (spin) {
844    e->da = (float)(random() % 1000)/125 - 4;
845    e->nx = (float)(random() % 100) / 100;
846    e->ny = (float)(random() % 100) / 100;
847    e->nz = (float)(random() % 100) / 100;
848  }
849
850  {
851    double spin_speed = 0.5;
852    double wander_speed = 0.01;
853
854  e->crankWidth = 1.5;
855  e->boom_red[3] = 0.9;
856  e->boom_lpos[3] = 1;
857
858  e->viewer[2] = 30;
859
860  e->rot = make_rotator (spin ? spin_speed : 0,
861                         spin ? spin_speed : 0,
862                         spin ? spin_speed : 0,
863                         1.0,
864                         move ? wander_speed : 0,
865                         True);
866
867     e->trackball = gltrackball_init ();
868  }
869
870  if ((e->glx_context = init_GL(mi)) != NULL) {
871       reshape_engine(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
872  } else {
873      MI_CLEARWINDOW(mi);
874  }
875  glClearColor(0.0,0.0,0.0,0.0);
876  glShadeModel(GL_SMOOTH);
877  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
878  glEnable(GL_DEPTH_TEST);
879  glEnable(GL_LIGHTING);
880  glEnable(GL_LIGHT0);
881  glEnable(GL_NORMALIZE);
882  make_tables(e);
883  e->engineType = find_engine(which_engine);
884
885  e->engine_name = malloc(200);
886  sprintf (e->engine_name,
887           "%s\n%s%d%s",
888           engines[e->engineType].engineName,
889           (engines[e->engineType].includedAngle == 0 ? "" :
890            engines[e->engineType].includedAngle == 180 ? "Flat " : "V"),
891           engines[e->engineType].cylinders,
892           (engines[e->engineType].includedAngle == 0 ? " Cylinder" : "")
893           );
894
895  makeshaft(e);
896  makepiston(e);
897  load_font (mi->dpy, "titleFont", &e->xfont, &e->font_dlist);
898 }
899
900 ENTRYPOINT Bool
901 engine_handle_event (ModeInfo *mi, XEvent *event)
902 {
903    Engine *e = &engine[MI_SCREEN(mi)];
904
905    if (event->xany.type == ButtonPress &&
906        event->xbutton.button == Button1)
907    {
908        e->button_down_p = True;
909        gltrackball_start (e->trackball,
910                           event->xbutton.x, event->xbutton.y,
911                           MI_WIDTH (mi), MI_HEIGHT (mi));
912        e->movepaused = 1;
913        return True;
914    }
915    else if (event->xany.type == ButtonRelease &&
916             event->xbutton.button == Button1) {
917        e->button_down_p = False;
918        e->movepaused = 0;
919        return True;
920    }
921   else if (event->xany.type == ButtonPress &&
922            (event->xbutton.button == Button4 ||
923             event->xbutton.button == Button5 ||
924             event->xbutton.button == Button6 ||
925             event->xbutton.button == Button7))
926     {
927       gltrackball_mousewheel (e->trackball, event->xbutton.button, 10,
928                               !!event->xbutton.state);
929       return True;
930     }
931    else if (event->xany.type == MotionNotify &&
932             e->button_down_p) {
933       gltrackball_track (e->trackball,
934                          event->xmotion.x, event->xmotion.y,
935                          MI_WIDTH (mi), MI_HEIGHT (mi));
936       return True;
937    }
938   return False;
939 }
940
941 ENTRYPOINT void draw_engine(ModeInfo *mi)
942 {
943   Engine *e = &engine[MI_SCREEN(mi)];
944   Window w = MI_WINDOW(mi);
945   Display *disp = MI_DISPLAY(mi);
946
947   if (!e->glx_context)
948     return;
949
950   glXMakeCurrent(disp, w, *(e->glx_context));
951
952
953   display(e);
954
955   if (do_titles)
956       print_gl_string (mi->dpy, e->xfont, e->font_dlist,
957                        mi->xgwa.width, mi->xgwa.height,
958                        10, mi->xgwa.height - 10,
959                        e->engine_name);
960
961   if(mi->fps_p) do_fps(mi);
962   glFinish(); 
963   glXSwapBuffers(disp, w);
964 }
965
966 ENTRYPOINT void
967 release_engine(ModeInfo *mi) 
968 {
969   if (engine != NULL) {
970    (void) free((void *) engine);
971    engine = NULL;
972   }
973   FreeAllGL(mi);
974 }
975
976 XSCREENSAVER_MODULE ("Engine", engine)
977
978 #endif