From http://www.jwz.org/xscreensaver/xscreensaver-5.27.tar.gz
[xscreensaver] / hacks / glx / mirrorblob.c
1 /* mirrorblob  Copyright (c) 2003 Jon Dowdall <jon.dowdall@bigpond.com> */
2 /*
3  * Permission to use, copy, modify, and distribute this software and its
4  * documentation for any purpose and without fee is hereby granted,
5  * provided that the above copyright notice appear in all copies and that
6  * both that copyright notice and this permission notice appear in
7  * supporting documentation.
8  *
9  * This file is provided AS IS with no warranties of any kind.  The author
10  * shall have no liability with respect to the infringement of copyrights,
11  * trade secrets or any patents by this file or any part thereof.  In no
12  * event will the author be liable for any lost revenue or profits or
13  * other special, indirect and consequential damages.
14  *
15  * Revision History:
16  * 23-Sep-2003:  jon.dowdall@bigpond.com  Created module "blob"
17  * 19-Oct-2003:  jon.dowdall@bigpond.com  Added texturing
18  * 21-Oct-2003:                           Renamed to mirrorblob
19  * 10-Feb-2004:  jon.dowdall@bigpond.com  Added motion blur
20  * 28-Jan-2006:  jon.dowdall@bigpond.com  Big clean up and bug fixes
21  * 13-Apr-2009:  jon.dowdall@gmail.com    Fixed Mac version
22  *
23  * The mirrorblob screensaver draws a pulsing blob on the screen.  Options
24  * include adding a background (via screen_to_texture), texturing the blob,
25  * making the blob semi-transparent and varying the resolution of the blob
26  * tessellation.
27  *
28  * The blob was inspired by a lavalamp is in no way a simulation.  The code is
29  * just an attempt to generate some eye-candy.
30  *
31  * Much of xmirrorblob code framework is taken from the pulsar module by David
32  * Konerding and the glslideshow by Mike Oliphant and Jamie Zawinski.
33  *
34  */
35
36 #include <math.h>
37
38 #ifdef STANDALONE
39 #define DEFAULTS "*delay:             " DEF_DELAY "\n"                      \
40                  "*showFPS:           " DEF_FPS   "\n"                      \
41                  "*useSHM:              True       \n"                      \
42                  "*desktopGrabber:  xscreensaver-getimage -no-desktop %s\n" \
43                  "*grabDesktopImages:   True  \n"                           \
44                  "*chooseRandomImages:  True  \n"
45
46 # define refresh_mirrorblob 0
47 /*
48 # define mirrorblob_handle_event 0
49 */
50 # include "xlockmore.h"
51 #else /* !STANDALONE */
52 # include "xlock.h"        /* from the xlockmore distribution */
53 #endif /* !STANDALONE */
54
55 #ifdef USE_GL /* whole file */
56
57
58 #define DEF_DELAY            "10000"
59 #define DEF_FPS              "False"
60 #define DEF_WIRE             "False"
61 #define DEF_BLEND            "1.0"
62 #define DEF_FOG              "False"
63 #define DEF_ANTIALIAS        "False"
64 #define DEF_WALLS            "False"
65 #define DEF_COLOUR           "False"
66 #define DEF_ASYNC            "True"
67 #define DEF_TEXTURE          "True"
68 #define DEF_OFFSET_TEXTURE   "False"
69 #define DEF_PAINT_BACKGROUND "True"
70 #define DEF_RESOLUTION       "30"
71 #define DEF_BUMPS            "10"
72 #define DEF_MOTION_BLUR      "0.0"
73 #define DEF_INCREMENTAL      "0"
74 #define DEF_HOLD_TIME        "30.0"
75 #define DEF_FADE_TIME        "5.0"
76 #define DEF_ZOOM             "1.0"
77
78 #ifdef HAVE_XMU
79 # ifndef VMS
80 #  include <X11/Xmu/Drawing.h>
81 #else  /* VMS */
82 #  include <Xmu/Drawing.h>
83 # endif /* VMS */
84 #endif
85
86 #include "gltrackball.h"
87 #include "grab-ximage.h"
88
89 #undef countof
90 #define countof(x) (sizeof((x)) / sizeof((*x)))
91
92 #define PI  3.1415926535897
93
94 /* Options from command line */
95 static GLfloat blend;
96 static Bool wireframe;
97 static Bool do_fog;
98 static Bool do_antialias;
99 static Bool do_walls;
100 static Bool do_texture;
101 static Bool do_paint_background;
102 static Bool do_colour;
103 static Bool offset_texture;
104 static int resolution;
105 static int bumps;
106 static float motion_blur;
107 static float fade_time;
108 static float hold_time;
109 static float zoom;
110
111 /* Internal parameters based on supplied options */
112 static Bool culling;
113 static Bool load_textures;
114
115 static XrmOptionDescRec opts[] = {
116     {"-wire",             ".blob.wire",             XrmoptionNoArg, "true" },
117     {"+wire",             ".blob.wire",             XrmoptionNoArg, "false" },
118     {"-blend",            ".blob.blend",            XrmoptionSepArg, 0 },
119     {"-fog",              ".blob.fog",              XrmoptionNoArg, "true" },
120     {"+fog",              ".blob.fog",              XrmoptionNoArg, "false" },
121     {"-antialias",        ".blob.antialias",        XrmoptionNoArg, "true" },
122     {"+antialias",        ".blob.antialias",        XrmoptionNoArg, "false" },
123     {"-walls",            ".blob.walls",            XrmoptionNoArg, "true" },
124     {"+walls",            ".blob.walls",            XrmoptionNoArg, "false" },
125     {"-texture",          ".blob.texture",          XrmoptionNoArg, "true" },
126     {"+texture",          ".blob.texture",          XrmoptionNoArg, "false" },
127     {"-colour",           ".blob.colour",           XrmoptionNoArg, "true" },
128     {"+colour",           ".blob.colour",           XrmoptionNoArg, "false" },
129     {"-offset-texture",   ".blob.offsetTexture",    XrmoptionNoArg, "true" },
130     {"+offset-texture",   ".blob.offsetTexture",    XrmoptionNoArg, "false" },
131     {"-paint-background", ".blob.paintBackground",  XrmoptionNoArg, "true" },
132     {"+paint-background", ".blob.paintBackground",  XrmoptionNoArg, "false" },
133     {"-resolution",       ".blob.resolution",       XrmoptionSepArg, NULL },
134     {"-bumps",            ".blob.bumps",            XrmoptionSepArg, NULL },
135     {"-motion-blur",      ".blob.motionBlur",       XrmoptionSepArg, 0 },
136     {"-fade-time",        ".blob.fadeTime",         XrmoptionSepArg, 0 },
137     {"-hold-time",        ".blob.holdTime",         XrmoptionSepArg, 0 },
138     {"-zoom",             ".blob.zoom",             XrmoptionSepArg, 0 },
139 };
140
141 static argtype vars[] = {
142     {&wireframe,    "wire",         "Wire",      DEF_WIRE,      t_Bool},
143     {&blend,        "blend",        "Blend",     DEF_BLEND,     t_Float},
144     {&do_fog,       "fog",          "Fog",       DEF_FOG,       t_Bool},
145     {&do_antialias, "antialias",    "Antialias", DEF_ANTIALIAS, t_Bool},
146     {&do_walls,     "walls",        "Walls",     DEF_WALLS,     t_Bool},
147     {&do_texture,   "texture",      "Texture",   DEF_TEXTURE,   t_Bool},
148     {&do_colour,    "colour",       "Colour",    DEF_COLOUR,   t_Bool},
149     {&offset_texture, "offsetTexture","OffsetTexture", DEF_OFFSET_TEXTURE, t_Bool},
150     {&do_paint_background,"paintBackground","PaintBackground", DEF_PAINT_BACKGROUND, t_Bool},
151     {&resolution,   "resolution",   "Resolution",   DEF_RESOLUTION,   t_Int},
152     {&bumps,        "bumps",        "Bump",         DEF_BUMPS, t_Int},
153     {&motion_blur,  "motionBlur",   "MotionBlur",   DEF_MOTION_BLUR,  t_Float},
154     {&fade_time,    "fadeTime",     "FadeTime",     DEF_FADE_TIME,    t_Float},
155     {&hold_time,    "holdTime",     "HoldTime",     DEF_HOLD_TIME,    t_Float},
156     {&zoom,         "zoom",         "Zoom",         DEF_ZOOM,         t_Float},
157 };
158
159
160 static OptionStruct desc[] =
161 {
162     {"-/+ wire", "whether to do use wireframe instead of filled (faster)"},
163     {"-/+ blend", "whether to do enable blending (slower)"},
164     {"-/+ fog", "whether to do enable fog (slower)"},
165     {"-/+ antialias", "whether to do enable antialiased lines (slower)"},
166     {"-/+ walls", "whether to add walls to the blob space (slower)"},
167     {"-/+ texture", "whether to add a texture to the blob (slower)"},
168     {"-/+ colour", "whether to colour the blob"},
169     {"-/+ offset_texture", "whether to offset texture co-ordinates"},
170     {"-/+ paint_background", "whether to display a background texture (slower)"},
171     {"-resolution", "Resolution of blob tesselation"},
172     {"-bumps", "Number of bumps used to disturb blob"},
173     {"-motion_blur", "Fade blob images (higher number = faster fade)"},
174     {"-fade_time", "Number of frames to transistion to next image"},
175     {"-hold_time", "Number of frames before next image"},
176 };
177
178 ENTRYPOINT ModeSpecOpt mirrorblob_opts = {countof(opts), opts, countof(vars), vars, desc};
179
180 #ifdef USE_MODULES
181 ModStruct   mirrorblob_description =
182 {"mirrorblob", "init_mirrorblob", "draw_mirrorblob", "release_mirrorblob",
183  "draw_mirrorblob", "init_mirrorblob", "handle_event", &mirrorblob_opts,
184  1000, 1, 2, 1, 4, 1.0, "",
185  "OpenGL mirrorblob", 0, NULL};
186 #endif
187
188 /*****************************************************************************
189  * Types used in blob code
190  *****************************************************************************/
191
192 typedef struct
193 {
194   GLfloat x, y;
195 } Vector2D;
196
197 typedef struct
198 {
199   GLfloat x, y, z;
200 } Vector3D;
201
202 typedef struct
203 {
204   GLfloat w;
205   GLfloat x;
206   GLfloat y;
207   GLfloat z;
208 } Quaternion;
209
210 typedef struct
211 {
212   GLubyte red, green, blue, alpha;
213 } Colour;
214
215 typedef struct
216 {
217   Vector3D initial_position;
218   Vector3D position;
219   Vector3D normal;
220 } Node_Data;
221
222 typedef struct
223 {
224   int node1, node2, node3;
225   Vector3D normal;
226   double length1, length2, length3;
227 } Face_Data;
228
229 /* Structure to hold data about bumps used to distortion sphere */
230 typedef struct
231 {
232   double cx, cy, cpower, csize;
233   double ax, ay, power, size;
234   double mx, my, mpower, msize;
235   double vx, vy, vpower, vsize;
236   Vector3D pos;
237 } Bump_Data;
238
239 /* Vertices of a tetrahedron */
240 #define sqrt_3 0.5773502692
241 /*#undef sqrt_3
242 #define sqrt_3 1.0*/
243 #define PPP {  sqrt_3,  sqrt_3,  sqrt_3 }       /* +X, +Y, +Z */
244 #define MMP { -sqrt_3, -sqrt_3,  sqrt_3 }       /* -X, -Y, +Z */
245 #define MPM { -sqrt_3,  sqrt_3, -sqrt_3 }       /* -X, +Y, -Z */
246 #define PMM {  sqrt_3, -sqrt_3, -sqrt_3 }       /* +X, -Y, -Z */
247
248 /* Structure describing a tetrahedron */
249 static Vector3D tetrahedron[4][3] = {
250     {PPP, MMP, MPM},
251     {PMM, MPM, MMP},
252     {PPP, MPM, PMM},
253     {PPP, PMM, MMP}
254 };
255
256 /*****************************************************************************
257  * Static blob data
258  *****************************************************************************/
259
260 static const Vector3D zero_vector = { 0.0, 0.0, 0.0 };
261
262 /* Use 2 textures to allow a gradual fade between images */
263 #define NUM_TEXTURES 2
264 #define BUMP_ARRAY_SIZE 1024
265
266 typedef enum
267 {
268   INITIALISING,
269   HOLDING,
270   LOADING,
271   TRANSITIONING
272 } Frame_State;
273
274 /* structure for holding the mirrorblob data */
275 typedef struct {
276   int screen_width, screen_height;
277   GLXContext *glx_context;
278   Window window;
279   XColor fg, bg;
280
281   /* Parameters controlling the position of the blob as a whole */
282   Vector3D blob_center;
283   Vector3D blob_anchor;
284   Vector3D blob_velocity;
285   Vector3D blob_force;
286
287   /* Count of the total number of nodes and faces used to tesselate the blob */
288   int num_nodes;
289   int num_faces;
290
291   Node_Data *nodes;
292   Face_Data *faces;
293   
294   Vector3D *dots;
295   Vector3D *normals;
296   Colour   *colours;
297   Vector2D *tex_coords;
298
299   /* Pointer to the bump function results */
300   double *bump_shape, *wall_shape;
301
302   Bump_Data *bump_data;
303
304   /* Use 2 textures to allow a gradual fade between images */
305   int current_texture;
306
307   /* Ratio of used texture size to total texture size */
308   GLfloat tex_width[NUM_TEXTURES], tex_height[NUM_TEXTURES];
309   GLuint textures[NUM_TEXTURES];
310
311   Frame_State state;
312   double state_start_time;
313
314   int colour_cycle;
315
316   Bool mipmap_p;
317   Bool waiting_for_image_p;
318   Bool first_image_p;
319
320   trackball_state *trackball;
321   int button_down;
322
323 } mirrorblobstruct;
324
325 static mirrorblobstruct *Mirrorblob = NULL;
326
327 /******************************************************************************
328  *
329  * Returns the current time in seconds as a double.  Shamelessly borrowed from
330  * glslideshow.
331  *
332  */
333 static double
334 double_time (void)
335 {
336   struct timeval now;
337 # ifdef GETTIMEOFDAY_TWO_ARGS
338   struct timezone tzp;
339   gettimeofday(&now, &tzp);
340 # else
341   gettimeofday(&now);
342 # endif
343
344   return (now.tv_sec + ((double) now.tv_usec * 0.000001));
345 }
346
347 /******************************************************************************
348  *
349  * Change to the projection matrix and set our viewing volume.
350  *
351  */
352 static void
353 reset_projection(int width, int height)
354 {
355   glMatrixMode (GL_PROJECTION);
356   glLoadIdentity ();
357   gluPerspective (60.0, 1.0, 1.0, 1024.0 );
358   glMatrixMode (GL_MODELVIEW);
359   glLoadIdentity ();
360 }
361
362 /******************************************************************************
363  *
364  * Calculate the dot product of two vectors u and v
365  * Dot product u.v = |u||v|cos(theta)
366  * Where theta = angle between u and v
367  */
368 static inline double
369 dot (const Vector3D u, const Vector3D v)
370 {
371   return (u.x * v.x) + (u.y * v.y) + (u.z * v.z);
372 }
373
374 /******************************************************************************
375  *
376  * Calculate the cross product of two vectors.
377  * Gives a vector perpendicular to u and v with magnitude |u||v|sin(theta)
378  * Where theta = angle between u and v
379  */
380 static inline Vector3D
381 cross (const Vector3D u, const Vector3D v)
382 {
383   Vector3D result;
384
385   result.x = (u.y * v.z - u.z * v.y);
386   result.y = (u.z * v.x - u.x * v.z);
387   result.z = (u.x * v.y - u.y * v.x);
388
389   return result;
390 }
391
392 /******************************************************************************
393  *
394  * Add vector v to vector u
395  */
396 static inline void
397 add (Vector3D *u, const Vector3D v)
398 {
399   u->x = u->x + v.x;
400   u->y = u->y + v.y;
401   u->z = u->z + v.z;
402 }
403
404 /******************************************************************************
405  *
406  * Subtract vector v from vector u
407  */
408 static inline Vector3D
409 subtract (const Vector3D u, const Vector3D v)
410 {
411   Vector3D result;
412
413   result.x = u.x - v.x;
414   result.y = u.y - v.y;
415   result.z = u.z - v.z;
416
417   return result;
418 }
419
420 /******************************************************************************
421  *
422  * multiply vector v by scalar s
423  */
424 static inline Vector3D
425 scale (const Vector3D v, const double s)
426 {
427   Vector3D result;
428     
429   result.x = v.x * s;
430   result.y = v.y * s;
431   result.z = v.z * s;
432   return result;
433 }
434
435 /******************************************************************************
436  *
437  * normalise vector v
438  */
439 static inline Vector3D
440 normalise (const Vector3D v)
441 {
442   Vector3D result;
443   double magnitude;
444
445   magnitude = sqrt (dot(v, v));
446
447   if (magnitude > 1e-300)
448     {
449       result = scale (v, 1.0 / magnitude);
450     }
451   else
452     {
453       printf("zero\n");
454       result = zero_vector;
455     }
456   return result;
457 }
458
459 /******************************************************************************
460  *
461  * Calculate the transform matrix for the given quaternion
462  */
463 static void
464 quaternion_transform (Quaternion q, GLfloat * transform)
465 {
466   GLfloat x, y, z, w;
467   x = q.x;
468   y = q.y;
469   z = q.z;
470   w = q.w;
471
472   transform[0] = (w * w) + (x * x) - (y * y) - (z * z);
473   transform[1] = (2.0 * x * y) + (2.0 * w * z);
474   transform[2] = (2.0 * x * z) - (2.0 * w * y);
475   transform[3] = 0.0;
476
477   transform[4] = (2.0 * x * y) - (2.0 * w * z);
478   transform[5] = (w * w) - (x * x) + (y * y) - (z * z);
479   transform[6] = (2.0 * y * z) + (2.0 * w * x);
480   transform[7] = 0.0;
481
482   transform[8] = (2.0 * x * z) + (2.0 * w * y);
483   transform[9] = (2.0 * y * z) - (2.0 * w * x);
484   transform[10] = (w * w) - (x * x) - (y * y) + (z * z);
485   transform[11] = 0.0;
486
487   transform[12] = 0.0;
488   transform[13] = 0.0;
489   transform[14] = 0.0;
490   transform[15] = (w * w) + (x * x) + (y * y) + (z * z);
491 }
492
493 /******************************************************************************
494  *
495  * Apply a matrix transform to the given vector
496  */
497 static inline Vector3D
498 vector_transform (Vector3D u, GLfloat * t)
499 {
500   Vector3D result;
501
502   result.x = (u.x * t[0] + u.y * t[4] + u.z * t[8] + 1.0 * t[12]);
503   result.y = (u.x * t[1] + u.y * t[5] + u.z * t[9] + 1.0 * t[13]);
504   result.z = (u.x * t[2] + u.y * t[6] + u.z * t[10] + 1.0 * t[14]);
505
506   return result;
507 }
508
509 /******************************************************************************
510  *
511  * Return a node that is on an arc between node1 and node2, where distance
512  * is the proportion of the distance from node1 to the total arc.
513  */
514 static Vector3D
515 partial (Vector3D node1, Vector3D node2, double distance)
516 {
517   Vector3D result;
518   Vector3D rotation_axis;
519   GLfloat transformation[16];
520   double angle;
521   Quaternion rotation;
522
523   rotation_axis = normalise (cross (node1, node2));
524   angle = acos (dot (node1, node2)) * distance;
525
526   rotation.x = rotation_axis.x * sin (angle / 2.0);
527   rotation.y = rotation_axis.y * sin (angle / 2.0);
528   rotation.z = rotation_axis.z * sin (angle / 2.0);
529   rotation.w = cos (angle / 2.0);
530
531   quaternion_transform (rotation, transformation);
532
533   result = vector_transform (node1, transformation);
534
535   return result;
536 }
537
538 /****************************************************************************
539  *
540  * Callback indicating a texture has loaded
541  */
542 static void
543 image_loaded_cb (const char *filename, XRectangle *geometry,
544                  int image_width, int image_height, 
545                  int texture_width, int texture_height,
546                  void *closure)
547 {
548   mirrorblobstruct *mp = (mirrorblobstruct *) closure;
549   GLint texid = -1;
550   int texture_index = -1;
551   int i;
552
553   glGetIntegerv (GL_TEXTURE_BINDING_2D, &texid);
554   if (texid < 0) abort();
555
556   for (i = 0; i < NUM_TEXTURES; i++) {
557     if (mp->textures[i] == texid) {
558       texture_index = i;
559       break;
560     }
561   }
562   if (texture_index < 0) abort();
563
564   mp->tex_width [texture_index] =  (GLfloat) image_width  / texture_width;
565   mp->tex_height[texture_index] = -(GLfloat) image_height / texture_height;
566
567   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
568   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
569                    (mp->mipmap_p ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR));
570   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
571   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
572   glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
573
574   mp->waiting_for_image_p = False;
575   mp->first_image_p = True;
576 }
577
578 /* Load a new file into a texture
579  */
580 static void
581 grab_texture(ModeInfo *mi, int texture_index)
582 {
583   mirrorblobstruct *mp = &Mirrorblob[MI_SCREEN(mi)];
584         
585   {
586     int w = (MI_WIDTH(mi)  / 2) - 1;
587     int h = (MI_HEIGHT(mi) / 2) - 1;
588     if (w <= 10) w = 10;
589     if (h <= 10) h = 10;
590         
591     mp->waiting_for_image_p = True;
592     mp->mipmap_p = True;
593     load_texture_async (mi->xgwa.screen, mi->window,
594                         *mp->glx_context, w, h, mp->mipmap_p, 
595                         mp->textures[texture_index],
596                         image_loaded_cb, mp);
597   }
598 }
599
600 /******************************************************************************
601  *
602  * Generate internal parameters based on supplied options the parameters to
603  * ensure they are consistant.
604  */
605 static void
606 set_parameters(void)
607 {
608 # ifdef HAVE_JWZGLES /* #### glPolygonMode other than GL_FILL unimplemented */
609   wireframe = 0;
610 # endif
611
612   /* In wire frame mode do not draw a texture */
613   if (wireframe)
614     {
615       do_texture = False;
616       blend = 1.0;
617     }
618     
619   /* Need to load textures if either the blob or the backgound has an image */
620   if (do_texture || do_paint_background)
621     {
622       load_textures = True;
623     }
624   else
625     {
626       load_textures = False;
627     }
628     
629   /* If theres no texture don't calculate co-ordinates. */
630   if (!do_texture)
631     {
632       offset_texture = False;
633     }
634     
635   culling = True;
636 }
637
638 /******************************************************************************
639  *
640  * Initialise the openGL state data.
641  */
642 static void
643 initialize_gl(ModeInfo *mi, GLsizei width, GLsizei height)
644 {
645   mirrorblobstruct *gp = &Mirrorblob[MI_SCREEN(mi)];
646     
647   /* Lighting values */
648   GLfloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
649
650   GLfloat lightPos0[] = {500.0f, 100.0f, 200.0f, 1.0f };
651   GLfloat whiteLight0[] = { 0.0f, 0.0f, 0.0f, 1.0f };
652   GLfloat sourceLight0[] = { 0.6f, 0.6f, 0.6f, 1.0f };
653   GLfloat specularLight0[] = { 0.8f, 0.8f, 0.9f, 1.0f };
654
655   GLfloat lightPos1[] = {-50.0f, -100.0f, 2500.0f, 1.0f };
656   GLfloat whiteLight1[] = { 0.0f, 0.0f, 0.0f, 1.0f };
657   GLfloat sourceLight1[] = { 0.6f, 0.6f, 0.6f, 1.0f };
658   GLfloat specularLight1[] = { 0.7f, 0.7f, 0.7f, 1.0f };
659
660   GLfloat specref[] = { 1.0f, 1.0f, 1.0f, 1.0f };
661
662   GLfloat fogColor[4] = { 0.4, 0.4, 0.5, 0.1 };
663
664   /* Set the internal parameters based on the configuration settings */
665   set_parameters();
666
667   /* Set the viewport to the width and heigh of the window */
668   glViewport (0, 0, width, height ); 
669
670   if (do_antialias)
671     {
672       blend = 1.0;
673       glEnable(GL_LINE_SMOOTH);
674       glEnable(GL_POLYGON_SMOOTH);
675     }
676
677   /* The blend function is used for trasitioning between two images even when
678    * blend is not selected.
679    */
680   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
681  
682   if (do_fog)
683     {
684       glEnable(GL_FOG);
685       glFogfv(GL_FOG_COLOR, fogColor);
686       glFogf(GL_FOG_DENSITY, 0.50);
687       glFogf(GL_FOG_START, 15.0);
688       glFogf(GL_FOG_END, 30.0);
689     }
690
691   /* Set the shading model to smooth (Gouraud shading). */
692   glShadeModel (GL_SMOOTH);
693
694   glLightModelfv (GL_LIGHT_MODEL_AMBIENT, ambientLight);
695   glLightfv (GL_LIGHT0, GL_AMBIENT, whiteLight0);
696   glLightfv (GL_LIGHT0, GL_DIFFUSE, sourceLight0);
697   glLightfv (GL_LIGHT0, GL_SPECULAR, specularLight0);
698   glLightfv (GL_LIGHT0, GL_POSITION, lightPos0);
699   glEnable (GL_LIGHT0);
700   glLightfv (GL_LIGHT1, GL_AMBIENT, whiteLight1);
701   glLightfv (GL_LIGHT1, GL_DIFFUSE, sourceLight1);
702   glLightfv (GL_LIGHT1, GL_SPECULAR, specularLight1);
703   glLightfv (GL_LIGHT1, GL_POSITION, lightPos1);
704   glEnable (GL_LIGHT1);
705   glEnable (GL_LIGHTING);
706
707   /* Enable color tracking */
708   glEnable (GL_COLOR_MATERIAL);
709
710   /* Set Material properties to follow glColor values */
711   glColorMaterial (GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
712
713   /* Set all materials to have specular reflectivity */
714   glMaterialfv (GL_FRONT, GL_SPECULAR, specref);
715   glMateriali (GL_FRONT, GL_SHININESS, 32);
716
717   /* Let GL implementation scale normal vectors. */
718   glEnable (GL_NORMALIZE);
719
720   /* Enable Arrays */
721   if (load_textures)
722     {
723       glLightModeli (GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
724       glEnable (GL_TEXTURE_2D);
725
726       gp->current_texture = 0;
727       glGenTextures(NUM_TEXTURES, gp->textures);
728       grab_texture(mi, gp->current_texture);
729
730       glMatrixMode (GL_TEXTURE);
731       glRotated (180.0, 1.0, 0.0, 0.0);
732       glMatrixMode (GL_MODELVIEW);
733     }
734
735   /* Clear the buffer since this is not done during a draw with motion blur */
736   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
737 }
738
739 /******************************************************************************
740  *
741  * Initialise the openGL state data.
742  */
743 static void
744 set_blob_gl_state(GLfloat alpha)
745 {
746   if (do_antialias)
747     {
748       glEnable(GL_LINE_SMOOTH);
749       glEnable(GL_POLYGON_SMOOTH);
750     }
751
752   if (wireframe)
753     {
754       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
755     }
756   else
757     {
758       glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
759     }
760
761   /* The blend function is used for trasitioning between two images even when
762    * blend is not selected.
763    */
764   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
765  
766   /* Culling. */
767   if (culling)
768     {
769       glCullFace (GL_BACK);
770       glEnable (GL_CULL_FACE);
771       glFrontFace (GL_CCW);
772     }
773   else
774     {
775       glDisable (GL_CULL_FACE);
776     }
777     
778   if (blend < 1.0)
779     {
780       glEnable (GL_BLEND);
781       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
782       /* Set the default blob colour to off-white. */
783       glColor4f (0.9, 0.9, 1.0, alpha);
784     }
785   else
786     {
787       glDisable(GL_BLEND);
788       glColor4f (0.9, 0.9, 1.0, 1.0);
789     }
790     
791   glEnable(GL_DEPTH_TEST);
792   glEnable(GL_LIGHTING);
793 }
794
795 /******************************************************************************
796  *
797  * Initialise the data required to draw the blob allocating the memory as
798  * necessary.
799  *
800  * Return 0 on success.
801  */
802 static int
803 initialise_blob(mirrorblobstruct *gp,
804                 int width,
805                 int height,
806                 int bump_array_size)
807 {
808   /* Loop variables */    
809   int i, u, v, node, side, face, base, base2 = 0;
810   int nodes_on_edge = resolution;
811   Vector3D node1, node2, result;
812
813   if (nodes_on_edge < 2)
814     return -1;
815
816   gp->num_nodes = 2 * nodes_on_edge * nodes_on_edge - 4 * nodes_on_edge + 4;
817   gp->num_faces = 4 * (nodes_on_edge - 1) * (nodes_on_edge - 1);
818  
819   gp->nodes = (Node_Data *) malloc (gp->num_nodes * sizeof (Node_Data));
820   if (!gp->nodes)
821     {
822       fprintf (stderr, "Couldn't allocate gp->nodes buffer\n");
823       return -1;
824     }
825
826   gp->faces = (Face_Data *) malloc (gp->num_faces * sizeof (Face_Data));
827   if (!gp->faces)
828     {
829       fprintf (stderr, "Couldn't allocate faces data buffer\n");
830       return -1;
831     }
832
833   gp->bump_data = (Bump_Data *) malloc (bumps * sizeof (Bump_Data));
834   if (!gp->bump_data)
835     {
836       fprintf(stderr, "Couldn't allocate bump data buffer\n");
837       return -1;
838     }
839
840   gp->bump_shape = (double *)malloc(bump_array_size * sizeof(double));
841   if (!gp->bump_shape)
842     {
843       fprintf(stderr, "Couldn't allocate bump buffer\n");
844       return -1;
845     }
846
847   gp->wall_shape = (double *)malloc(bump_array_size * sizeof(double));
848   if (!gp->wall_shape)
849     {
850       fprintf(stderr, "Couldn't allocate wall bump buffer\n");
851       return -1;
852     }
853
854         
855   gp->dots = (Vector3D *)malloc(gp->num_nodes * sizeof(Vector3D));
856   if (!gp->dots)
857     {
858       fprintf(stderr, "Couldn't allocate nodes buffer\n");
859       return -1;
860     }
861
862   gp->normals = (Vector3D *)malloc(gp->num_nodes * sizeof(Vector3D));
863   if (!gp->normals)
864     {
865       fprintf(stderr, "Couldn't allocate normals buffer\n");
866       return -1;
867     }
868
869   gp->colours = (Colour *)malloc(gp->num_nodes * sizeof(Colour));
870   if (!gp->colours)
871     {
872       fprintf(stderr, "Couldn't allocate colours buffer\n");
873       return -1;
874     }
875
876   gp->tex_coords = (Vector2D *)malloc(gp->num_nodes * sizeof(Vector2D));
877   if (!gp->tex_coords)
878     {
879       fprintf(stderr, "Couldn't allocate gp->tex_coords buffer\n");
880       return -1;
881     }
882
883         
884   /* Initialise bump data */
885   for (i = 0; i < bumps; i++)
886     {
887       gp->bump_data[i].ax = 2.0 * (((double)random() / (double)RAND_MAX) - 0.5);
888       gp->bump_data[i].ay = 2.0 * (((double)random() / (double)RAND_MAX) - 0.5);
889       gp->bump_data[i].power = (5.0 / pow(bumps, 0.75)) * (((double)random() / (double)RAND_MAX) - 0.5);
890       gp->bump_data[i].size = 0.1 + 0.5 * (((double)random() / (double)RAND_MAX));
891
892       gp->bump_data[i].pos.x = 1.5 * sin(PI * gp->bump_data[i].ay)
893         * cos(PI *  gp->bump_data[i].ax);
894       gp->bump_data[i].pos.y = 1.5 * cos(PI * gp->bump_data[i].ay);
895       gp->bump_data[i].pos.z = 1.5 * sin(PI * gp->bump_data[i].ay)
896         * sin(PI *  gp->bump_data[i].ax);
897
898       gp->bump_data[i].cx = 2.0 * (((double)random() / (double)RAND_MAX) - 0.5);
899       gp->bump_data[i].cy = 2.0 * (((double)random() / (double)RAND_MAX) - 0.5);
900       gp->bump_data[i].cpower = (5.0 / pow(bumps, 0.75)) * (((double)random() / (double)RAND_MAX) - 0.5);
901       gp->bump_data[i].csize = 0.35; /*0.1 + 0.25 * (((double)random() / (double)RAND_MAX));*/
902
903       gp->bump_data[i].vx = 0.0;
904       gp->bump_data[i].vy = 0.0;
905       gp->bump_data[i].vpower = 0.0;
906       gp->bump_data[i].vsize = 0.0;
907
908       gp->bump_data[i].mx = 0.003 * ((double)random() / (double)RAND_MAX);
909       gp->bump_data[i].my = 0.003 * ((double)random() / (double)RAND_MAX);
910       gp->bump_data[i].mpower = 0.003 * ((double)random() / (double)RAND_MAX);
911       gp->bump_data[i].msize = 0.003 * ((double)random() / (double)RAND_MAX);
912     }
913
914   /* Initialise lookup table of bump strength */
915   for (i = 0; i < bump_array_size; i++)
916     {
917       double xd, xd2;
918       xd = i / (double)bump_array_size;
919
920       xd2 = 48.0 * xd * xd;
921       gp->bump_shape[i] = 0.1 / (xd2 + 0.1);
922
923       xd2 = 40.0 * xd * xd * xd * xd;
924       gp->wall_shape[i] = 0.4 / (xd2 + 0.1);
925     }
926
927   node = 0;
928   face = 0;
929   for (side = 0; side < 4; side++)
930     {
931       base = node;
932       if (side == 2) 
933         {
934           base2 = node;
935         }
936       /*
937        * The start and end of the for loops below are modified based on the 
938        * side of the tetrahedron that is being calculated to avoid duplication
939        * of the gp->nodes that are on the edges of the tetrahedron. 
940        */
941       for (u = (side > 1); u < (nodes_on_edge - (side > 0)); u++)
942         {
943           node1 = partial (normalise (tetrahedron[side][0]),
944                            normalise (tetrahedron[side][1]),
945                            u / (double) (nodes_on_edge - 1));
946           node2 = partial (normalise (tetrahedron[side][0]),
947                            normalise (tetrahedron[side][2]),
948                            u / (double) (nodes_on_edge - 1));
949
950           for (v = (side > 1); v <= (u - (side > 2)); v++)
951             {
952               if (u > 0)
953                 result = partial (node1, node2, v / (double) u);
954               else
955                 result = node1;
956
957               gp->nodes[node].position = normalise (result);
958               gp->nodes[node].initial_position = gp->nodes[node].position;
959               gp->nodes[node].normal = zero_vector;
960               node++;
961             }
962         }
963  
964       /*
965        * Determine which nodes make up each face.  The complexity is caused 
966        * by having to determine the correct nodes for the edges of the
967        * tetrahedron since the common nodes on the edges are only calculated
968        * once (see above).
969        */
970       for (u = 0; u < (nodes_on_edge - 1); u++)
971         {
972           for (v = 0; v <= u; v++)
973             {
974               {
975                 if (side < 2)
976                   {
977                     gp->faces[face].node1 = base + ((u * (u + 1)) / 2) + v;
978                     gp->faces[face].node2 =
979                       base + ((u + 1) * (u + 2)) / 2 + v + 1;
980                     gp->faces[face].node3 =
981                       base + ((u + 1) * (u + 2)) / 2 + v;
982
983                     if ((side == 1) && (u == (nodes_on_edge - 2)))
984                       {
985                         gp->faces[face].node3 =
986                           ((u + 1) * (u + 2)) / 2 +
987                           nodes_on_edge - v - 1;
988                         gp->faces[face].node2 =
989                           ((u + 1) * (u + 2)) / 2 +
990                           nodes_on_edge - v - 2;
991                       }
992                   }
993                 else if (side < 3)
994                   {
995                     gp->faces[face].node1 =
996                       base + (((u - 1) * u) / 2) + v - 1;
997                     gp->faces[face].node2 = base + ((u) * (u + 1)) / 2 + v;
998                     gp->faces[face].node3 =
999                       base + ((u) * (u + 1)) / 2 + v - 1;
1000
1001                     if (u == (nodes_on_edge - 2))
1002                       {
1003                         int n = nodes_on_edge - v - 1;
1004                         gp->faces[face].node2 =
1005                           ((nodes_on_edge *
1006                             (nodes_on_edge + 1)) / 2) +
1007                           ((n - 1) * (n + 0)) / 2;
1008                         gp->faces[face].node3 =
1009                           ((nodes_on_edge *
1010                             (nodes_on_edge + 1)) / 2) +
1011                           ((n + 0) * (n + 1)) / 2;
1012                       }
1013                     if (v == 0)
1014                       {
1015                         gp->faces[face].node1 = (((u + 1) * (u + 2)) / 2) - 1;
1016                         gp->faces[face].node3 = (((u + 2) * (u + 3)) / 2) - 1;
1017                       }
1018                   }
1019                 else
1020                   {
1021                     gp->faces[face].node1 =
1022                       base + (((u - 2) * (u - 1)) / 2) + v - 1;
1023                     gp->faces[face].node2 = base + ((u - 1) * u) / 2 + v;
1024                     gp->faces[face].node3 = base + ((u - 1) * u) / 2 + v - 1;
1025
1026                     if (v == 0)
1027                       {
1028                         gp->faces[face].node1 =
1029                           base2 + ((u * (u + 1)) / 2) - 1;
1030                         gp->faces[face].node3 =
1031                           base2 + ((u + 1) * (u + 2)) / 2 - 1;
1032                       }
1033                     if (u == (nodes_on_edge - 2))
1034                       {
1035                         gp->faces[face].node3 =
1036                           ((nodes_on_edge *
1037                             (nodes_on_edge + 1)) / 2) +
1038                           ((v + 1) * (v + 2)) / 2 - 1;
1039                         gp->faces[face].node2 =
1040                           ((nodes_on_edge *
1041                             (nodes_on_edge + 1)) / 2) +
1042                           ((v + 2) * (v + 3)) / 2 - 1;
1043                       }
1044                     if (v == u)
1045                       {
1046                         gp->faces[face].node1 = (u * (u + 1)) / 2;
1047                         gp->faces[face].node2 = ((u + 1) * (u + 2)) / 2;
1048                       }
1049                   }
1050                 face++;
1051               }
1052
1053               if (v < u)
1054                 {
1055                   if (side < 2)
1056                     {
1057                       gp->faces[face].node1 = base + ((u * (u + 1)) / 2) + v;
1058                       gp->faces[face].node2 =
1059                         base + ((u * (u + 1)) / 2) + v + 1;
1060                       gp->faces[face].node3 =
1061                         base + (((u + 1) * (u + 2)) / 2) + v + 1;
1062
1063                       if ((side == 1) && (u == (nodes_on_edge - 2)))
1064                         {
1065                           gp->faces[face].node3 =
1066                             ((u + 1) * (u + 2)) / 2 +
1067                             nodes_on_edge - v - 2;
1068                         }
1069                     }
1070                   else if (side < 3)
1071                     {
1072                       gp->faces[face].node1 =
1073                         base + ((u * (u - 1)) / 2) + v - 1;
1074                       gp->faces[face].node2 = base + ((u * (u - 1)) / 2) + v;
1075                       gp->faces[face].node3 = base + ((u * (u + 1)) / 2) + v;
1076
1077                       if (u == (nodes_on_edge - 2))
1078                         {
1079                           int n = nodes_on_edge - v - 1;
1080                           gp->faces[face].node3 =
1081                             ((nodes_on_edge *
1082                               (nodes_on_edge + 1)) / 2) +
1083                             ((n + 0) * (n - 1)) / 2;
1084                         }
1085                       if (v == 0)
1086                         {
1087                           gp->faces[face].node1 = (((u + 1) * (u + 2)) / 2) - 1;
1088                         }
1089                     }
1090                   else
1091                     {
1092                       gp->faces[face].node1 =
1093                         base + (((u - 2) * (u - 1)) / 2) + v - 1;
1094                       gp->faces[face].node2 =
1095                         base + (((u - 2) * (u - 1)) / 2) + v;
1096                       gp->faces[face].node3 = base + (((u - 1) * u) / 2) + v;
1097
1098                       if (v == 0)
1099                         {
1100                           gp->faces[face].node1 = base2 + (u * (u + 1)) / 2 - 1;
1101                         }
1102                       if (u == (nodes_on_edge - 2))
1103                         {
1104                           gp->faces[face].node3 =
1105                             ((nodes_on_edge * (nodes_on_edge + 1)) / 2) +
1106                             ((v + 2) * (v + 3)) / 2 - 1;
1107                         }
1108                       if (v == (u - 1))
1109                         {
1110                           gp->faces[face].node2 = (u * (u + 1)) / 2;
1111                         }
1112                     }
1113                   face++;
1114                 }
1115             }
1116         }
1117     }
1118
1119   return 0;
1120 }
1121
1122 /******************************************************************************
1123  *
1124  * Return the magnitude of the given vector
1125  */
1126 #if 0
1127 static inline double
1128 length (Vector3D u)
1129 {
1130   return sqrt (u.x * u.x + u.y * u.y + u.z * u.z);
1131 }
1132 #endif
1133
1134 /******************************************************************************
1135  *
1136  * Calculate the blob shape.
1137  */
1138 static void
1139 calc_blob(mirrorblobstruct *gp,
1140           int width,
1141           int height,
1142           int bump_array_size,
1143           float limit,
1144           double fade)
1145 {
1146   /* Loop variables */
1147   int i, index, face;
1148   /* position of a node */
1149   Vector3D node;
1150   Vector3D offset;
1151   Vector3D bump_vector;
1152   int dist;
1153
1154   /* Update position and strength of bumps used to distort the blob */
1155   for (i = 0; i < bumps; i++)
1156     {
1157       gp->bump_data[i].vx += gp->bump_data[i].mx*(gp->bump_data[i].cx - gp->bump_data[i].ax);
1158       gp->bump_data[i].vy += gp->bump_data[i].my*(gp->bump_data[i].cy - gp->bump_data[i].ay);
1159       gp->bump_data[i].vpower += gp->bump_data[i].mpower
1160         * (gp->bump_data[i].cpower - gp->bump_data[i].power);
1161       gp->bump_data[i].vsize += gp->bump_data[i].msize
1162         * (gp->bump_data[i].csize - gp->bump_data[i].size);
1163
1164       gp->bump_data[i].ax += 0.1 * gp->bump_data[i].vx;
1165       gp->bump_data[i].ay += 0.1 * gp->bump_data[i].vy;
1166       gp->bump_data[i].power += 0.1 * gp->bump_data[i].vpower;
1167       gp->bump_data[i].size += 0.1 * gp->bump_data[i].vsize;
1168
1169       gp->bump_data[i].pos.x = 1.0 * sin(PI * gp->bump_data[i].ay)
1170         * cos(PI * gp->bump_data[i].ax);
1171       gp->bump_data[i].pos.y = 1.0 * cos(PI * gp->bump_data[i].ay);
1172       gp->bump_data[i].pos.z = 1.0 * sin(PI * gp->bump_data[i].ay)
1173         * sin(PI * gp->bump_data[i].ax);
1174     }
1175
1176   /* Update calculate new position for each vertex based on an offset from
1177    * the initial position
1178    */
1179   gp->blob_force = zero_vector;
1180   for (index = 0; index < gp->num_nodes; ++index)
1181     {
1182       node = gp->nodes[index].initial_position;
1183       gp->nodes[index].normal = node;
1184
1185       offset = zero_vector;
1186       for ( i = 0; i < bumps; i++)
1187         {
1188           bump_vector = subtract(gp->bump_data[i].pos, node);
1189
1190           dist = bump_array_size * dot(bump_vector, bump_vector) * gp->bump_data[i].size;
1191
1192           if (dist < bump_array_size)
1193             {
1194               add(&offset, scale(node, gp->bump_data[i].power * gp->bump_shape[dist]));
1195               add(&gp->blob_force, scale(node, gp->bump_data[i].power * gp->bump_shape[dist]));
1196             }
1197         }
1198
1199       add(&node, offset);
1200       node = scale(node, zoom);
1201       add(&node, gp->blob_center);
1202
1203       if (do_walls)
1204         {
1205           if (node.z < -limit) node.z = -limit;
1206           if (node.z > limit) node.z = limit;
1207
1208           dist = bump_array_size * (node.z + limit) * (node.z + limit) * 0.5;
1209           if (dist < bump_array_size)
1210             {
1211               node.x += (node.x - gp->blob_center.x) * gp->wall_shape[dist];
1212               node.y += (node.y - gp->blob_center.y) * gp->wall_shape[dist];
1213               gp->blob_force.z += (node.z + limit);
1214             }
1215           else
1216             {
1217               dist = bump_array_size * (node.z - limit) * (node.z - limit) * 0.5;
1218               if (dist < bump_array_size)
1219                 {
1220                   node.x += (node.x - gp->blob_center.x) * gp->wall_shape[dist];
1221                   node.y += (node.y - gp->blob_center.y) * gp->wall_shape[dist];
1222                   gp->blob_force.z -= (node.z - limit);
1223                 }
1224
1225               if (node.y < -limit) node.y = -limit;
1226               if (node.y > limit) node.y = limit;
1227
1228               dist = bump_array_size * (node.y + limit) * (node.y + limit) * 0.5;
1229               if (dist < bump_array_size)
1230                 {
1231                   node.x += (node.x - gp->blob_center.x) * gp->wall_shape[dist];
1232                   node.z += (node.z - gp->blob_center.z) * gp->wall_shape[dist];
1233                   gp->blob_force.y += (node.y + limit);
1234                 }
1235               else
1236                 {
1237                   dist = bump_array_size * (node.y - limit) * (node.y - limit) * 0.5;
1238                   if (dist < bump_array_size)
1239                     {
1240                       node.x += (node.x - gp->blob_center.x) * gp->wall_shape[dist];
1241                       node.z += (node.z - gp->blob_center.z) * gp->wall_shape[dist];
1242                       gp->blob_force.y -= (node.y - limit);
1243                     }
1244                 }
1245
1246               if (node.x < -limit) node.x = -limit;
1247               if (node.x > limit) node.x = limit;
1248
1249               dist = bump_array_size * (node.x + limit) * (node.x + limit) * 0.5;
1250               if (dist < bump_array_size)
1251                 {
1252                   node.y += (node.y - gp->blob_center.y) * gp->wall_shape[dist];
1253                   node.z += (node.z - gp->blob_center.z) * gp->wall_shape[dist];
1254                   gp->blob_force.x += (node.x + limit);
1255                 }
1256               else
1257                 {
1258                   dist = bump_array_size * (node.x - limit) * (node.x - limit) * 0.5;
1259                   if (dist < bump_array_size)
1260                     {
1261                       node.y += (node.y - gp->blob_center.y) * gp->wall_shape[dist];
1262                       node.z += (node.z - gp->blob_center.z) * gp->wall_shape[dist];
1263                       gp->blob_force.x -= (node.x - limit);
1264                     }
1265                 }
1266
1267               if (node.y < -limit) node.y = -limit;
1268               if (node.y > limit) node.y = limit;
1269             }
1270         }
1271       gp->dots[index] = node;
1272     }
1273
1274   /* Determine the normal for each face */
1275   for (face = 0; face < gp->num_faces; face++)
1276     {
1277       /* Use pointers to indexed nodes to help readability */
1278       int index1 = gp->faces[face].node1;
1279       int index2 = gp->faces[face].node2;
1280       int index3 = gp->faces[face].node3;
1281
1282       gp->faces[face].normal = cross(subtract(gp->dots[index2], gp->dots[index1]),
1283                                      subtract(gp->dots[index3], gp->dots[index1]));
1284             
1285       /* Add the normal for the face onto the normal for the verticies of
1286          the face */
1287       add(&gp->nodes[index1].normal, gp->faces[face].normal);
1288       add(&gp->nodes[index2].normal, gp->faces[face].normal);
1289       add(&gp->nodes[index3].normal, gp->faces[face].normal);
1290     }
1291
1292   /* Use the normal to set the colour and texture */
1293   if (do_colour || do_texture)
1294     {
1295       for (index = 0; index < gp->num_nodes; ++index)
1296         {
1297           gp->normals[index] = normalise(gp->nodes[index].normal);
1298    
1299           if (do_colour)
1300             {
1301               gp->colours[index].red = (int)(255.0 * fabs(gp->normals[index].x));
1302               gp->colours[index].green = (int)(255.0 * fabs(gp->normals[index].y));
1303               gp->colours[index].blue = (int)(255.0 * fabs(gp->normals[index].z));
1304               gp->colours[index].alpha = (int)(255.0 * fade);
1305             }
1306           if (do_texture)
1307             {
1308               if (offset_texture)
1309                 {
1310                   const float cube_size = 100.0;
1311                   Vector3D eye = {0.0, 0.0, 50.0};
1312                   Vector3D eye_r = normalise(subtract(gp->dots[index], eye));
1313                   Vector3D reference = subtract(eye_r, scale(gp->normals[index], 2.0 * dot(eye_r, gp->normals[index])));
1314                   double x = 0.0;
1315                   double y = 0.0;
1316                   double n, n_min = 10000.0, sign = 1.0;
1317                   if (fabs(reference.z) > 1e-9)
1318                     {
1319                       n = (cube_size - gp->dots[index].z) / reference.z;
1320                       if (n < 0.0)
1321                         {
1322                           n = (-cube_size - gp->dots[index].z) / reference.z;
1323                           sign = 3.0;
1324                         }
1325                       if (n > 0.0)
1326                         {
1327                           x = sign * (gp->dots[index].x + n * reference.x);
1328                           y = sign * (gp->dots[index].y + n * reference.y);
1329                           n_min = n;
1330                         }
1331                     }
1332                   if (fabs(reference.x) > 1e-9)
1333                     {
1334                       n = (cube_size - gp->dots[index].x) / reference.x;
1335                       sign = 1.0;
1336                       if (n < 0.0)
1337                         {
1338                           n = (-cube_size - gp->dots[index].x) / reference.x;
1339                           sign = -1.0;
1340                         }
1341                       if ((n > 0.0) && (n < n_min))
1342                         {
1343                           x = sign * (2.0 * cube_size - (gp->dots[index].z + n * reference.z));
1344                           y = sign * x * (gp->dots[index].y + n * reference.y) / cube_size;
1345                           n_min = n;
1346                         }
1347                     }
1348                   if (fabs(reference.y) > 1e-9)
1349                     {
1350                       n = (cube_size - gp->dots[index].y) / reference.y;
1351                       sign = 1.0;
1352                       if (n < 0.0)
1353                         {
1354                           n = (-cube_size - gp->dots[index].y) / reference.y;
1355                           sign = -1.0;
1356                         }
1357                       if ((n > 0.0) && (n < n_min))
1358                         {
1359                           y = sign * (2.0 * cube_size -( gp->dots[index].z + n * reference.z));
1360                           x = sign * y * (gp->dots[index].x + n * reference.x) / cube_size;
1361                         }
1362                     }
1363                                         
1364                   gp->tex_coords[index].x = 0.5 + x / (cube_size * 6.0);
1365                   gp->tex_coords[index].y = 0.5 - y / (cube_size * 6.0);
1366                 }
1367               else
1368                 {
1369                   gp->tex_coords[index].x = 0.5
1370                     * (1.0 + asin(gp->normals[index].x) / (0.5 * PI));
1371                   gp->tex_coords[index].y = -0.5
1372                     * (1.0 + asin(gp->normals[index].y) / (0.5 * PI));
1373                 }
1374               /* Adjust the texture co-ordinates to from range 0..1 to
1375                * 0..width or 0..height as appropriate
1376                */
1377               gp->tex_coords[index].x *= gp->tex_width[gp->current_texture];
1378               gp->tex_coords[index].y *= gp->tex_height[gp->current_texture];
1379             }
1380         }
1381     }
1382     
1383   /* Update the center of the whole blob */
1384   add(&gp->blob_velocity, scale (subtract (gp->blob_anchor, gp->blob_center), 1.0 / 80.0));
1385   add(&gp->blob_velocity, scale (gp->blob_force, 0.01 / gp->num_nodes));
1386
1387   add(&gp->blob_center, scale(gp->blob_velocity, 0.5));
1388
1389   gp->blob_velocity = scale(gp->blob_velocity, 0.999);
1390 }
1391
1392 static void
1393 draw_vertex(mirrorblobstruct *gp, int index)
1394 {
1395   if (do_colour)
1396     {
1397       glColor3ub(gp->colours[index].red,
1398                  gp->colours[index].green,
1399                  gp->colours[index].blue);
1400     }
1401   if (load_textures)
1402     {
1403       glTexCoord2fv(&gp->tex_coords[index].x);
1404     }
1405   glNormal3fv(&gp->normals[index].x);
1406   glVertex3fv(&gp->dots[index].x);
1407 }
1408
1409 /******************************************************************************
1410  *
1411  * Draw the blob shape.
1412  *
1413  */
1414 static void
1415 draw_blob (mirrorblobstruct *gp)
1416 {
1417   int face;
1418
1419   glMatrixMode(GL_MODELVIEW);
1420   glLoadIdentity();
1421   glRotatef(current_device_rotation(), 0, 0, 1);
1422
1423   /* Move down the z-axis. */
1424   glTranslatef (0.0, 0.0, -4.0);
1425
1426   gltrackball_rotate (gp->trackball);
1427
1428   /* glColor4ub (255, 0, 0, 128); */
1429   glBegin(GL_TRIANGLES);
1430   for (face = 0; face < gp->num_faces; face++)
1431     {
1432       draw_vertex(gp, gp->faces[face].node1);
1433       draw_vertex(gp, gp->faces[face].node2);
1434       draw_vertex(gp, gp->faces[face].node3);
1435     }
1436   glEnd();
1437
1438 #if 0
1439   glBegin(GL_LINES);
1440   for (face = 0; face < gp->num_faces; face++)
1441     {
1442       if (gp->normals[gp->faces[face].node1].z > 0.0)
1443         {
1444           Vector3D end = gp->dots[gp->faces[face].node1];
1445           glVertex3dv(&end);
1446           add(&end, scale(gp->normals[gp->faces[face].node1], 0.25));
1447           glVertex3dv(&end);
1448         }
1449     }
1450   glEnd();
1451 #endif
1452         
1453   glLoadIdentity();
1454 }
1455
1456 /******************************************************************************
1457  *
1458  * Draw the background image simply map a texture onto a full screen quad.
1459  */
1460 static void
1461 draw_background (ModeInfo *mi)
1462 {
1463   mirrorblobstruct *gp = &Mirrorblob[MI_SCREEN(mi)];
1464   GLfloat rot = current_device_rotation();
1465     
1466   glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
1467   glEnable (GL_TEXTURE_2D);
1468   glDisable(GL_LIGHTING);
1469   glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1470
1471   /* Reset the projection matrix to make it easier to get the size of the quad
1472    * correct
1473    */
1474   glMatrixMode(GL_PROJECTION);
1475   glPushMatrix();
1476   glLoadIdentity();
1477
1478   glRotatef (rot, 0, 0, 1);
1479   if ((rot >  45 && rot <  135) ||
1480       (rot < -45 && rot > -135))
1481     {
1482       GLfloat s = MI_WIDTH(mi) / (GLfloat) MI_HEIGHT(mi);
1483       glScalef (s, 1/s, 1);
1484     }
1485
1486   glOrtho(0.0, MI_WIDTH(mi), MI_HEIGHT(mi), 0.0, -1000.0, 1000.0);
1487
1488   glBegin (GL_QUADS);
1489     
1490   glTexCoord2f (0.0, 0.0);
1491   glVertex2i (0, 0);
1492     
1493   glTexCoord2f (0.0, gp->tex_height[gp->current_texture]);
1494   glVertex2i (0, MI_HEIGHT(mi));
1495
1496   glTexCoord2f (gp->tex_width[gp->current_texture], gp->tex_height[gp->current_texture]);
1497   glVertex2i (MI_WIDTH(mi), MI_HEIGHT(mi));
1498
1499   glTexCoord2f (gp->tex_width[gp->current_texture], 0.0);
1500   glVertex2i (MI_WIDTH(mi), 0);
1501   glEnd();
1502
1503   glPopMatrix ();
1504   glMatrixMode (GL_MODELVIEW);
1505   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1506 }
1507
1508 /******************************************************************************
1509  *
1510  * Update the scene.
1511  */
1512 static GLvoid
1513 draw_scene(ModeInfo * mi)
1514 {
1515   mirrorblobstruct *gp = &Mirrorblob[MI_SCREEN(mi)];
1516     
1517   double fade = 0.0;
1518   double current_time;
1519   check_gl_error ("draw_scene");
1520
1521   mi->polygon_count = 0;
1522   glColor4f (1.0, 1.0, 1.0, 1.0);
1523
1524   current_time = double_time();
1525   switch (gp->state)
1526     {
1527     case INITIALISING:
1528       glColor4f (0.0, 0.0, 0.0, 1.0);
1529       fade = 1.0;
1530       break;
1531
1532     case TRANSITIONING:
1533       fade = 1.0 - (current_time - gp->state_start_time) / fade_time;
1534       break;
1535
1536     case LOADING: /* FALL-THROUGH */
1537     case HOLDING:
1538       fade = 1.0;
1539       break;
1540     }
1541
1542   /* Set the correct texture, when transitioning this ensures that the first draw
1543    * is the original texture (which has the new texture drawn over it with decreasing
1544    * transparency)
1545    */
1546   if (load_textures)
1547     {
1548       glBindTexture(GL_TEXTURE_2D, gp->textures[gp->current_texture]);
1549     }
1550
1551   glDisable (GL_DEPTH_TEST);
1552   if (do_paint_background)
1553     {
1554       glEnable (GL_TEXTURE_2D);
1555       if (motion_blur > 0.0)
1556         {
1557           glClear(GL_DEPTH_BUFFER_BIT);
1558           glEnable (GL_BLEND);
1559           glColor4f (1.0, 1.0, 1.0, motion_blur);
1560         }
1561       else
1562         {
1563           glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1564         }
1565       draw_background (mi);
1566       mi->polygon_count++;
1567
1568       /* When transitioning between two images paint the new image over the old
1569        * image with a varying alpha value to get a smooth fade.
1570        */
1571       if (gp->state == TRANSITIONING)
1572         {
1573           glEnable (GL_BLEND);
1574           /* Select the texture to transition to */
1575           glBindTexture (GL_TEXTURE_2D, gp->textures[1 - gp->current_texture]);
1576           glColor4f (1.0, 1.0, 1.0, 1.0 - fade);
1577
1578           draw_background (mi);
1579           mi->polygon_count++;
1580
1581           /* Select the original texture to draw the blob */
1582           glBindTexture (GL_TEXTURE_2D, gp->textures[gp->current_texture]);
1583         }
1584       /* Clear the depth buffer bit so the backgound is behind the blob */
1585       glClear(GL_DEPTH_BUFFER_BIT);
1586     }
1587   else if (motion_blur > 0.0)
1588     {
1589       glEnable (GL_BLEND);
1590       glColor4f (0.0, 0.0, 0.0, motion_blur);
1591       glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1592       glTranslatef (0.0, 0.0, -4.0);
1593       glRectd (-10.0, -10.0, 10.0, 10.0);
1594       if (wireframe)
1595         {
1596           glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
1597         }
1598       glClear(GL_DEPTH_BUFFER_BIT);
1599     }
1600   else
1601     {
1602       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1603     }
1604
1605   if (!do_texture)
1606     {
1607       fade = 1.0;
1608       glDisable (GL_TEXTURE_2D);
1609     }
1610
1611   calc_blob(gp, MI_WIDTH(mi), MI_HEIGHT(mi), BUMP_ARRAY_SIZE, 2.5, fade * blend);
1612
1613   set_blob_gl_state(fade * blend);
1614
1615   if (blend < 1.0)
1616     {
1617       /* Disable the colour chanels so that only the depth buffer is updated */
1618       glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1619       draw_blob(gp);
1620       mi->polygon_count += gp->num_faces;
1621       glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1622     }
1623         
1624   glDepthFunc(GL_LEQUAL);
1625   draw_blob(gp);
1626   mi->polygon_count += gp->num_faces;
1627
1628   /* While transitioning between images draw a second blob with a modified
1629    * alpha value.
1630    */
1631   if (load_textures && (hold_time > 0))
1632     {
1633       switch (gp->state)
1634         {
1635         case INITIALISING:
1636           if (!gp->waiting_for_image_p)
1637             {
1638               gp->state = HOLDING;
1639             }
1640           break;
1641                 
1642         case HOLDING:
1643           if ((current_time - gp->state_start_time) > hold_time)
1644             {
1645               grab_texture(mi, 1 - gp->current_texture);
1646               gp->state = LOADING;
1647             }
1648           break;
1649
1650         case LOADING:
1651           /* Once the image has loaded move to the TRANSITIONING STATE */
1652           if (!gp->waiting_for_image_p)
1653             {
1654               gp->state = TRANSITIONING;
1655               /* Get the time again rather than using the current time so
1656                * that the time taken by the grab_texture function is not part
1657                * of the fade time
1658                */
1659               gp->state_start_time = double_time();
1660             }
1661           break;        
1662
1663         case TRANSITIONING:
1664
1665           /* If the blob is textured draw over existing blob to fade between
1666            * images
1667            */
1668           if (do_texture)
1669             {
1670               /* Select the texture to transition to */
1671               glBindTexture (GL_TEXTURE_2D, gp->textures[1 - gp->current_texture]);
1672               glEnable (GL_BLEND);
1673                 
1674               /* If colour is enabled update the alpha data in the buffer and
1675                * use that in the blending since the alpha of the incomming
1676                * verticies will not be correct
1677                */
1678               if (do_colour)
1679                 {
1680                   glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
1681                   glClearColor(0.0, 0.0, 0.0, (1.0 - fade) * blend);
1682                   glClear(GL_COLOR_BUFFER_BIT);
1683                   glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);                    
1684                   glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
1685                 }
1686               else
1687                 {
1688                   glColor4f (0.9, 0.9, 1.0, (1.0 - fade) * blend);
1689                 }
1690
1691               draw_blob (gp);
1692               mi->polygon_count += gp->num_faces;
1693
1694               if (do_colour)
1695                 {
1696                   /* Restore the 'standard' blend functions. */
1697                   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1698                 }
1699             }
1700             
1701           if ((current_time - gp->state_start_time) > fade_time)
1702             {
1703               gp->state = HOLDING;
1704               gp->state_start_time = current_time;
1705               gp->current_texture = 1 - gp->current_texture;
1706             }
1707           break;
1708
1709         }
1710     }
1711 }
1712
1713 /******************************************************************************
1714  *
1715  * XMirrorblob screen update entry
1716  */
1717 ENTRYPOINT void
1718 draw_mirrorblob(ModeInfo * mi)
1719 {
1720   mirrorblobstruct *gp = &Mirrorblob[MI_SCREEN(mi)];
1721   Display    *display = MI_DISPLAY(mi);
1722   Window      window = MI_WINDOW(mi);
1723
1724   if (!gp->glx_context)
1725     return;
1726
1727   /* Wait for the first image; for subsequent images, load them in the
1728      background while animating. */
1729   if (gp->waiting_for_image_p && gp->first_image_p)
1730     return;
1731
1732   glXMakeCurrent(display, window, *(gp->glx_context));
1733   draw_scene(mi);
1734   if (mi->fps_p) do_fps (mi);
1735   glFinish();
1736   glXSwapBuffers(display, window);
1737 }
1738
1739 /******************************************************************************
1740  *
1741  * XMirrorblob screen resize entry
1742  */
1743 ENTRYPOINT void
1744 reshape_mirrorblob(ModeInfo *mi, int width, int height)
1745 {
1746   glViewport( 0, 0, MI_WIDTH(mi), MI_HEIGHT(mi) );
1747   reset_projection(width, height);
1748 }
1749
1750 /****************************************************************************
1751  *
1752  * Handle Mouse events
1753  */
1754 ENTRYPOINT Bool
1755 mirrorblob_handle_event (ModeInfo * mi, XEvent * event)
1756 {
1757   mirrorblobstruct *gp = &Mirrorblob[MI_SCREEN (mi)];
1758
1759   if (event->xany.type == ButtonPress &&
1760       event->xbutton.button == Button1)
1761     {
1762       gp->button_down = 1;
1763       gltrackball_start (gp->trackball, event->xbutton.x,
1764                          event->xbutton.y, MI_WIDTH (mi), MI_HEIGHT (mi));
1765       return True;
1766     }
1767   else if (event->xany.type == ButtonRelease &&
1768            event->xbutton.button == Button1)
1769     {
1770       gp->button_down = 0;
1771       return True;
1772     }
1773   else if (event->xany.type == ButtonPress &&
1774            event->xbutton.button == Button4)
1775     {
1776       zoom *= 1.1;
1777       return True;
1778     }
1779   else if (event->xany.type == ButtonPress &&
1780            event->xbutton.button == Button5)
1781     {
1782
1783       zoom *= 0.9;
1784       return True;
1785     }
1786   else if (event->xany.type == MotionNotify && gp->button_down)
1787     {
1788       gltrackball_track (gp->trackball, event->xmotion.x,
1789                          event->xmotion.y, MI_WIDTH (mi), MI_HEIGHT (mi));
1790       return True;
1791     }
1792   return False;
1793 }
1794
1795 /******************************************************************************
1796  *
1797  * XMirrorblob initialise entry
1798  */
1799 ENTRYPOINT void
1800 init_mirrorblob(ModeInfo * mi)
1801 {
1802   int screen = MI_SCREEN(mi);
1803
1804   mirrorblobstruct *gp;
1805
1806   if (Mirrorblob == NULL)
1807     {
1808       if ((Mirrorblob = (mirrorblobstruct *)
1809            calloc(MI_NUM_SCREENS(mi), sizeof (mirrorblobstruct))) == NULL)
1810         {
1811           return;
1812         }
1813     }
1814   gp = &Mirrorblob[screen];
1815
1816   gp->window = MI_WINDOW(mi);
1817   if ((gp->glx_context = init_GL(mi)) != NULL)
1818     {
1819       reshape_mirrorblob(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
1820       initialize_gl(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
1821     }
1822   else
1823     {
1824       MI_CLEARWINDOW(mi);
1825     }
1826   gp->trackball = gltrackball_init();
1827     
1828   initialise_blob(gp, MI_WIDTH(mi), MI_HEIGHT(mi), BUMP_ARRAY_SIZE);
1829   gp->state = INITIALISING;
1830   gp->state_start_time = double_time();
1831
1832   gp->first_image_p = True;
1833 }
1834
1835 /******************************************************************************
1836  *
1837  * XMirrorblob cleanup entry
1838  */
1839 ENTRYPOINT void
1840 release_mirrorblob(ModeInfo * mi)
1841 {
1842   if (Mirrorblob != NULL) {
1843     int i;
1844     for (i = 0; i < MI_NUM_SCREENS(mi); i++) {
1845       mirrorblobstruct *gp = &Mirrorblob[i];
1846       if (gp->nodes) free(gp->nodes);
1847       if (gp->faces) free(gp->faces);
1848       if (gp->bump_data) free(gp->bump_data);
1849       if (gp->colours) free(gp->colours);
1850       if (gp->tex_coords) free(gp->tex_coords);
1851       if (gp->dots) free(gp->dots);
1852       if (gp->wall_shape) free(gp->wall_shape);
1853       if (gp->bump_shape) free(gp->bump_shape);
1854     }
1855
1856     free(Mirrorblob);
1857     Mirrorblob = NULL;
1858   }
1859   FreeAllGL(mi);
1860 }
1861
1862 XSCREENSAVER_MODULE ("MirrorBlob", mirrorblob)
1863
1864 #endif