e5351886f017efd61d2c642506e75bf4d6868dc5
[xscreensaver] / hacks / glx / jigglypuff.c
1 /* jigglypuff - a most, most, unfortunate screensaver.
2  *
3  * Copyright (c) 2003 Keith Macleod (kmacleod@primus.ca)
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and its
6  * documentation for any purpose is hereby granted without fee, provided that
7  * the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation.  No representations are made about the suitability of this
10  * software for any purpose.  It is provided "as is" without express or 
11  * implied warranty.
12  *
13  * Draws all varieties of obscene, spastic, puffy balls
14  * orbiting lazily about the screen. More of an accident
15  * than anything else.
16  *
17  * Apologies to anyone who thought they were getting a Pokemon
18  * out of this.
19  *
20  * Of course, if you modify it to do something interesting and/or
21  * funny, I'd appreciate receiving a copy.
22  *
23  * 04/06/2003 - Oops, figured out what was wrong with the sphere
24  *              mapping. I had assumed it was done in model space,
25  *              but of course I was totally wrong... Eye space you
26  *              say? Yup. km
27  *
28  * 03/31/2003 - Added chrome to the color options. The mapping
29  *              is anything but 'correct', but it's a pretty good
30  *              effect anyways, as long as the surface is jiggling
31  *              enough that you can't tell. Sure, it seems  kind of odd
32  *              that it's reflecting a sky that's obviously not there,
33  *              but who has time to worry about silly details like
34  *              that? Not me, ah rekkin'. km
35  *
36  */
37
38 #include <X11/Intrinsic.h>
39
40 #ifdef STANDALONE
41 # define PROGCLASS          "Jigglypuff"
42 # define HACK_INIT          init_jigglypuff
43 # define HACK_DRAW          draw_jigglypuff
44 # define HACK_RESHAPE       reshape_jigglypuff
45 # define HACK_HANDLE_EVENT  jigglypuff_handle_event
46 # define EVENT_MASK         PointerMotionMask 
47 # define jigglypuff_opts    xlockmore_opts
48
49 #define DEF_COLOR           "cycle"
50 #define DEF_SHININESS       "100"
51 #define DEF_COMPLEXITY      "2"
52 #define DEF_SPEED           "500"
53 #define DEF_DISTANCE        "100"
54 #define DEF_HOLD            "800"
55 #define DEF_SPHERISM        "75"
56 #define DEF_DAMPING         "500"
57
58 # define DEFAULTS           "*delay: 20000\n" \
59                             "*showFPS: False\n" \
60                             "*wireframe: False\n" \
61                             "*color: cycle\n" \
62                             "*shininess: 100\n" \
63                             "*complexity: 2\n" \
64                             "*speed: 500\n" \
65                             "*distance: 100\n" \
66                             "*hold: 800\n" \
67                             "*spherism: 200\n" \
68                             "*damping: 500\n"
69
70
71 # include "xlockmore.h"
72 #else
73 # include "xlock.h"
74 #endif
75
76 #ifdef HAVE_CONFIG_H
77 # include "config.h"
78 #endif
79
80 #include "xpm-ximage.h"
81 #include "gltrackball.h"
82 #include "../images/jigglymap.xpm"
83
84 #ifdef USE_GL
85 #include <GL/gl.h>
86
87 #ifndef max
88 #define max(a,b) (((a)>(b))?(a):(b))
89 #define min(a,b) (((a)<(b))?(a):(b))
90 #endif
91
92 /* Why isn't RAND_MAX correct in the first place? */
93 #define REAL_RAND_MAX (2.0*(float)RAND_MAX)
94
95 static int spherism;
96 static int hold;
97 static int distance;
98 static int damping;
99
100 static int complexity;
101 static int speed;
102
103 static int do_tetrahedron;
104 static int spooky;
105 static char *color;
106 static int shininess;
107
108 static int random_parms;
109
110 typedef struct solid solid;
111
112 typedef struct {
113     float stable_distance;
114     float hold_strength;
115     float spherify_strength;
116     float damping_velocity;
117     float damping_factor;
118
119     int do_wireframe;
120     int spooky;
121     int color_style;
122     GLint shininess;
123     GLfloat jiggly_color[4];
124     GLfloat color_dir[3];
125
126     solid *shape;
127
128     trackball_state *trackball;
129     int button_down;
130
131     float angle;
132     float axis;
133     float speed;
134
135     GLXContext *glx_context;
136 } jigglystruct;
137
138 static jigglystruct *jss = NULL;
139
140 static XrmOptionDescRec opts[] = {
141     {"-random", ".Jigglypuff.random", XrmoptionNoArg, (caddr_t)"true"},
142     {"+random", ".Jigglypuff.random", XrmoptionNoArg, (caddr_t)"false"},
143     {"-tetra", ".Jigglypuff.tetra", XrmoptionNoArg, (caddr_t)"true"},
144     {"+tetra", ".Jigglypuff.tetra", XrmoptionNoArg, (caddr_t)"false"},
145     {"-spooky", ".Jigglypuff.spooky", XrmoptionSepArg, (caddr_t)"0"},
146     {"-color", ".Jigglypuff.color", XrmoptionSepArg, (caddr_t)DEF_COLOR},
147     {"-shininess", ".Jigglypuff.shininess", XrmoptionSepArg, (caddr_t)DEF_SHININESS},
148     {"-complexity", ".Jigglypuff.complexity", XrmoptionSepArg, (caddr_t)DEF_COMPLEXITY},
149     {"-speed", ".Jigglypuff.speed", XrmoptionSepArg, (caddr_t)DEF_SPEED},
150     {"-spherism", ".Jigglypuff.spherism", XrmoptionSepArg, (caddr_t)DEF_SPHERISM},
151     {"-hold", ".Jigglypuff.hold", XrmoptionSepArg, (caddr_t)DEF_HOLD},
152     {"-distance", "Jigglypuff.distance", XrmoptionSepArg, (caddr_t)DEF_DISTANCE},
153     {"-damping", "Jigglypuff.damping", XrmoptionSepArg, (caddr_t)DEF_DAMPING}
154 };
155
156 static argtype vars[] = {
157     {(caddr_t*)&random_parms, "random", "Random", "False", t_Bool},
158     {(caddr_t*)&do_tetrahedron, "tetra", "Tetra", "False", t_Bool},
159     {(caddr_t*)&spooky, "spooky", "Spooky", "0", t_Int},
160     {(caddr_t*)&color, "color", "Color", DEF_COLOR, t_String},
161     {(caddr_t*)&shininess, "shininess", "Shininess", DEF_SHININESS, t_Int},
162     {(caddr_t*)&complexity, "complexity", "Complexity", DEF_COMPLEXITY, t_Int},
163     {(caddr_t*)&speed, "speed", "Speed", DEF_SPEED, t_Int},
164     {(caddr_t*)&spherism, "spherism", "Spherism", DEF_SPHERISM, t_Int},
165     {(caddr_t*)&hold, "hold", "Hold", DEF_HOLD, t_Int},
166     {(caddr_t*)&distance, "distance", "Distance", DEF_DISTANCE, t_Int},
167     {(caddr_t*)&damping, "damping", "Damping", DEF_DAMPING, t_Int}
168 };
169
170 #undef countof
171 #define countof(x) ((int)(sizeof(x)/sizeof(*(x))))
172
173 ModeSpecOpt jigglypuff_opts = {countof(opts), opts, countof(vars), vars, NULL};
174
175 #define COLOR_STYLE_NORMAL    0
176 #define COLOR_STYLE_CYCLE     1
177 #define COLOR_STYLE_CLOWNBARF 2
178 #define COLOR_STYLE_FLOWERBOX 3
179 #define COLOR_STYLE_CHROME    4
180
181 #define CLOWNBARF_NCOLORS 5
182
183 static GLfloat clownbarf_colors[CLOWNBARF_NCOLORS][4] = {
184     {0.7, 0.7, 0.0, 1.0},
185     {0.8, 0.1, 0.1, 1.0},
186     {0.1, 0.1, 0.8, 1.0},
187     {0.9, 0.9, 0.9, 1.0},
188     {0.0, 0.0, 0.0, 1.0}
189 };
190
191 static GLfloat flowerbox_colors[4][4] = {
192     {0.7, 0.7, 0.0, 1.0},
193     {0.9, 0.0, 0.0, 1.0},
194     {0.0, 0.9, 0.0, 1.0},
195     {0.0, 0.0, 0.9, 1.0},
196 };
197
198 #ifdef DEBUG
199 # ifdef __GNUC__ /* GCC style */
200 #define _DEBUG(msg, args...) do { \
201     fprintf(stderr, "%s : %d : " msg ,__FILE__,__LINE__ ,##args); \
202 } while(0)
203 # else /* C99 standard style */
204 #define _DEBUG(msg, ...) do { \
205     fprintf(stderr, "%s : %d : " msg ,__FILE__,__LINE__,__VA_ARGS__); \
206 } while(0)
207 # endif
208 #else
209 # ifdef __GNUC__ /* GCC style */
210 #define _DEBUG(msg, args...)
211 # else /* C99 standard style */
212 #define _DEBUG(msg, ...)
213 # endif
214 #endif
215
216 /* This is all the half-edge b-rep code (as well as basic geometry) */
217 typedef struct face face;
218 typedef struct edge edge;
219 typedef struct hedge hedge;
220 typedef struct vertex vertex;
221 typedef GLfloat coord;
222 typedef coord vector[3];
223
224 struct solid {
225     face *faces;
226     edge *edges;
227     vertex *vertices;
228 };
229
230 struct face {
231     solid *s;
232     hedge *start;
233     GLfloat *color;
234     face *next;
235 };
236
237 struct edge {
238     solid *s;
239     hedge *left;
240     hedge *right;
241     edge *next;
242 };
243
244 struct hedge {
245     face *f;
246     edge *e;
247     vertex *vtx;
248     hedge *next;
249     hedge *prev;
250 };
251
252 struct vertex {
253     solid *s;
254     hedge *h;
255     vector v;
256     vector n;
257     vector f;
258     vector vel;
259     vertex *next;
260 };
261
262 static inline void vector_init(vector v, coord x, coord y, coord z)
263 {
264     v[0] = x;
265     v[1] = y;
266     v[2] = z;
267 }    
268
269 static inline void vector_copy(vector d, vector s)
270 {
271     d[0] = s[0];
272     d[1] = s[1];
273     d[2] = s[2];
274 }
275
276 static inline void vector_add(vector v1, vector v2, vector v)
277 {
278     vector_init(v, v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]);
279 }
280
281 static inline void vector_add_to(vector v1, vector v2)
282 {
283     v1[0] += v2[0];
284     v1[1] += v2[1];
285     v1[2] += v2[2];
286 }
287
288 static inline void vector_sub(vector v1, vector v2, vector v)
289 {
290     vector_init(v, v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]);
291 }
292
293 static inline void vector_scale(vector v, coord s)
294 {
295     v[0] *= s;
296     v[1] *= s;
297     v[2] *= s;
298 }
299
300 static inline coord dot(vector v1, vector v2)
301 {
302     return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
303 }
304
305 static inline void cross(vector v1, vector v2, vector v)
306 {
307     vector_init(v,
308                 v1[1]*v2[2] - v2[1]*v1[2],
309                 v1[2]*v2[0] - v2[2]*v1[0],
310                 v1[0]*v2[1] - v2[0]*v1[1]);
311 }
312
313 static inline coord magnitude2(vector v)
314 {
315     return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
316 }
317
318 static inline coord magnitude(vector v)
319 {
320     return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
321 }
322
323 static inline void normalize(vector v)
324 {
325     coord mag = 1.0/sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
326
327     v[0] *= mag;
328     v[1] *= mag;
329     v[2] *= mag;
330 }
331
332 static inline void normalize_to(vector v, coord m)
333 {
334     coord mag = 1.0/sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2])/m;
335
336     v[0] *= mag;
337     v[1] *= mag;
338     v[2] *= mag;
339 }
340
341 static inline void midpoint(vector v1, vector v2, vector v)
342 {
343     vector_init(v,
344                 v1[0] + 0.5 * (v2[0] - v1[0]),
345                 v1[1] + 0.5 * (v2[1] - v1[1]),
346                 v1[2] + 0.5 * (v2[2] - v1[2]));
347 }
348
349 static inline hedge *partner(hedge *h) {
350     if(!h->e)
351         return NULL;
352     if(h == h->e->left) {
353         return h->e->right;
354     }
355     else if(h == h->e->right) {
356         return h->e->left;
357     }
358     else {
359         _DEBUG("Inconsistent edge detected. Presumably, this is a bug. Exiting.\n", NULL);
360         exit(-1);
361     }
362 }
363
364 vertex *vertex_new(solid *s, vector v)
365 {
366     vertex *vtx = (vertex*)malloc(sizeof(vertex));
367
368     if(!vtx)
369         return NULL;
370     vtx->s = s;
371     vtx->next = s->vertices;
372     s->vertices = vtx;
373     vector_copy(vtx->v, v);
374     vector_init(vtx->f, 0, 0, 0);
375     vector_init(vtx->vel, 0, 0, 0);
376     return vtx;
377 }
378
379 /* insert a new halfedge after hafter. this is low-level,
380  * i.e. it is a helper for the split_* functions, which
381  * maintain the consistency of the solid.
382  */
383 hedge *hedge_new(hedge *hafter, vertex *vtx)
384 {
385     hedge *h = (hedge*)malloc(sizeof(hedge));
386     
387     if(!h) {
388         _DEBUG("Out of memory in hedge_new()\n",NULL);
389         return NULL;
390     }
391     h->f = hafter->f;
392     h->vtx = vtx;
393     h->e = NULL;
394     h->prev = hafter;
395     h->next = hafter->next;
396     hafter->next = h;
397     h->next->prev = h;
398     return h;
399 }
400
401 edge *edge_new(solid *s)
402 {
403     edge *e = (edge*)malloc(sizeof(edge));
404     if(!e) {
405         _DEBUG("Out of memory in edge_new()\n",NULL);
406         exit(-1);
407     }
408     e->next = s->edges;
409     s->edges = e;
410     e-> s = s;
411     e->left = e->right = NULL;
412     return e;
413 }
414
415 face *face_new(solid *s, hedge *h)
416 {
417     face *f = (face*)malloc(sizeof(face));
418     if(!f) {
419         _DEBUG("Out of memory in face_new()",NULL);
420         exit(-1);
421     }
422     f->s = s;
423     f->start = h;
424     f->next = s->faces;
425     s->faces = f;
426     return f;
427 }
428
429 /* split vertex vtx, creating a new edge after v on f
430  * that goes to a new vertex at v, adjoining whatever
431  * face is on the other side of the halfedge attached to
432  * v on f. 
433  * Assumptions:
434  *    there are at least 2 faces.
435  *    partner(h)->next->vtx == vtx
436  * Post-assumptions:
437  *    the new halfedge will be inserted AFTER the indicated
438  *    halfedge. This means that f->start is guaranteed not to
439  *    change.
440  *    the vertex returned will have h==<the new halfedge>.
441  */
442
443 vertex *vertex_split(hedge *h, vector v)
444 {
445     hedge *h2, *hn1, *hn2;
446     vertex *vtxn;
447     edge *en;
448     face *f1, *f2;
449
450     f1 = h->f;
451     h2 = partner(h);
452     f2 = h2->f;
453     
454     vtxn = vertex_new(f1->s, v);
455     hn1 = hedge_new(h, vtxn);
456     vtxn->h = hn1;
457     hn2 = hedge_new(h2, vtxn);
458     hn2->e = h->e;
459
460     if(h2->e->left == h2)
461         h2->e->left = hn2;
462     else
463         h2->e->right = hn2;
464
465     en = edge_new(f1->s);
466     en->left = hn1;
467     en->right = h2;
468     hn1->e = en;
469     h2->e = en;
470     return vtxn;
471 }
472
473 face *face_split(face *f, hedge *h1, hedge *h2)
474 {
475     hedge *hn1, *hn2, *tmp;
476     edge *en;
477     face *fn;
478
479     if(h1->f != f || h2->f != f) {
480         _DEBUG("Whoah, cap'n, yer usin' a bad halfedge!\n",NULL);
481         exit(-1);
482     }
483     if(h1 == h2) {
484         _DEBUG("Trying to split a face at a single vertex\n",NULL);
485         exit(-1);
486     }
487     /* close the loops */
488     h1->prev->next = h2;
489     h2->prev->next = h1;
490     tmp = h1->prev;
491     h1->prev = h2->prev;
492     h2->prev = tmp;
493     /* insert halfedges & create edge */
494     hn1 = hedge_new(h2->prev, h1->vtx);
495     hn2 = hedge_new(h1->prev, h2->vtx);
496     en = edge_new(f->s);
497     en->left = hn1;
498     en->right = hn2;
499     hn1->e = en;
500     hn2->e = en;
501
502     /* make the new face, first find out which hedge is contained
503     * in the original face, then start the new face at the other */
504     tmp = f->start;
505     while(tmp != h1 && tmp != h2)
506         tmp = tmp->next;
507     tmp = (tmp == h1) ? h2 : h1 ;
508     fn = face_new(f->s, tmp);
509     do {
510         tmp->f = fn;
511         tmp = tmp->next;
512     } while(tmp != fn->start);
513     fn->color = f->color;
514     return fn;
515 }
516
517 solid *solid_new(vector where) 
518 {
519     solid *s = (solid*)malloc(sizeof(solid));
520     face *f1, *f2;
521     edge *e;
522     vertex *vtx;
523     hedge *h1,*h2;
524
525     s->faces = NULL;
526     s->edges = NULL;
527     s->vertices = NULL;
528
529     h1 = (hedge*)malloc(sizeof(hedge));
530     h2 = (hedge*)malloc(sizeof(hedge));
531     h1->next = h1->prev = h1;
532     h2->next = h2->prev = h2;
533
534     vtx = vertex_new(s, where);
535     vtx->h = h1;
536     h1->vtx = vtx;
537     h2->vtx = vtx;
538
539     e = edge_new(s);
540     e->left = h1;
541     e->right = h2;
542     h1->e = e;
543     h2->e = e;
544
545     f1 = face_new(s, h1);
546     f2 = face_new(s, h2);
547     h1->f = f1;
548     h2->f = f2;
549
550     return s;
551 }
552
553 /* This is all the code directly related to constructing the jigglypuff */
554 void face_tessel2(face *f)
555 {
556     hedge *h1=f->start->prev, *h2=f->start->next;
557     
558     if(h1->next == h1)
559         return;
560     while(h2 != h1 && h2->next != h1) {
561         f = face_split(f, h1, h2);
562         h1 = f->start;
563         h2 = f->start->next->next;
564     }
565 }
566
567 /* This will only work with solids composed entirely of
568  * triangular faces. It first add a vertex to the middle
569  * of each edge, then walks the faces, connecting the
570  * dots.
571  * I'm abusing the fact that new faces and edges are always
572  * added at the head of the list. If that ever changes,
573  * this is borked. 
574  */
575 void solid_tesselate(solid *s) 
576 {
577     edge *e = s->edges;
578     face *f = s->faces;
579     
580     while(e) {
581         vector v;
582         midpoint(e->left->vtx->v, e->right->vtx->v, v);
583         vertex_split(e->left, v);
584         e = e->next;
585     }
586     while(f) {
587         face_tessel2(f);
588         f=f->next;
589     }
590 }
591                 
592 void solid_spherify(solid * s, coord size) 
593 {
594     vertex *vtx = s->vertices;
595
596     while(vtx) {
597         normalize_to(vtx->v, size);
598         vtx = vtx->next;
599     }
600 }
601
602 solid *tetrahedron(jigglystruct *js) 
603 {
604     solid *s;
605     vertex *vtx;
606     vector v;
607     hedge *h;
608     face *f;
609     int i;
610
611     vector_init(v, 1, 1, 1);
612     s = solid_new(v);
613     vector_init(v, -1, -1, 1);
614     h = s->faces->start;
615     vtx = vertex_split(h, v);
616     vector_init(v, -1, 1, -1);
617     vtx = vertex_split(vtx->h, v);
618     h = vtx->h;
619     f = face_split(s->faces, h, h->prev);
620     vector_init(v, 1, -1, -1);
621     vertex_split(f->start, v);
622     f = s->faces->next->next;
623     h = f->start;
624     face_split(f, h, h->next->next);
625
626     if(js->color_style == COLOR_STYLE_FLOWERBOX) {
627         f = s->faces;
628         for(i=0; i<4; i++) {
629             f->color = flowerbox_colors[i];
630             f = f->next;
631         }
632     }       
633
634     return s;
635 }
636
637 solid *tesselated_tetrahedron(coord size, int iter, jigglystruct *js) {
638     solid *s = tetrahedron(js);
639     int i;
640
641     for(i=0; i<iter; i++) {
642         solid_tesselate(s);
643     }
644     return s;
645 }
646
647 static void clownbarf_colorize(solid *s) {
648     face *f = s->faces;
649     while(f) {
650         f->color = clownbarf_colors[random() % CLOWNBARF_NCOLORS];
651         f = f->next;
652     }
653 }
654
655 /* Here be the rendering code */
656
657 static inline void vertex_calcnormal(vertex *vtx, jigglystruct *js)
658 {
659     hedge *start = vtx->h, *h=start;
660     
661     vector_init(vtx->n, 0, 0, 0);
662     do {
663         vector u, v, norm;
664         vector_sub(h->prev->vtx->v, vtx->v, u);
665         vector_sub(h->next->vtx->v, vtx->v, v);
666         cross(u, v, norm);
667         vector_add_to(vtx->n, norm);
668         h = partner(h)->next;
669     } while(h != start);
670     if(!js->spooky)
671         normalize(vtx->n);
672     else
673         vector_scale(vtx->n, js->spooky);
674 }
675
676 static inline void vertex_render(vertex *vtx, jigglystruct *js)
677 {
678     glNormal3fv(vtx->n);
679     glVertex3fv(vtx->v);
680 }
681
682 /* This can be optimized somewhat due to the fact that all
683  * the faces are triangles. I haven't actually tested to
684  * see what the cost is of calling glBegin/glEnd for each
685  * triangle.
686  */
687 static inline void face_render(face *f, jigglystruct *js)
688 {
689     hedge *h1, *h2, *hend;
690
691     h1 = f->start;
692     hend = h1->prev;
693     h2 = h1->next;
694     
695     if(js->color_style == COLOR_STYLE_FLOWERBOX ||
696         js->color_style == COLOR_STYLE_CLOWNBARF)
697         glColor4fv(f->color);
698     glBegin(GL_TRIANGLES);
699     while(h1 != hend && h2 !=hend) {
700         vertex_render(h1->vtx, js);
701         vertex_render(h2->vtx, js);
702         vertex_render(hend->vtx, js);
703         h1 = h2;
704         h2 = h1->next;
705     }
706     glEnd();
707 }
708
709 void jigglypuff_render(jigglystruct *js) 
710 {
711     face *f = js->shape->faces;
712     vertex *vtx = js->shape->vertices;
713
714     while(vtx) {
715         vertex_calcnormal(vtx, js);
716         vtx = vtx->next;
717     }
718     while(f) {
719         face_render(f, js);
720         f=f->next;
721     }
722 }
723
724 /* This is the jiggling code */
725
726 /* stable distance when subdivs == 4 */
727 #define STABLE_DISTANCE 0.088388347648
728
729 void update_shape(jigglystruct *js)
730 {
731     vertex *vtx = js->shape->vertices;
732     edge *e = js->shape->edges;
733     vector zero;
734
735     vector_init(zero, 0, 0, 0);
736
737     /* sum all the vertex-vertex forces */
738     while(e) {
739         vector f;
740         coord mag;
741         vector_sub(e->left->vtx->v, e->right->vtx->v, f);
742         mag = js->stable_distance - magnitude(f);
743         vector_scale(f, mag);
744         vector_add_to(e->left->vtx->f, f);
745         vector_sub(zero, f, f);
746         vector_add_to(e->right->vtx->f, f);
747         e = e->next;
748     }
749
750     /* scale back the v-v force and add the spherical force
751      * then add the result to the vertex velocity, damping
752      * if necessary. Finally, move the vertex */
753     while(vtx) {
754         coord mag;
755         vector to_sphere;
756         vector_scale(vtx->f, js->hold_strength);
757         vector_copy(to_sphere, vtx->v);
758         mag = 1 - magnitude(to_sphere);
759         vector_scale(to_sphere, mag * js->spherify_strength);
760         vector_add_to(vtx->f, to_sphere);
761         vector_add_to(vtx->vel, vtx->f);
762         vector_init(vtx->f, 0, 0, 0);
763         mag = magnitude2(vtx->vel);
764         if(mag > js->damping_velocity)
765             vector_scale(vtx->vel, js->damping_factor);
766         vector_add_to(vtx->v, vtx->vel);
767         vtx = vtx->next;
768     }
769 }
770
771 /* These are the various initialization routines */
772
773 void init_texture(ModeInfo *mi)
774 {
775     XImage *img = xpm_to_ximage(mi->dpy, mi->xgwa.visual,
776                                mi->xgwa.colormap, jigglymap_xpm);
777
778     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
779                  img->width, img->height, 0, GL_RGBA,
780                  GL_UNSIGNED_BYTE, img->data);
781
782     XDestroyImage(img);
783 }
784
785 void setup_opengl(ModeInfo *mi, jigglystruct *js)
786 {
787     const GLfloat lpos0[4] = {-12, 8, 12, 0};
788     const GLfloat lpos1[4] = {7, -5, 0, 0};
789     const GLfloat lcol0[4] = {0.7f, 0.7f, 0.65f, 1};
790     const GLfloat lcol1[4] = {0.3f, 0.2f, 0.1f, 1};
791     const GLfloat scolor[4]= {0.9f, 0.9f, 0.9f, 0.5f};
792
793     glDrawBuffer(GL_BACK);
794     glClearColor(0, 0, 0, 0);
795     glShadeModel(GL_SMOOTH);
796     glEnable(GL_DEPTH_TEST);
797
798     if(js->do_wireframe) {
799         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
800     }
801     else {
802         glCullFace(GL_BACK);
803         glFrontFace(GL_CW);
804         glEnable(GL_CULL_FACE);
805     }
806
807     if(js->color_style != COLOR_STYLE_CHROME) {
808         glEnable(GL_LIGHTING);
809         glEnable(GL_LIGHT0);
810         glEnable(GL_LIGHT1);
811         
812         glLightfv(GL_LIGHT0, GL_POSITION, lpos0);
813         glLightfv(GL_LIGHT1, GL_POSITION, lpos1);
814         glLightfv(GL_LIGHT0, GL_DIFFUSE, lcol0);
815         glLightfv(GL_LIGHT1, GL_DIFFUSE, lcol1);
816
817         glEnable(GL_COLOR_MATERIAL);
818         glColor4fv(js->jiggly_color);
819
820         glMaterialfv(GL_FRONT, GL_SPECULAR, scolor);
821         glMateriali(GL_FRONT, GL_SHININESS, js->shininess);
822     }
823     else { /* chrome */
824         init_texture(mi);
825         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
826         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
827         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
828         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
829         glEnable(GL_TEXTURE_GEN_S);
830         glEnable(GL_TEXTURE_GEN_T);
831         glEnable(GL_TEXTURE_2D);
832         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
833         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
834         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
835     }
836 }
837
838 int parse_color(jigglystruct *js)
839 {
840     int r, g, b;
841     if(!strcmp(color, "clownbarf")) {
842         js->color_style = COLOR_STYLE_CLOWNBARF;
843         return 1;
844     }
845     else if(!strcmp(color, "flowerbox")) {
846         js->color_style = COLOR_STYLE_FLOWERBOX;
847         return 1;
848     }
849     else if(!strcmp(color, "chrome")) {
850         js->color_style = COLOR_STYLE_CHROME;
851         return 1;
852     }
853     else if(!strcmp(color, "cycle")) {
854         js->color_style = COLOR_STYLE_CYCLE;
855         js->jiggly_color[0] = ((float)random()) / REAL_RAND_MAX * 0.7 + 0.3;
856         js->jiggly_color[1] = ((float)random()) / REAL_RAND_MAX * 0.7 + 0.3;
857         js->jiggly_color[2] = ((float)random()) / REAL_RAND_MAX * 0.7 + 0.3;
858         js->jiggly_color[3] = 1.0f;
859         js->color_dir[0] = ((float)random()) / REAL_RAND_MAX / 100.0;
860         js->color_dir[1] = ((float)random()) / REAL_RAND_MAX / 100.0;
861         js->color_dir[2] = ((float)random()) / REAL_RAND_MAX / 100.0;
862         return 1;
863     }
864     else
865         js->color_style = 0;
866     if(strlen(color) != 7)
867         return 0;
868     if(sscanf(color,"#%02x%02x%02x", &r, &g, &b) != 3) {
869         return 0;
870     }
871     js->jiggly_color[0] = ((float)r)/255;
872     js->jiggly_color[1] = ((float)g)/255;
873     js->jiggly_color[2] = ((float)b)/255;
874     js->jiggly_color[3] = 1.0f;
875
876     return 1;
877 }
878
879 void randomize_parameters(jigglystruct *js) {
880     do_tetrahedron = random() & 1;
881     js->do_wireframe = !(random() & 3);
882     js->color_style = random() % 5;
883     if(js->color_style == COLOR_STYLE_NORMAL
884         || js->color_style == COLOR_STYLE_CYCLE) {
885         js->jiggly_color[0] = ((float)random()) / REAL_RAND_MAX * 0.5 + 0.5;
886         js->jiggly_color[1] = ((float)random()) / REAL_RAND_MAX * 0.5 + 0.5;
887         js->jiggly_color[2] = ((float)random()) / REAL_RAND_MAX * 0.5 + 0.5;
888         js->jiggly_color[3] = 1.0f;
889         if(js->color_style == COLOR_STYLE_CYCLE) {
890             js->color_dir[0] = ((float)random()) / REAL_RAND_MAX / 100.0;
891             js->color_dir[1] = ((float)random()) / REAL_RAND_MAX / 100.0;
892             js->color_dir[2] = ((float)random()) / REAL_RAND_MAX / 100.0;
893         }
894     }
895     if((js->color_style != COLOR_STYLE_CHROME) && (random() & 1))
896         js->spooky = (random() % 6) + 4;
897     else 
898         js->spooky = 0;
899     js->shininess = random() % 200;
900     speed = (random() % 700) + 50;
901     /* It' kind of dull if this is too high when it starts as a sphere */
902     spherism = do_tetrahedron ? (random() % 500) + 20 : (random() % 100) + 10;
903     hold = (random() % 800) + 100;
904     distance = (random() % 500) + 100;
905     damping = (random() % 800) + 50;
906 }    
907
908 void calculate_parameters(jigglystruct *js, int subdivs) {
909     /* try to compensate for the inherent instability at
910      * low complexity. */
911     float dist_factor = (subdivs == 6) ? 2 : (subdivs == 5) ? 1 : 0.5;
912
913     js->stable_distance = ((float)distance / 500.0) 
914         * (STABLE_DISTANCE / dist_factor);
915     js->hold_strength = (float)hold / 10000.0;
916     js->spherify_strength = (float)spherism / 10000.0;
917     js->damping_velocity = (float)damping / 100000.0;
918     js->damping_factor = 
919         0.001/max(js->hold_strength, js->spherify_strength);
920
921     js->speed = (float)speed / 1000.0;
922 }
923
924 /* The screenhack related functions begin here */
925
926 Bool jigglypuff_handle_event(ModeInfo *mi, XEvent *event)
927 {
928     jigglystruct *js = &jss[MI_SCREEN(mi)];
929     
930     if(event->xany.type == ButtonPress &&
931        event->xbutton.button & Button1) {
932         js->button_down = 1;
933         gltrackball_start(js->trackball, event->xbutton.x, event->xbutton.y,
934                           MI_WIDTH(mi), MI_HEIGHT(mi));
935         return True;
936     }
937     else if(event->xany.type == ButtonRelease &&
938             event->xbutton.button & Button1) {
939         js->button_down = 0;
940         return True;
941     }
942     else if(event->xany.type == MotionNotify && js->button_down) {
943         gltrackball_track(js->trackball, event->xmotion.x, event->xmotion.y,
944                           MI_WIDTH(mi), MI_HEIGHT(mi));
945         return True;
946     }
947     return False;
948 }
949
950 void reshape_jigglypuff(ModeInfo *mi, int width, int height)
951 {
952     GLfloat aspect = (GLfloat)width / (GLfloat)height;
953
954     glViewport(0, 0, width, height);
955     glMatrixMode(GL_PROJECTION);
956     glLoadIdentity();
957     glFrustum(-0.5*aspect, 0.5*aspect, -0.5, 0.5, 1, 20);
958 /*    glTranslatef(0, 0, -10);*/
959 }
960
961 void draw_jigglypuff(ModeInfo *mi)
962 {
963     jigglystruct *js = &jss[MI_SCREEN(mi)];
964     
965     glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(js->glx_context));
966     
967     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
968
969     glMatrixMode(GL_MODELVIEW);
970     glLoadIdentity();
971     glTranslatef(0,0,-10);
972
973     glRotatef(js->angle, sin(js->axis), cos(js->axis), -sin(js->axis));
974     glTranslatef(0, 0, 5);
975     if(!(js->button_down)) {
976         if((js->angle += js->speed) >= 360.0f ) {
977             js->angle -= 360.0f;
978         }
979         if((js->axis+=0.01f) >= 2*M_PI ) {
980             js->axis -= 2*M_PI;
981         }
982     }
983     gltrackball_rotate(js->trackball);
984
985     if(js->color_style == COLOR_STYLE_CYCLE) {
986         int i;
987         vector_add(js->jiggly_color, js->color_dir, js->jiggly_color);
988         
989         for(i=0; i<3; i++) {
990             if(js->jiggly_color[i] > 1.0 || js->jiggly_color[i] < 0.3) {
991                 js->color_dir[i] = (-js->color_dir[i]);
992                 js->jiggly_color[i] += js->color_dir[i];
993             }
994         }
995         glColor4fv(js->jiggly_color);
996     }
997     
998     jigglypuff_render(js);
999     if(MI_IS_FPS(mi))
1000         do_fps(mi);
1001     glFinish();
1002     update_shape(js);
1003     glXSwapBuffers(MI_DISPLAY(mi), MI_WINDOW(mi));
1004 }
1005
1006 void init_jigglypuff(ModeInfo *mi)
1007 {
1008     jigglystruct *js;
1009     int subdivs;
1010
1011     if(!jss) {
1012         jss = (jigglystruct*)
1013             calloc(MI_NUM_SCREENS(mi), sizeof(jigglystruct));
1014         if(!jss) {
1015             fprintf(stderr, "%s: No..memory...must...abort..\n", progname);
1016             exit(1);
1017         }
1018     }
1019
1020     js = &jss[MI_SCREEN(mi)];
1021
1022     js->do_wireframe = MI_IS_WIREFRAME(mi);
1023
1024     js->shininess = shininess;
1025
1026     subdivs = (complexity==1) ? 4 : (complexity==2) ? 5
1027         : (complexity==3) ? 6 : 5;
1028
1029     js->spooky = spooky << (subdivs-3);
1030
1031     if(!parse_color(js)) {
1032         fprintf(stderr, "%s: Bad color specification: '%s'.\n", progname, color);
1033         exit(-1);
1034     }
1035     
1036     if(random_parms)
1037         randomize_parameters(js);
1038
1039     js->shape = tesselated_tetrahedron(1, subdivs, js);
1040
1041     if(!do_tetrahedron)
1042         solid_spherify(js->shape, 1);
1043
1044     if(js->color_style == COLOR_STYLE_CLOWNBARF)
1045         clownbarf_colorize(js->shape);
1046
1047     calculate_parameters(js, subdivs);
1048
1049     if((js->glx_context = init_GL(mi)) != NULL) {
1050         glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(js->glx_context));
1051         setup_opengl(mi, js);
1052         reshape_jigglypuff(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
1053     }
1054     else {
1055         MI_CLEARWINDOW(mi);
1056     }
1057     js->trackball = gltrackball_init();
1058     _DEBUG("distance : %f\nhold : %f\nspherify : %f\ndamping : %f\ndfact : %f\n",
1059            js->stable_distance, js->hold_strength, js->spherify_strength,
1060            js->damping_velocity, js->damping_factor);
1061     _DEBUG("wire : %d\nspooky : %d\nstyle : %d\nshininess : %d\n",
1062            js->do_wireframe, js->spooky, js->color_style, js->shininess);
1063 }
1064
1065 /* This is the end of the file */
1066
1067 #endif /* USE_GL */
1068
1069
1070
1071
1072
1073
1074