From http://www.jwz.org/xscreensaver/xscreensaver-5.37.tar.gz
[xscreensaver] / hacks / glx / crackberg.c
1 /***************************
2  ** crackberg; Matus Telgarsky [ catachresis@cmu.edu ] 2005 
3  ** */
4 #ifndef HAVE_JWXYZ
5 # define XK_MISCELLANY
6 # include <X11/keysymdef.h>
7 #endif
8
9 #define DEFAULTS    "*delay:        20000       \n" \
10                     "*showFPS:      False       \n" \
11                     "*wireframe:    False       \n" \
12
13 # define refresh_crackberg 0
14 # define release_crackberg 0
15 #undef countof
16 #define countof(x) (sizeof((x))/sizeof((*x)))
17
18 #include "xlockmore.h"
19 #ifdef USE_GL /* whole file */
20
21 #define DEF_NSUBDIVS   "4"
22 #define DEF_BORING     "False"
23 #define DEF_CRACK      "True"
24 #define DEF_WATER      "True"
25 #define DEF_FLAT       "True"
26 #define DEF_COLOR      "random"
27 #define DEF_LIT        "True"
28 #define DEF_VISIBILITY "0.6"
29 #define DEF_LETTERBOX  "False"
30
31
32 /***************************
33  ** macros
34  ** */
35
36 #define M_RAD7_4        0.661437827766148
37 #define M_SQRT3_2       0.866025403784439
38 #define M_PI_180        0.0174532925199433
39 #define M_180_PI        57.2957795130823
40 #define MSPEED_SCALE    1.1
41 #define AVE3(a,b,c)     ( ((a) + (b) + (c)) / 3.0 )
42 #define MAX_ZDELTA      0.35
43 #define DISPLACE(h,d)   (h+(random()/(double)RAND_MAX-0.5)*2*MAX_ZDELTA/(1<<d))
44 #define MEAN(x,y)       ( ((x) + (y)) / 2.0 )
45 #define TCOORD(x,y)     (cberg->heights[(cberg->epoints * (y) - ((y)-1)*(y)/2 + (x))])
46 #define sNCOORD(x,y,p)  (cberg->norms[3 * (cberg->epoints * (y) - ((y)-1)*(y)/2 + (x)) + (p)])
47 #define SET_sNCOORD(x,y, down, a,b,c,d,e,f)   \
48     sNCOORD(x,y,0) = AVE3(a-d, 0.5 * (b-e), -0.5 * (c-f)); \
49     sNCOORD(x,y,1) = ((down) ? -1 : +1) * AVE3(0.0, M_SQRT3_2 * (b-e), M_SQRT3_2 * (c-f)); \
50     sNCOORD(x,y,2) = (2*dx)
51 #define fNCOORD(x,y,w,p)  \
52     (cberg->norms[3 * (2*(y)*cberg->epoints-((y)+1)*((y)+1) + 1 + 2 * ((x)-1) + (w)) + (p)])
53 #define SET_fNCOORDa(x,y, down, dz00,dz01) \
54     fNCOORD(x,y,0,0) = (down) * (dy) * (dz01); \
55     fNCOORD(x,y,0,1) = (down) * ((dz01) * (dx) / 2 - (dx) * (dz00)); \
56     fNCOORD(x,y,0,2) = (down) * (dx) * (dy)
57 #define SET_fNCOORDb(x,y, down, dz10,dz11) \
58     fNCOORD(x,y,1,0) = (down) * (dy) * (dz10); \
59     fNCOORD(x,y,1,1) = (down) * ((dz11) * (dx) - (dx) * (dz10) / 2); \
60     fNCOORD(x,y,1,2) = (down) * (dx) * (dy)
61
62
63 /***************************
64  ** types
65  ** */
66
67
68 typedef struct _cberg_state cberg_state;
69 typedef struct _Trile Trile;
70
71 typedef struct {
72     void (*init)(Trile *);
73     void (*free)(Trile *);
74     void (*draw)(Trile *);
75     void (*init_iter)(Trile *, cberg_state *);
76     void (*dying_iter)(Trile *, cberg_state *);
77 } Morph;
78
79 typedef struct {
80     char *id;
81     void (*land)(cberg_state *, double);
82     void (*water)(cberg_state *, double);
83     double bg[4];
84 } Color;
85
86 enum { TRILE_NEW, TRILE_INIT, TRILE_STABLE, TRILE_DYING, TRILE_DELETE };
87
88 struct _Trile {
89     int x,y; /*center coords; points up if (x+y)%2 == 0, else down*/
90     short state;
91     short visible;
92     double *l,*r,*v; /*only edges need saving*/
93     GLuint call_list;
94
95     void *morph_data;
96     const Morph *morph;
97
98     struct _Trile *left, *right, *parent; /* for bst, NOT spatial */
99     struct _Trile *next_free; /* for memory allocation */
100 };
101
102 enum { MOTION_AUTO = 0, MOTION_MANUAL = 1, MOTION_LROT= 2,    MOTION_RROT = 4,
103        MOTION_FORW = 8,   MOTION_BACK = 16,  MOTION_DEC = 32, MOTION_INC = 64,
104        MOTION_LEFT = 128, MOTION_RIGHT = 256 };
105
106 struct _cberg_state {
107     GLXContext *glx_context;
108     Trile *trile_head;
109     
110     double x,y,z, yaw,roll,pitch, dx,dy,dz, dyaw,droll,dpitch, elapsed;
111     double prev_frame;
112     int motion_state;
113     double mspeed;
114
115     double fovy, aspect, zNear, zFar;
116
117     const Color *color;
118
119     int count;
120
121     unsigned int epoints, /*number of points to one edge*/
122                  tpoints, /*number points total*/
123                  ntris,   /*number triangles per trile*/
124                  tnorms;  /*number of normals*/
125
126     double *heights, *norms;
127     Trile *free_head; /* for trile_[alloc|free] */
128
129     double draw_elapsed;
130
131     double dx0;
132
133     double vs0r,vs0g,vs0b, vs1r, vs1g, vs1b,
134            vf0r,vf0g,vf0b, vf1r, vf1g, vf1b;
135
136     Bool button_down_p;
137     int mouse_x, mouse_y;
138     struct timeval paused;
139 };
140
141
142
143 /***************************
144  ** globals
145  ** */
146
147 static unsigned int nsubdivs;
148 static Bool crack, boring, do_water, flat, lit, letterbox;
149 static float visibility;
150 static char *color;
151
152 static cberg_state *cbergs = NULL;
153
154 static XrmOptionDescRec opts[] = {
155   {"-nsubdivs",   ".nsubdivs",   XrmoptionSepArg, 0},
156   {"-boring",     ".boring",     XrmoptionNoArg,  "True"},
157   {"-crack",      ".crack",      XrmoptionNoArg,  "True"},
158   {"-no-crack",   ".crack",      XrmoptionNoArg,  "False"},
159   {"-water",      ".water",      XrmoptionNoArg,  "True"},
160   {"-no-water",   ".water",      XrmoptionNoArg,  "False"},
161   {"-flat",       ".flat",       XrmoptionNoArg,  "True"},
162   {"-no-flat",    ".flat",       XrmoptionNoArg,  "False"},
163   {"-color",      ".color",      XrmoptionSepArg, 0},
164   {"-lit",        ".lit",        XrmoptionNoArg,  "True"},
165   {"-no-lit",     ".lit",        XrmoptionNoArg,  "False"},
166   {"-visibility", ".visibility", XrmoptionSepArg, 0},
167   {"-letterbox",  ".letterbox",  XrmoptionNoArg,  "True"}
168 };
169
170 static argtype vars[] = {
171   {&nsubdivs,   "nsubdivs",   "nsubdivs",   DEF_NSUBDIVS,   t_Int},
172   {&boring,     "boring",     "boring",     DEF_BORING,     t_Bool},
173   {&crack,      "crack",      "crack",      DEF_CRACK,      t_Bool},
174   {&do_water,   "water",      "water",      DEF_WATER,      t_Bool},
175   {&flat,       "flat",       "flat",       DEF_FLAT,       t_Bool},
176   {&color,      "color",      "color",      DEF_COLOR,      t_String},
177   {&lit,        "lit",        "lit",        DEF_LIT,        t_Bool},
178   {&visibility, "visibility", "visibility", DEF_VISIBILITY, t_Float},
179   {&letterbox,  "letterbox",  "letterbox",  DEF_LETTERBOX,  t_Bool}
180 };
181
182 ENTRYPOINT ModeSpecOpt crackberg_opts = {countof(opts), opts, countof(vars), vars, NULL};
183
184
185 /***************************
186  ** Trile functions. 
187  **  first come all are regular trile functions 
188  ** */
189
190
191 /* forward decls for trile_new */
192 static Trile *triles_find(Trile *tr, int x, int y);
193 static Trile *trile_alloc(cberg_state *cberg);
194 static const Morph *select_morph(void);
195 static const Color *select_color(cberg_state *);
196
197 static void trile_calc_sides(cberg_state *cberg, 
198                              Trile *new, int x, int y, Trile *root)
199 {
200     unsigned int i,j,k; 
201     int dv = ( (x + y) % 2 ? +1 : -1); /* we are pointing down or up*/
202     Trile *l, *r, *v; /* v_ertical */
203
204
205     if (root) {
206         l = triles_find(root, x-1, y);
207         r = triles_find(root, x+1, y);  
208         v = triles_find(root, x,y+dv); 
209     } else
210         l = r = v = NULL;
211
212     if (v) {
213         for (i = 0; i != cberg->epoints; ++i)
214             new->v[i] = v->v[i];
215     } else {
216         if (l)          new->v[0] = l->l[0];
217         else if (!root) new->v[0] = DISPLACE(0,0);
218         else { 
219             Trile *tr; /* all of these tests needed.. */
220             if ( (tr = triles_find(root, x-1, y + dv)) )
221                 new->v[0] = tr->l[0];
222             else if ( (tr = triles_find(root, x-2, y)) )
223                 new->v[0] = tr->r[0];
224             else if ( (tr = triles_find(root, x-2, y + dv)) )
225                 new->v[0] = tr->r[0];
226             else
227                 new->v[0] = DISPLACE(0,0);
228         }
229
230         if (r)          new->v[cberg->epoints-1] = r->l[0];
231         else if (!root) new->v[cberg->epoints-1] = DISPLACE(0,0);
232         else {
233             Trile *tr;
234             if ( (tr = triles_find(root, x+1, y + dv)) )
235                 new->v[cberg->epoints-1] = tr->l[0];
236             else if ( (tr = triles_find(root, x+2, y)) )
237                 new->v[cberg->epoints-1] = tr->v[0];
238             else if ( (tr = triles_find(root, x+2, y + dv)) )
239                 new->v[cberg->epoints-1] = tr->v[0];
240             else
241                 new->v[cberg->epoints-1] = DISPLACE(0,0);
242         }
243
244         for (i = ((1 << nsubdivs) >> 1), k =1; i; i >>= 1, ++k)
245             for (j = i; j < cberg->epoints; j += i * 2)
246                 new->v[j] = DISPLACE(MEAN(new->v[j-i], new->v[j+i]), k);
247     }
248         
249     if (l) {
250         for (i = 0; i != cberg->epoints; ++i)
251             new->l[i] = l->r[i];
252     } else {
253         if (r)          new->l[0] = r->v[0];
254         else if (!root) new->l[0] = DISPLACE(0,0);
255         else {
256             Trile *tr;
257             if ( (tr = triles_find(root, x-1, y-dv)) )
258                 new->l[0] = tr->r[0];
259             else if ( (tr = triles_find(root, x+1, y-dv)) )
260                 new->l[0] = tr->v[0];
261             else if ( (tr = triles_find(root, x, y-dv)) )
262                 new->l[0] = tr->l[0];
263             else 
264                 new->l[0] = DISPLACE(0,0);
265         }
266
267         new->l[cberg->epoints - 1] = new->v[0];
268
269         for (i = ((1 << nsubdivs) >> 1), k =1; i; i >>= 1, ++k)
270             for (j = i; j < cberg->epoints; j += i * 2)
271                 new->l[j] = DISPLACE(MEAN(new->l[j-i], new->l[j+i]), k);
272     }
273
274     if (r) {
275         for (i = 0; i != cberg->epoints; ++i)
276             new->r[i] = r->l[i];
277     } else {
278         new->r[0] = new->v[cberg->epoints - 1];
279         new->r[cberg->epoints - 1] = new->l[0];
280
281         for (i = ((1 << nsubdivs) >> 1), k =1; i; i >>= 1, ++k)
282             for (j = i; j < cberg->epoints; j += i * 2)
283                 new->r[j] = DISPLACE(MEAN(new->r[j-i], new->r[j+i]), k);
284     }
285 }
286
287 static void trile_calc_heights(cberg_state *cberg, Trile *new)
288 {
289     unsigned int i, j, k, h;
290
291     for (i = 0; i < cberg->epoints - 1; ++i) { /* copy in sides */
292         TCOORD(i,0) = new->v[i];
293         TCOORD(cberg->epoints - 1 - i, i) = new->r[i];
294         TCOORD(0, cberg->epoints - 1 - i) = new->l[i];
295     }
296
297     for (i = ((1 << nsubdivs) >> 2), k =1; i; i >>= 1, ++k)
298         for (j = 1; j < (1 << k); ++j)
299             for (h = 1; h <= (1<<k) - j; ++h) {
300                 TCOORD( i*(2*h - 1), i*(2*j - 1) ) = /*rights*/
301                   DISPLACE(MEAN(TCOORD( i*(2*h - 2), i*(2*j + 0) ),
302                                 TCOORD( i*(2*h + 0), i*(2*j - 2) )), k);
303
304                 TCOORD( i*(2*h + 0), i*(2*j - 1) ) = /*lefts*/
305                   DISPLACE(MEAN(TCOORD( i*(2*h + 0), i*(2*j - 2) ),
306                                 TCOORD( i*(2*h + 0), i*(2*j + 0) )), k);
307
308                 TCOORD( i*(2*h - 1), i*(2*j + 0) ) = /*verts*/
309                   DISPLACE(MEAN(TCOORD( i*(2*h - 2), i*(2*j + 0) ),
310                                 TCOORD( i*(2*h + 0), i*(2*j + 0) )), k);
311             }
312 }
313
314 static void trile_calc_flat_norms(cberg_state *cberg, Trile *new)
315 {
316     unsigned int x, y;
317     int down = (((new->x + new->y) % 2) ? -1 : +1);
318     double dz00,dz01,dz10,dz11, a,b,c,d;
319     double dy = down * M_SQRT3_2 / (1 << nsubdivs);
320     double dx = cberg->dx0;
321
322     for (y = 0; y < cberg->epoints - 1; ++y) {
323         a = TCOORD(0,y);
324         b = TCOORD(0,y+1);
325         for (x = 1; x < cberg->epoints - 1 - y; ++x) {
326             c = TCOORD(x,y);
327             d = TCOORD(x,y+1);
328
329             dz00 = b-c;
330             dz01 = a-c;
331             dz10 = b-d;
332             dz11 = c-d;
333             
334             SET_fNCOORDa(x,y, down, dz00,dz01);
335             SET_fNCOORDb(x,y, down, dz10,dz11);
336
337             a = c;
338             b = d;
339         }
340
341         c = TCOORD(x,y);
342         dz00 = b-c;
343         dz01 = a-c;
344         SET_fNCOORDa(x,y, down, dz00, dz01);
345     }
346 }
347
348 static void trile_calc_smooth_norms(cberg_state *cberg, Trile *new)
349 {
350     unsigned int i,j, down = (new->x + new->y) % 2;
351     double prev, cur, next;
352     double dx = cberg->dx0;
353
354     /** corners -- assume level (bah) **/
355     cur = TCOORD(0,0);
356     SET_sNCOORD(0,0, down,
357         cur,cur,TCOORD(0,1),TCOORD(1,0),cur,cur);
358     cur = TCOORD(cberg->epoints-1,0);
359     SET_sNCOORD(cberg->epoints-1,0, down,
360         TCOORD(cberg->epoints-2,0),TCOORD(cberg->epoints-2,1),cur,cur,cur,cur);
361     cur = TCOORD(0,cberg->epoints-1);
362     SET_sNCOORD(0,cberg->epoints-1, down,
363         cur,cur,cur,cur,TCOORD(1,cberg->epoints-2),TCOORD(0,cberg->epoints-2));
364
365
366     /** sides **/
367     /* vert */
368     prev = TCOORD(0,0);
369     cur = TCOORD(1,0);
370     for (i = 1; i < cberg->epoints - 1; ++i) {
371         next = TCOORD(i+1,0);
372         SET_sNCOORD(i,0, down, prev,TCOORD(i-1,1),TCOORD(i,1), next,cur,cur);
373         prev = cur;
374         cur = next;
375     }
376
377     /* right */
378     prev = TCOORD(cberg->epoints-1,0);
379     cur = TCOORD(cberg->epoints-2,0);
380     for (i = 1; i < cberg->epoints - 1; ++i) {
381         next = TCOORD(cberg->epoints-i-2,i+1);
382         SET_sNCOORD(cberg->epoints-i-1,i, down, TCOORD(cberg->epoints-i-2,i),next,cur,
383                                         cur,prev,TCOORD(cberg->epoints-i-1,i-1));
384         prev = cur;
385         cur = next;
386     }
387         
388     /* left */
389     prev = TCOORD(0,0);
390     cur = TCOORD(0,1);
391     for (i = 1; i < cberg->epoints - 1; ++i) {
392         next = TCOORD(0,i+1);
393         SET_sNCOORD(0,i, down, cur,cur,next,TCOORD(1,i),TCOORD(1,i-1),prev);
394         prev = cur;
395         cur = next;
396     }
397
398
399     /** fill in **/
400     for (i = 1; i < cberg->epoints - 2; ++i) {
401         prev = TCOORD(0,i);
402         cur = TCOORD(1,i);
403         for (j = 1; j < cberg->epoints - i - 1; ++j) {
404             next = TCOORD(j+1,i);
405             SET_sNCOORD(j,i, down, prev,TCOORD(j-1,i+1),TCOORD(j,i+1),
406                             next,TCOORD(j+1,i-1),TCOORD(j,i-1));
407             prev = cur;
408             cur = next;
409         }
410     }
411 }
412
413 static inline void trile_light(cberg_state *cberg, 
414                                unsigned int x, unsigned int y, 
415                                unsigned int which)
416 {
417     if (flat) {
418         if (x) {
419             glNormal3d(fNCOORD(x,y,which,0),
420                        fNCOORD(x,y,which,1),
421                        fNCOORD(x,y,which,2));
422         } else { /* I get mesa errors and bizarre glitches without this!! */
423             glNormal3d(fNCOORD(1,y,0,0),
424                        fNCOORD(1,y,0,1),
425                        fNCOORD(1,y,0,2));
426         }
427     } else {
428         glNormal3d(sNCOORD(x,y+which,0),
429                    sNCOORD(x,y+which,1),
430                    sNCOORD(x,y+which,2));
431     }
432 }
433
434 static inline void trile_draw_vertex(cberg_state *cberg, unsigned int ix,
435     unsigned int iy, unsigned int which, double x,double y,
436     double zcur, double z1, double z2)
437 {
438     glColor3d(0.0, 0.0, 0.0); /* don't ask. my card breaks otherwise. */
439     
440     if (do_water && zcur <= 0.0) {
441         cberg->color->water(cberg, zcur); /* XXX use average-of-3 for color when flat?*/
442         if (lit) glNormal3d(0.0,0.0,1.0);
443         glVertex3d(x, y, 0.0); 
444     } else {
445         cberg->color->land(cberg, zcur);
446         if (lit) trile_light(cberg,ix,iy,which);
447         glVertex3d(x, y, zcur);
448     }
449 }
450
451 static void trile_render(cberg_state *cberg, Trile *new)
452 {
453     double cornerx = 0.5 * new->x - 0.5, cornery;
454     double dy = M_SQRT3_2 / (1 << nsubdivs);
455     double z0,z1,z2;
456     int x,y;
457
458     new->call_list = glGenLists(1);
459     glNewList(new->call_list, GL_COMPILE);
460
461         if ((new->x + new->y) % 2) { /*point down*/
462             cornery = (new->y + 0.5)*M_SQRT3_2;
463             glFrontFace(GL_CW);
464             dy = -dy;
465         } else
466             cornery = (new->y - 0.5) * M_SQRT3_2;
467
468         for (y = 0; y < cberg->epoints - 1; ++y) {
469             double dx = cberg->dx0;
470             glBegin(GL_TRIANGLE_STRIP);
471                 /* first three points all part of the same triangle.. */
472                 z0 = TCOORD(0,y);
473                 z1 = TCOORD(0,y+1);
474                 z2 = TCOORD(1,y);
475                 trile_draw_vertex(cberg, 0,y,0,
476                   cornerx,cornery, z0, z1, z2);
477                 trile_draw_vertex(cberg, 0,y,1,
478                   cornerx+0.5*dx,cornery+dy, z1, z0, z2);
479
480                 for (x = 1; x < cberg->epoints - 1 - y; ++x) {
481                     trile_draw_vertex(cberg, x,y,0,
482                       cornerx+x*dx,cornery, z2, z1, z0);
483
484                     z0 = TCOORD(x, y+1);
485
486                     trile_draw_vertex(cberg, x,y,1,
487                       cornerx+(x+0.5)*dx,cornery+dy, z0, z2, z1);
488
489                     z1 = z0;
490                     z0 = z2;
491                     z2 = TCOORD(x+1,y);
492                 }
493                 trile_draw_vertex(cberg, x,y,0,
494                   cornerx + x*dx, cornery, z2, z1, z0);
495             glEnd();
496
497             cornerx += dx/2;
498             cornery += dy;
499         }
500
501         if ((new->x + new->y) % 2) /*point down*/
502             glFrontFace(GL_CCW);
503     glEndList();
504 }
505
506 static Trile *trile_new(cberg_state *cberg, int x,int y,Trile *parent,Trile *root)
507 {
508     Trile *new;
509
510     new = trile_alloc(cberg);
511
512     new->x = x;
513     new->y = y;
514     new->state = TRILE_NEW;
515     new->parent = parent;
516     new->left = new->right = NULL;
517     new->visible = 1;
518
519     new->morph = select_morph();
520     new->morph->init(new);
521
522     trile_calc_sides(cberg, new, x, y, root);
523     trile_calc_heights(cberg, new);
524
525     if (lit) {
526         if (flat)   trile_calc_flat_norms(cberg, new);
527         else        trile_calc_smooth_norms(cberg, new);
528     }
529
530     trile_render(cberg, new);
531     return new;
532 }
533
534 static Trile *trile_alloc(cberg_state *cberg)
535 {
536     Trile *new;
537
538     if (cberg->free_head) {
539         new = cberg->free_head;
540         cberg->free_head = cberg->free_head->next_free;
541     } else {
542         ++cberg->count;
543         if (!(new = malloc(sizeof(Trile)))
544          || !(new->l = (double *) malloc(sizeof(double) * cberg->epoints * 3))) {
545             perror(progname);
546             exit(1);
547         }
548         new->r = new->l + cberg->epoints;
549         new->v = new->r + cberg->epoints;
550 #ifdef DEBUG
551         printf("needed to alloc; [%d]\n", cberg->count);
552 #endif
553     }
554     return new;
555 }
556
557 static void trile_free(cberg_state *cberg, Trile *tr)
558 {
559     glDeleteLists(tr->call_list, 1);
560     tr->morph->free(tr);
561     tr->next_free = cberg->free_head;
562     cberg->free_head = tr;
563 }
564
565
566 static void trile_draw_vanilla(Trile *tr)
567 { glCallList(tr->call_list); }
568
569 static void trile_draw(Trile *tr, void *ignore)
570 {
571     if (tr->state == TRILE_STABLE)
572         trile_draw_vanilla(tr);
573     else
574         tr->morph->draw(tr);
575 }
576
577
578 /***************************
579  ** Trile morph functions. 
580  **  select function at bottom (forward decls sucls) 
581  ** */
582
583
584 /*** first the basic growing morph */
585
586 static void grow_init(Trile *tr)
587 {
588     tr->morph_data = (void *) malloc(sizeof(double));
589     *((double *)tr->morph_data) = 0.02; /* not 0; avoid normals crapping */
590 }
591
592 static void grow_free(Trile *tr)
593 {
594     free(tr->morph_data);
595 }
596
597 static void grow_draw(Trile *tr)
598 {
599     glPushMatrix();
600         glScaled(1.0,1.0, *((double *)tr->morph_data));
601         trile_draw_vanilla(tr);
602     glPopMatrix();
603 }
604
605 static void grow_init_iter(Trile *tr, cberg_state *cberg)
606 {
607     *((double *)(tr->morph_data)) = *((double *)tr->morph_data) + cberg->elapsed;
608     if (*((double *)tr->morph_data) >= 1.0)
609         tr->state = TRILE_STABLE;
610 }
611
612 static void grow_dying_iter(Trile *tr, cberg_state *cberg)
613 {
614     *((double *)tr->morph_data) = *((double *)tr->morph_data) - cberg->elapsed;
615     if (*((double *)tr->morph_data) <= 0.02) /* XXX avoid fast del/cons? */
616         tr->state = TRILE_DELETE;
617 }
618
619 /**** falling morph ****/
620
621 static void fall_init(Trile *tr)
622 {
623     tr->morph_data = (void *) malloc(sizeof(double));
624     *((double *)tr->morph_data) = 0.0;
625 }
626
627 static void fall_free(Trile *tr)
628 {
629     free(tr->morph_data);
630 }
631
632 static void fall_draw(Trile *tr)
633 {
634     glPushMatrix();
635         glTranslated(0.0,0.0,(0.5 - *((double *)tr->morph_data)) * 8);
636         trile_draw_vanilla(tr);
637     glPopMatrix();
638 }
639
640 static void fall_init_iter(Trile *tr, cberg_state *cberg)
641 {
642     *((double *)(tr->morph_data)) = *((double *)tr->morph_data) + cberg->elapsed;
643     if (*((double *)tr->morph_data) >= 0.5)
644         tr->state = TRILE_STABLE;
645 }
646
647 static void fall_dying_iter(Trile *tr, cberg_state *cberg)
648 {
649     *((double *)tr->morph_data) = *((double *)tr->morph_data) - cberg->elapsed;
650     if (*((double *)tr->morph_data) <= 0.0) /* XXX avoid fast del/cons? */
651         tr->state = TRILE_DELETE;
652 }
653
654 /**** yeast morph ****/
655
656 static void yeast_init(Trile *tr)
657 {
658     tr->morph_data = (void *) malloc(sizeof(double));
659     *((double *)tr->morph_data) = 0.02;
660 }
661
662 static void yeast_free(Trile *tr)
663 {
664     free(tr->morph_data);
665 }
666
667 static void yeast_draw(Trile *tr)
668 {
669     double x = tr->x * 0.5,
670            y = tr->y * M_SQRT3_2,
671            z = *((double *)tr->morph_data);
672
673     glPushMatrix();
674         glTranslated(x, y, 0);
675         glRotated(z*360, 0,0,1);
676         glScaled(z,z,z);
677         glTranslated(-x, -y, 0);
678         trile_draw_vanilla(tr);
679     glPopMatrix();
680 }
681
682 static void yeast_init_iter(Trile *tr, cberg_state *cberg)
683 {
684     *((double *)(tr->morph_data)) = *((double *)tr->morph_data) + cberg->elapsed;
685     if (*((double *)tr->morph_data) >= 1.0)
686         tr->state = TRILE_STABLE;
687 }
688
689 static void yeast_dying_iter(Trile *tr, cberg_state *cberg)
690 {
691     *((double *)tr->morph_data) = *((double *)tr->morph_data) - cberg->elapsed;
692     if (*((double *)tr->morph_data) <= 0.02) /* XXX avoid fast del/cons? */
693         tr->state = TRILE_DELETE;
694 }
695
696 /**** identity morph ****/
697
698 static void identity_init(Trile *tr)
699 { tr->state = TRILE_STABLE; }
700
701 static void identity_free(Trile *tr)
702 {}
703
704 static void identity_draw(Trile *tr)
705 { trile_draw_vanilla(tr); }
706
707 static void identity_init_iter(Trile *tr, cberg_state *cberg)
708 {}
709
710 static void identity_dying_iter(Trile *tr, cberg_state *cberg)
711 { tr->state = TRILE_DELETE; }
712
713 /** now to handle selection **/
714
715 static const Morph morphs[] = {
716     {grow_init, grow_free, grow_draw, grow_init_iter, grow_dying_iter},
717     {fall_init, fall_free, fall_draw, fall_init_iter, fall_dying_iter},
718     {yeast_init, yeast_free, yeast_draw, yeast_init_iter, yeast_dying_iter},
719     {identity_init,  /*always put identity last to skip it..*/
720         identity_free, identity_draw, identity_init_iter, identity_dying_iter}
721 };    
722
723 static const Morph *select_morph()
724
725     int nmorphs = countof(morphs);
726     if (crack)
727         return &morphs[random() % (nmorphs-1)]; 
728     else if (boring)
729         return &morphs[nmorphs-1]; 
730     else
731         return morphs;
732 }
733
734
735 /***************************
736  ** Trile superstructure functions. 
737  **  */
738
739
740 static void triles_set_visible(cberg_state *cberg, Trile **root, int x, int y)
741 {
742     Trile *parent = NULL, 
743           *iter = *root;
744     int goleft=0;
745
746     while (iter != NULL) {
747         parent = iter;
748         goleft = (iter->x > x || (iter->x == x && iter->y > y));
749         if (goleft)
750             iter = iter->left;
751         else if (iter->x == x && iter->y == y) {
752             iter->visible = 1;
753             return;
754         } else
755             iter = iter->right;
756     }
757
758     if (parent == NULL)
759         *root = trile_new(cberg, x,y, NULL, NULL);
760     else if (goleft)
761         parent->left = trile_new(cberg, x,y, parent, *root);
762     else
763         parent->right = trile_new(cberg, x,y, parent, *root);
764 }
765
766 static unsigned int triles_foreach(Trile *root, void (*f)(Trile *, void *), 
767   void *data)
768 {
769     if (root == NULL) 
770         return 0;
771     
772     f(root, data);
773     return 1 + triles_foreach(root->left, f, data) 
774       + triles_foreach(root->right, f, data);
775 }
776
777 static void triles_update_state(Trile **root, cberg_state *cberg)
778 {
779     int process_current = 1;
780     if (*root == NULL)
781         return;
782
783     while (process_current) {
784         if ( (*root)->visible ) {
785             if ( (*root)->state == TRILE_INIT )
786                 (*root)->morph->init_iter(*root, cberg);
787             else if ( (*root)->state == TRILE_DYING ) {
788                 (*root)->state = TRILE_INIT;
789                 (*root)->morph->init_iter(*root, cberg);
790             } else if ( (*root)->state == TRILE_NEW ) 
791                 (*root)->state = TRILE_INIT;
792
793             (*root)->visible = 0;
794         } else {
795             if ( (*root)->state == TRILE_STABLE )
796                 (*root)->state = TRILE_DYING;
797             else if ( (*root)->state == TRILE_INIT ) {
798                 (*root)->state = TRILE_DYING;
799                 (*root)->morph->dying_iter(*root, cberg);
800             } else if ( (*root)->state == TRILE_DYING )
801                 (*root)->morph->dying_iter(*root, cberg);
802         }
803
804         if ( (*root)->state == TRILE_DELETE ) {
805             Trile *splice_me;
806             process_current = 1;
807
808             if ((*root)->left == NULL) {
809                 splice_me = (*root)->right;
810                 if (splice_me)
811                     splice_me->parent = (*root)->parent;
812                 else 
813                     process_current = 0;
814             } else if ((*root)->right == NULL) {
815                 splice_me = (*root)->left;
816                 splice_me->parent = (*root)->parent;
817             } else {
818                 Trile *tmp;
819                 for (splice_me = (*root)->right; splice_me->left != NULL; )
820                     splice_me = splice_me->left;
821                 tmp = splice_me->right;
822
823                 if (tmp) tmp->parent = splice_me->parent;
824
825                 if (splice_me == splice_me->parent->left)
826                     splice_me->parent->left = tmp;
827                 else
828                     splice_me->parent->right = tmp;
829
830                 splice_me->parent = (*root)->parent;
831                 splice_me->left = (*root)->left;
832                 (*root)->left->parent = splice_me;
833                 splice_me->right = (*root)->right;
834                 if ((*root)->right)
835                     (*root)->right->parent = splice_me;
836             }
837             trile_free(cberg, *root);
838             *root = splice_me;
839         } else
840             process_current = 0;
841     }
842
843     if (*root) {
844         triles_update_state(&((*root)->left), cberg);
845         triles_update_state(&((*root)->right), cberg);
846     } 
847 }
848
849 static Trile *triles_find(Trile *tr, int x, int y)
850 {
851     while (tr && !(tr->x == x && tr->y == y))
852         if (x < tr->x || (x == tr->x && y < tr->y))
853             tr = tr->left;
854         else
855             tr = tr->right;
856     return tr;
857 }
858
859
860 /***************************
861  ** Trile superstructure visibility functions. 
862  **  strategy fine, implementation lazy&retarded =/
863  **  */
864
865 #ifdef DEBUG
866 static double x_shit, y_shit;
867 #endif
868
869 static void calc_points(cberg_state *cberg, double *x1,double *y1, 
870         double *x2,double *y2, double *x3,double *y3, double *x4,double *y4)
871 {
872     double zNear, x_nearcenter, y_nearcenter, nhalfwidth, x_center, y_center;
873
874
875     /* could cache these.. bahhhhhhhhhhhhhh */
876     double halfheight = tan(cberg->fovy / 2 * M_PI_180) * cberg->zNear;
877     double fovx_2 = atan(halfheight * cberg->aspect / cberg->zNear) * M_180_PI; 
878     double zFar = cberg->zFar + M_RAD7_4;
879     double fhalfwidth = zFar * tan(fovx_2 * M_PI_180)
880                       + M_RAD7_4 / cos(fovx_2 * M_PI_180);
881     double x_farcenter = cberg->x + zFar * cos(cberg->yaw * M_PI_180);
882     double y_farcenter = cberg->y + zFar * sin(cberg->yaw * M_PI_180);
883     *x1 = x_farcenter + fhalfwidth * cos((cberg->yaw - 90) * M_PI_180);
884     *y1 = y_farcenter + fhalfwidth * sin((cberg->yaw - 90) * M_PI_180);
885     *x2 = x_farcenter - fhalfwidth * cos((cberg->yaw - 90) * M_PI_180);
886     *y2 = y_farcenter - fhalfwidth * sin((cberg->yaw - 90) * M_PI_180);
887
888 #ifdef DEBUG
889     printf("pos (%.3f,%.3f) @ %.3f || fovx: %f || fovy: %f\n", 
890             cberg->x, cberg->y, cberg->yaw, fovx_2 * 2, cberg->fovy);
891     printf("\tfarcenter: (%.3f,%.3f) || fhalfwidth: %.3f \n"
892            "\tp1: (%.3f,%.3f) || p2: (%.3f,%.3f)\n",
893             x_farcenter, y_farcenter, fhalfwidth, *x1, *y1, *x2, *y2);
894 #endif
895
896     if (cberg->z - halfheight <= 0) /* near view plane hits xy */
897         zNear = cberg->zNear - M_RAD7_4;
898     else /* use bottom of frustum */
899         zNear = cberg->z / tan(cberg->fovy / 2 * M_PI_180) - M_RAD7_4;
900     nhalfwidth = zNear * tan(fovx_2 * M_PI_180)
901                + M_RAD7_4 / cos(fovx_2 * M_PI_180);
902     x_nearcenter = cberg->x + zNear * cos(cberg->yaw * M_PI_180);
903     y_nearcenter = cberg->y + zNear * sin(cberg->yaw * M_PI_180);
904     *x3 = x_nearcenter - nhalfwidth * cos((cberg->yaw - 90) * M_PI_180);
905     *y3 = y_nearcenter - nhalfwidth * sin((cberg->yaw - 90) * M_PI_180);
906     *x4 = x_nearcenter + nhalfwidth * cos((cberg->yaw - 90) * M_PI_180);
907     *y4 = y_nearcenter + nhalfwidth * sin((cberg->yaw - 90) * M_PI_180);
908
909 #ifdef DEBUG
910     printf("\tnearcenter: (%.3f,%.3f) || nhalfwidth: %.3f\n"
911            "\tp3: (%.3f,%.3f) || p4: (%.3f,%.3f)\n",
912             x_nearcenter, y_nearcenter, nhalfwidth, *x3, *y3, *x4, *y4);
913 #endif
914
915
916     /* center can be average or the intersection of diagonals.. */
917 #if 0
918     {
919         double c = nhalfwidth * (zFar -zNear) / (fhalfwidth + nhalfwidth);
920         x_center = x_nearcenter + c * cos(cberg->yaw * M_PI_180);
921         y_center = y_nearcenter + c * sin(cberg->yaw * M_PI_180);
922     }
923 #else
924     x_center = (x_nearcenter + x_farcenter) / 2;
925     y_center = (y_nearcenter + y_farcenter) / 2;
926 #endif
927 #ifdef DEBUG
928     x_shit = x_center;
929     y_shit = y_center;
930 #endif
931     
932 #define VSCALE(p)   *x##p = visibility * *x##p + (1-visibility) * x_center; \
933                     *y##p = visibility * *y##p + (1-visibility) * y_center
934
935     VSCALE(1);
936     VSCALE(2);
937     VSCALE(3);
938     VSCALE(4);
939 #undef VSCALE
940 }
941
942 /* this is pretty stupid.. */
943 static inline void minmax4(double a, double b, double c, double d, 
944   double *min, double *max)
945 {
946     *min = *max = a;
947
948     if (b > *max)       *max = b;
949     else if (b < *min)  *min = b;
950     if (c > *max)       *max = c;
951     else if (c < *min)  *min = c;
952     if (d > *max)       *max = d;
953     else if (d < *min)  *min = d;
954 }
955
956 typedef struct {
957     double min, max, start, dx;
958 } LS;
959
960 #define check_line(a, b)                     \
961     if (fabs(y##a-y##b) > 0.001) {                    \
962         ls[count].dx = (x##b-x##a)/(y##b-y##a);               \
963         if (y##b > y##a) {                            \
964             ls[count].start = x##a;                     \
965             ls[count].min = y##a;                       \
966             ls[count].max = y##b;                       \
967         } else {                                  \
968             ls[count].start = x##b;                     \
969             ls[count].min = y##b;                       \
970             ls[count].max = y##a;                       \
971         }                                         \
972         ++count;                                    \
973     }
974
975 static unsigned int build_ls(cberg_state *cberg, 
976                       double x1, double y1, double x2, double y2, 
977                       double x3, double y3, double x4, double y4, LS *ls,
978                       double *trough, double *peak)
979 {
980     unsigned int count = 0;
981
982     check_line(1, 2);
983     check_line(2, 3);
984     check_line(3, 4);
985     check_line(4, 1);
986
987     minmax4(y1, y2, y3, y4, trough, peak);
988     return count;
989 }
990
991 #undef check_line
992
993 /*needs bullshit to avoid double counts on corners.*/
994 static void find_bounds(double y, double *left, double *right, LS *ls,
995         unsigned int nls)
996 {
997     double x;
998     unsigned int i, set = 0;
999
1000     for (i = 0; i != nls; ++i)
1001         if (ls[i].min <= y && ls[i].max >= y) {
1002             x = (y - ls[i].min) * ls[i].dx + ls[i].start;
1003             if (!set) {
1004                 *left = x;
1005                 ++set;
1006             } else if (fabs(x - *left) > 0.001) {
1007                 if (*left < x)
1008                     *right = x;
1009                 else {
1010                     *right = *left;
1011                     *left = x;
1012                 }
1013                 return;
1014             }
1015         }
1016
1017     /* just in case we somehow blew up */
1018     *left = 3.0;
1019     *right = -3.0;
1020 }
1021
1022 static void mark_visible(cberg_state *cberg)
1023 {
1024     double trough, peak, yval, left=0, right=0;
1025     double x1,y1, x2,y2, x3,y3, x4,y4;
1026     int start, stop, x, y;
1027     LS ls[4];
1028     unsigned int nls;
1029
1030     calc_points(cberg, &x1,&y1, &x2,&y2, &x3,&y3, &x4,&y4);
1031     nls = build_ls(cberg, x1,y1, x2,y2, x3,y3, x4,y4, ls, &trough, &peak);
1032
1033     start = (int) ceil(trough / M_SQRT3_2);
1034     stop = (int) floor(peak / M_SQRT3_2);
1035     
1036     for (y = start; y <= stop; ++y) {
1037         yval = y * M_SQRT3_2;
1038         find_bounds(yval, &left, &right, ls, nls);
1039         for (x = (int) ceil(left*2-1); x <= (int) floor(right*2); ++x) 
1040             triles_set_visible(cberg, &(cberg->trile_head), x, y);
1041     }
1042 }
1043
1044
1045 /***************************
1046  ** color schemes
1047  ** */
1048
1049 static void plain_land(cberg_state *cberg, double z)
1050 { glColor3f(pow((z/0.35),4),  z/0.35, pow((z/0.35),4)); }
1051 static void plain_water(cberg_state *cberg, double z)
1052 { glColor3f(0.0, (z+0.35)*1.6, 0.8); }
1053
1054 static void ice_land(cberg_state *cberg, double z)
1055 { glColor3f((0.35 - z)/0.35, (0.35 - z)/0.35, 1.0); }
1056 static void ice_water(cberg_state *cberg, double z)
1057 { glColor3f(0.0, (z+0.35)*1.6, 0.8); }
1058
1059
1060 static void magma_land(cberg_state *cberg, double z)
1061 { glColor3f(z/0.35, z/0.2,0); }
1062 static void magma_lava(cberg_state *cberg, double z)
1063 { glColor3f((z+0.35)*1.6, (z+0.35), 0.0); }
1064
1065 static void vomit_solid(cberg_state *cberg, double z)
1066 {
1067     double norm = fabs(z) / 0.35;
1068     glColor3f( 
1069       (1-norm) * cberg->vs0r + norm * cberg->vs1r, 
1070       (1-norm) * cberg->vs0g + norm * cberg->vs1g, 
1071       (1-norm) * cberg->vs0b + norm * cberg->vs1b 
1072     );
1073 }
1074 static void vomit_fluid(cberg_state *cberg, double z)
1075 {
1076     double norm = z / -0.35;
1077     glColor3f( 
1078       (1-norm) * cberg->vf0r + norm * cberg->vf1r, 
1079       (1-norm) * cberg->vf0g + norm * cberg->vf1g, 
1080       (1-norm) * cberg->vf0b + norm * cberg->vf1b 
1081     );
1082 }
1083
1084
1085 static const Color colors[] = {
1086     {"plain", plain_land, plain_water, {0.0, 0.0, 0.0, 1.0}},
1087     {"ice", ice_land, ice_water, {0.0, 0.0, 0.0, 1.0}},
1088     {"magma", magma_land, magma_lava, {0.3, 0.3, 0.0, 1.0}},
1089     {"vomit", vomit_solid, vomit_fluid, {0.3, 0.3, 0.0, 1.0}}, /* no error! */
1090 };
1091
1092 static const Color *select_color(cberg_state *cberg)
1093 {
1094     unsigned int ncolors = countof(colors);
1095     int idx = -1;
1096     if ( ! strcmp(color, "random") )
1097         idx = random() % ncolors;
1098     else {
1099         unsigned int i;
1100         for (i = 0; i != ncolors; ++i)
1101             if ( ! strcmp(colors[i].id, color) ) {
1102                 idx = i;
1103                 break;
1104             }
1105
1106         if (idx == -1) {
1107             printf("invalid color scheme selected; valid choices are:\n");
1108             for (i = 0; i != ncolors; ++i)
1109                 printf("\t%s\n", colors[i].id);
1110             printf("\t%s\n", "random");
1111             idx = 0;
1112         }
1113     }
1114
1115     if ( ! strcmp(colors[idx].id, "vomit") ) { /* need to create it (ghetto) */
1116         cberg->vs0r = random()/(double)RAND_MAX;
1117         cberg->vs0g = random()/(double)RAND_MAX;
1118         cberg->vs0b = random()/(double)RAND_MAX; 
1119         cberg->vs1r = random()/(double)RAND_MAX; 
1120         cberg->vs1g = random()/(double)RAND_MAX;
1121         cberg->vs1b = random()/(double)RAND_MAX;
1122         cberg->vf0r = random()/(double)RAND_MAX;
1123         cberg->vf0g = random()/(double)RAND_MAX;
1124         cberg->vf0b = random()/(double)RAND_MAX; 
1125         cberg->vf1r = random()/(double)RAND_MAX; 
1126         cberg->vf1g = random()/(double)RAND_MAX; 
1127         cberg->vf1b = random()/(double)RAND_MAX; 
1128  
1129         glClearColor(random()/(double)RAND_MAX,
1130                      random()/(double)RAND_MAX,
1131                      random()/(double)RAND_MAX,
1132                      1.0);
1133     } else {
1134         glClearColor(colors[idx].bg[0],
1135                      colors[idx].bg[1],
1136                      colors[idx].bg[2],
1137                      colors[idx].bg[3]);
1138     }
1139     return colors + idx;
1140 }
1141
1142
1143 /***************************
1144  ** misc helper functions
1145  ** */
1146
1147
1148 /* simple one for now.. */
1149 static inline double drunken_rando(double cur_val, double max, double width)
1150 {
1151     double r = random() / (double) RAND_MAX * 2;
1152     if (cur_val > 0)
1153         if (r >= 1)
1154             return cur_val + (r-1) * width * (1-cur_val/max);
1155         else
1156             return cur_val - r * width; 
1157     else
1158         if (r >= 1)
1159             return cur_val - (r-1) * width * (1+cur_val/max);
1160         else
1161             return cur_val + r * width; 
1162 }
1163
1164
1165 /***************************
1166  ** core crackberg routines
1167  ** */
1168
1169 ENTRYPOINT void reshape_crackberg (ModeInfo *mi, int w, int h);
1170 static void free_crackberg (ModeInfo *mi);
1171
1172 ENTRYPOINT void init_crackberg (ModeInfo *mi)
1173 {
1174     cberg_state *cberg;
1175
1176     nsubdivs %= 16; /* just in case.. */
1177
1178     MI_INIT(mi, cbergs, free_crackberg);
1179
1180     if (visibility > 1.0 || visibility < 0.2) {
1181         printf("visibility must be in range [0.2 .. 1.0]\n");
1182         visibility = 1.0;
1183     }
1184
1185     cberg = &cbergs[MI_SCREEN(mi)];
1186     
1187     cberg->epoints = 1 + (1 << nsubdivs);
1188     cberg->tpoints = cberg->epoints * (cberg->epoints + 1) / 2;
1189     cberg->ntris = (1 << (nsubdivs << 1));
1190     cberg->tnorms = ( (flat) ? cberg->ntris : cberg->tpoints);
1191     cberg->dx0 = 1.0 / (1 << nsubdivs);
1192
1193     cberg->heights = malloc(cberg->tpoints * sizeof(double));
1194     cberg->norms = malloc(3 * cberg->tnorms * sizeof(double));
1195
1196     cberg->glx_context = init_GL(mi);
1197     cberg->motion_state = MOTION_AUTO;
1198     cberg->mspeed = 1.0;
1199     cberg->z = 0.5;
1200
1201     cberg->fovy = 60.0;
1202     cberg->zNear = 0.5;
1203     cberg->zFar = 5.0;
1204
1205     cberg->draw_elapsed = 1.0;
1206
1207     glEnable(GL_DEPTH_TEST);
1208     glEnable(GL_BLEND);
1209     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1210     glShadeModel((flat) ? GL_FLAT : GL_SMOOTH);
1211 # ifndef HAVE_JWZGLES /* #### glPolygonMode other than GL_FILL unimplemented */
1212     glPolygonMode(GL_FRONT_AND_BACK, (MI_IS_WIREFRAME(mi)) ? GL_LINE : GL_FILL);
1213 # endif
1214
1215     if (lit) {
1216         glEnable(GL_LIGHTING);
1217         glEnable(GL_LIGHT0);
1218         glEnable(GL_COLOR_MATERIAL);
1219         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1220         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
1221         glEnable(GL_NORMALIZE);
1222         glEnable(GL_RESCALE_NORMAL); 
1223     }
1224
1225     cberg->color = select_color(cberg);
1226
1227     reshape_crackberg(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
1228 }
1229
1230 ENTRYPOINT void reshape_crackberg (ModeInfo *mi, int w, int h)
1231 {
1232     int h2;
1233     cberg_state *cberg = &cbergs[MI_SCREEN(mi)];
1234
1235     if (letterbox && (h2 = w * 9 / 16) < h) {
1236         glViewport(0, (h-h2)/2, w, h2);
1237         cberg->aspect = w/(double)h2;
1238     } else {
1239         glViewport (0, 0, w, h);
1240         cberg->aspect = w/(double)h;
1241     }
1242
1243     glMatrixMode(GL_PROJECTION);
1244     glLoadIdentity();
1245     gluPerspective(cberg->fovy, cberg->aspect, cberg->zNear, cberg->zFar);
1246     glMatrixMode(GL_MODELVIEW);
1247 }
1248
1249 ENTRYPOINT Bool crackberg_handle_event (ModeInfo *mi, XEvent *ev)
1250 {
1251     cberg_state *cberg = &cbergs[MI_SCREEN(mi)];
1252     KeySym keysym = 0;
1253     char c = 0;
1254     if (ev->xany.type == KeyPress || ev->xany.type == KeyRelease)
1255       XLookupString (&ev->xkey, &c, 1, &keysym, 0);
1256
1257     if (ev->xany.type == KeyPress) {
1258         switch (keysym) {
1259             case XK_Left:   cberg->motion_state |= MOTION_LROT;  break;
1260             case XK_Prior:  cberg->motion_state |= MOTION_LROT;  break;
1261             case XK_Right:  cberg->motion_state |= MOTION_RROT;  break;
1262             case XK_Next:   cberg->motion_state |= MOTION_RROT;  break;
1263             case XK_Down:   cberg->motion_state |= MOTION_BACK;  break;
1264             case XK_Up:     cberg->motion_state |= MOTION_FORW;  break;
1265             case '1':       cberg->motion_state |= MOTION_DEC;   break; 
1266             case '2':       cberg->motion_state |= MOTION_INC;   break;
1267             case 'a':       cberg->motion_state |= MOTION_LEFT;  break;
1268             case 'd':       cberg->motion_state |= MOTION_RIGHT; break;
1269             case 's':       cberg->motion_state |= MOTION_BACK;  break;
1270             case 'w':       cberg->motion_state |= MOTION_FORW;  break;
1271             default:        return False;
1272         }
1273         cberg->motion_state |= MOTION_MANUAL;
1274     } else if (ev->xany.type == KeyRelease) { 
1275 #if 0
1276         XEvent peek_ev;
1277         if (XPending(mi->dpy)) {
1278             XPeekEvent(mi->dpy, &peek_ev);
1279             if (peek_ev.type == KeyPress
1280              && peek_ev.xkey.keycode == ev->xkey.keycode       
1281              && peek_ev.xkey.time - ev->xkey.time < 2) {
1282                 XNextEvent(mi->dpy, &peek_ev); /* drop bullshit repeat events */
1283                 return False;
1284             }
1285         }
1286 #endif
1287
1288         switch (keysym) {
1289             case XK_Left:   cberg->motion_state &= ~MOTION_LROT;  break;
1290             case XK_Prior:  cberg->motion_state &= ~MOTION_LROT;  break;
1291             case XK_Right:  cberg->motion_state &= ~MOTION_RROT;  break;
1292             case XK_Next:   cberg->motion_state &= ~MOTION_RROT;  break;
1293             case XK_Down:   cberg->motion_state &= ~MOTION_BACK;  break;
1294             case XK_Up:     cberg->motion_state &= ~MOTION_FORW;  break;
1295             case '1':       cberg->motion_state &= ~MOTION_DEC;   break; 
1296             case '2':       cberg->motion_state &= ~MOTION_INC;   break;
1297             case 'a':       cberg->motion_state &= ~MOTION_LEFT;  break;
1298             case 'd':       cberg->motion_state &= ~MOTION_RIGHT; break;
1299             case 's':       cberg->motion_state &= ~MOTION_BACK;  break;
1300             case 'w':       cberg->motion_state &= ~MOTION_FORW;  break;
1301             case ' ':       
1302                 if (cberg->motion_state == MOTION_MANUAL)
1303                     cberg->motion_state = MOTION_AUTO;     
1304                 break;
1305             default:            return False;
1306         }
1307     } else if (ev->xany.type == ButtonPress &&
1308                ev->xbutton.button == Button1) {
1309       cberg->button_down_p = True;
1310       cberg->mouse_x = ev->xbutton.x;
1311       cberg->mouse_y = ev->xbutton.y;
1312       cberg->motion_state = MOTION_MANUAL;
1313       cberg->paused.tv_sec = 0;
1314     } else if (ev->xany.type == ButtonRelease &&
1315                ev->xbutton.button == Button1) {
1316       cberg->button_down_p = False;
1317       cberg->motion_state = MOTION_AUTO;
1318       /* After mouse-up, don't go back into auto-motion mode for a second, so
1319          that repeated click-and-drag gestures don't fight with auto-motion. */
1320       gettimeofday(&cberg->paused, NULL);
1321     } else if (ev->xany.type == MotionNotify &&
1322                cberg->button_down_p) {
1323       int dx = ev->xmotion.x - cberg->mouse_x;
1324       int dy = ev->xmotion.y - cberg->mouse_y;
1325       cberg->mouse_x = ev->xmotion.x;
1326       cberg->mouse_y = ev->xmotion.y;
1327       cberg->motion_state = MOTION_MANUAL;
1328
1329       /* Take the larger dimension, since motion_state doesn't scale */
1330       if (dx > 0 && dx > dy) dy = 0;
1331       if (dx < 0 && dx < dy) dy = 0;
1332       if (dy > 0 && dy > dx) dx = 0;
1333       if (dy < 0 && dy < dx) dx = 0;
1334
1335       {
1336         int rot = current_device_rotation();
1337         int swap;
1338         while (rot <= -180) rot += 360;
1339         while (rot >   180) rot -= 360;
1340         if (rot > 135 || rot < -135)            /* 180 */
1341             dx = -dx, dy = -dy;
1342         else if (rot > 45)                      /* 90 */
1343           swap = dx, dx = -dy, dy = swap;
1344         else if (rot < -45)                     /* 270 */
1345           swap = dx, dx = dy, dy = -swap;
1346       }
1347
1348       if      (dx > 0) cberg->motion_state |= MOTION_LEFT;
1349       else if (dx < 0) cberg->motion_state |= MOTION_RIGHT;
1350       else if (dy > 0) cberg->motion_state |= MOTION_FORW;
1351       else if (dy < 0) cberg->motion_state |= MOTION_BACK;
1352     } else
1353         return False;
1354     return True;
1355 }   
1356  
1357 ENTRYPOINT void draw_crackberg (ModeInfo *mi)
1358 {
1359     cberg_state *cberg = &cbergs[MI_SCREEN(mi)];
1360     struct timeval cur_frame_t;
1361     double cur_frame;
1362     static const float lpos[] = {2.0,0.0,-0.3,0.0};
1363
1364     if (!cberg->glx_context) /*XXX does this get externally tweaked? it kinda*/
1365         return;               /*XXX can't.. check it in crackberg_init*/
1366
1367     glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(cberg->glx_context));
1368
1369     gettimeofday(&cur_frame_t, NULL);
1370     cur_frame = cur_frame_t.tv_sec + cur_frame_t.tv_usec / 1.0E6;
1371     if ( cberg->prev_frame ) { /*not first run */
1372
1373         cberg->elapsed = cur_frame - cberg->prev_frame;
1374
1375         if (cberg->motion_state == MOTION_AUTO &&
1376             cberg->paused.tv_sec < cur_frame_t.tv_sec) {
1377             cberg->x += cberg->dx * cberg->elapsed;
1378             cberg->y += cberg->dy * cberg->elapsed;
1379             /* cberg->z */
1380             /* cberg->pitch */
1381             /* cberg->roll */
1382             cberg->yaw += cberg->dyaw * cberg->elapsed;
1383
1384             cberg->draw_elapsed += cberg->elapsed;
1385             if (cberg->draw_elapsed >= 0.8) {
1386                 cberg->draw_elapsed = 0.0;
1387                 cberg->dx = drunken_rando(cberg->dx, 2.5, 0.8);
1388                 cberg->dy = drunken_rando(cberg->dy, 2.5, 0.8);
1389                 /* cberg->dz */
1390                 /* cberg->dpitch */
1391                 /* cberg->droll */
1392                 cberg->dyaw = drunken_rando(cberg->dyaw, 40.0,  8.0);
1393             }
1394         } else {
1395             double scale = cberg->elapsed * cberg->mspeed;
1396             if (cberg->motion_state & MOTION_BACK) {
1397                 cberg->x -= cos(cberg->yaw * M_PI_180) * scale;
1398                 cberg->y -= sin(cberg->yaw * M_PI_180) * scale;
1399             }
1400             if (cberg->motion_state & MOTION_FORW) {
1401                 cberg->x += cos(cberg->yaw * M_PI_180) * scale;
1402                 cberg->y += sin(cberg->yaw * M_PI_180) * scale;
1403             }
1404
1405             if (cberg->motion_state & MOTION_LEFT) {
1406                 cberg->x -= sin(cberg->yaw * M_PI_180) * scale;
1407                 cberg->y += cos(cberg->yaw * M_PI_180) * scale;
1408             }
1409             if (cberg->motion_state & MOTION_RIGHT) {
1410                 cberg->x += sin(cberg->yaw * M_PI_180) * scale;
1411                 cberg->y -= cos(cberg->yaw * M_PI_180) * scale;
1412             }
1413
1414             if (cberg->motion_state & MOTION_LROT)
1415                 cberg->yaw += 45 * scale;
1416             if (cberg->motion_state & MOTION_RROT)
1417                 cberg->yaw -= 45 * scale;
1418
1419             if (cberg->motion_state & MOTION_DEC)
1420                 cberg->mspeed /= pow(MSPEED_SCALE, cberg->draw_elapsed);
1421             if (cberg->motion_state & MOTION_INC)
1422                 cberg->mspeed *= pow(MSPEED_SCALE, cberg->draw_elapsed);
1423
1424         }
1425     }
1426     cberg->prev_frame = cur_frame;
1427
1428     mark_visible(cberg);
1429     triles_update_state(&(cberg->trile_head), cberg);
1430         
1431     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1432     glLoadIdentity();
1433     glRotatef(current_device_rotation(), 0, 0, 1);
1434     gluLookAt(0,0,0, 1,0,0, 0,0,1);
1435     glLightfv(GL_LIGHT0, GL_POSITION, lpos);
1436     /*glRotated(cberg->roll, 1,0,0); / * XXX blah broken and unused for now..* /
1437     glRotated(cberg->pitch, 0,1,0); */
1438     glRotated(-cberg->yaw, 0,0,1); /* camera sees ->yaw over */
1439     glTranslated(-cberg->x, -cberg->y, -cberg->z);
1440
1441     mi->polygon_count = cberg->ntris * 
1442       triles_foreach(cberg->trile_head, trile_draw,(void *) cberg);
1443     
1444     if (mi->fps_p)  
1445         do_fps(mi);
1446
1447 #ifdef DEBUG
1448     glBegin(GL_LINES);
1449         glColor3f(1.0,0.0,0.0);
1450         glVertex3d(x_shit, y_shit, 0.0);
1451         glVertex3d(x_shit, y_shit, 1.0);
1452     glEnd();
1453 #endif
1454
1455     glFinish();
1456     glXSwapBuffers(MI_DISPLAY(mi), MI_WINDOW(mi));
1457 }
1458
1459 /* uh */
1460 static void free_crackberg (ModeInfo *mi)
1461 {
1462   cberg_state *cberg = &cbergs[MI_SCREEN(mi)];
1463   if (cberg->norms)
1464     free(cberg->norms);
1465   free(cberg->heights);
1466 }
1467
1468 XSCREENSAVER_MODULE ("Crackberg", crackberg)
1469
1470 #endif /* USE_GL */