From http://www.jwz.org/xscreensaver/xscreensaver-5.35.tar.gz
[xscreensaver] / hacks / glx / sierpinski3d.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* Sierpinski3D --- 3D sierpinski gasket */
3
4 #if 0
5 static const char sccsid[] = "@(#)sierpinski3D.c        00.01 99/11/04 xlockmore";
6 #endif
7
8 /*-
9  * Permission to use, copy, modify, and distribute this software and its
10  * documentation for any purpose and without fee is hereby granted,
11  * provided that the above copyright notice appear in all copies and that
12  * both that copyright notice and this permission notice appear in
13  * supporting documentation.
14  *
15  * This file is provided AS IS with no warranties of any kind.  The author
16  * shall have no liability with respect to the infringement of copyrights,
17  * trade secrets or any patents by this file or any part thereof.  In no
18  * event will the author be liable for any lost revenue or profits or
19  * other special, indirect and consequential damages.
20  *
21  * Revision History:
22  * 1999: written by Tim Robinson <the_luggage@bigfoot.com>
23  *       a 3-D representation of the Sierpinski gasket fractal.
24  *
25  * 10-Dec-99  jwz   rewrote to draw a set of tetrahedrons instead of a
26  *                  random scattering of points.
27  */
28
29 #ifdef STANDALONE
30 # define DEFAULTS                                       "*delay:                20000   \n"                     \
31                                                                         "*showFPS:      False   \n"                     \
32                                                                         "*wireframe:    False   \n"                     \
33                                                                         "*suppressRotationAnimation: True\n" \
34
35 # define refresh_gasket 0
36 # include "xlockmore.h"         /* from the xscreensaver distribution */
37 #else  /* !STANDALONE */
38 # include "xlock.h"                     /* from the xlockmore distribution */
39 #endif /* !STANDALONE */
40
41 #ifdef USE_GL
42
43 #define DEF_SPIN                                "True"
44 #define DEF_WANDER                              "True"
45 #define DEF_SPEED                               "150"
46 #define DEF_MAX_DEPTH                   "5"
47
48 #include "rotator.h"
49 #include "gltrackball.h"
50
51 #undef countof
52 #define countof(x) (sizeof((x))/sizeof((*x)))
53
54 static int max_depth;
55 static int speed;
56 static Bool do_spin;
57 static Bool do_wander;
58
59 static XrmOptionDescRec opts[] = {
60   {"-depth", ".sierpinski3d.maxDepth", XrmoptionSepArg, 0 },
61   {"-speed", ".sierpinski3d.speed",    XrmoptionSepArg, 0 },
62   { "-spin",   ".spin",   XrmoptionNoArg, "True" },
63   { "+spin",   ".spin",   XrmoptionNoArg, "False" },
64   { "-wander", ".wander", XrmoptionNoArg, "True" },
65   { "+wander", ".wander", XrmoptionNoArg, "False" },
66 };
67
68 static argtype vars[] = {
69   {&do_spin,   "spin",     "Spin",     DEF_SPIN,      t_Bool},
70   {&do_wander, "wander",   "Wander",   DEF_WANDER,    t_Bool},
71   {&speed,     "speed",    "Speed",    DEF_SPEED,     t_Int},
72   {&max_depth, "maxDepth", "MaxDepth", DEF_MAX_DEPTH, t_Int},
73 };
74
75
76 ENTRYPOINT ModeSpecOpt gasket_opts = {countof(opts), opts, countof(vars), vars, NULL};
77
78 #ifdef USE_MODULES
79 ModStruct   gasket_description =
80 {"gasket", "init_gasket", "draw_gasket", "release_gasket",
81  "draw_gasket", "init_gasket", NULL, &gasket_opts,
82  1000, 1, 2, 1, 4, 1.0, "",
83  "Shows GL's Sierpinski gasket", 0, NULL};
84
85 #endif
86
87 typedef struct {
88   double x,y,z;
89 } XYZ;
90
91 typedef struct {
92   GLuint      gasket0, gasket1, gasket2, gasket3;
93   GLXContext *glx_context;
94   Window      window;
95   rotator    *rot;
96   trackball_state *trackball;
97   Bool            button_down_p;
98
99   int current_depth;
100
101   int ncolors;
102   XColor *colors;
103   int ccolor0;
104   int ccolor1;
105   int ccolor2;
106   int ccolor3;
107
108   int tick;
109
110 } gasketstruct;
111
112 static gasketstruct *gasket = NULL;
113
114
115 static void
116 triangle (GLfloat x1, GLfloat y1, GLfloat z1,
117           GLfloat x2, GLfloat y2, GLfloat z2,
118           GLfloat x3, GLfloat y3, GLfloat z3,
119           Bool wireframe_p)
120 {
121   if (wireframe_p)
122     glBegin (GL_LINE_LOOP);
123   else
124     glBegin (GL_TRIANGLES);
125   glVertex3f (x1, y1, z1);
126   glVertex3f (x2, y2, z2);
127   glVertex3f (x3, y3, z3);
128   glEnd();
129 }
130
131 static void
132 four_tetras (gasketstruct *gp, 
133              XYZ *outer, XYZ *normals,
134              Bool wireframe_p, int countdown, int which,
135              int *countP)
136 {
137   if (countdown <= 0)
138     {
139       (*countP)++;
140       if (which == 0)
141         {
142           glNormal3f (normals[0].x, normals[0].y, normals[0].z);
143           triangle (outer[0].x, outer[0].y, outer[0].z,
144                     outer[1].x, outer[1].y, outer[1].z,
145                     outer[2].x, outer[2].y, outer[2].z,
146                     wireframe_p);
147         }
148       else if (which == 1)
149         {
150           glNormal3f (normals[1].x, normals[1].y, normals[1].z);
151           triangle (outer[0].x, outer[0].y, outer[0].z,
152                     outer[3].x, outer[3].y, outer[3].z,
153                     outer[1].x, outer[1].y, outer[1].z,
154                     wireframe_p);
155         }
156       else if (which == 2)
157         {
158           glNormal3f (normals[2].x, normals[2].y, normals[2].z);
159           triangle (outer[0].x, outer[0].y, outer[0].z,
160                     outer[2].x, outer[2].y, outer[2].z,
161                     outer[3].x, outer[3].y, outer[3].z,
162                     wireframe_p);
163         }
164       else
165         {
166           glNormal3f (normals[3].x, normals[3].y, normals[3].z);
167           triangle (outer[1].x, outer[1].y, outer[1].z,
168                     outer[3].x, outer[3].y, outer[3].z,
169                     outer[2].x, outer[2].y, outer[2].z,
170                     wireframe_p);
171         }
172     }
173   else
174     {
175 #     define M01 0
176 #     define M02 1
177 #     define M03 2
178 #     define M12 3
179 #     define M13 4
180 #     define M23 5
181       XYZ inner[M23+1];
182       XYZ corner[4];
183
184       inner[M01].x = (outer[0].x + outer[1].x) / 2.0;
185       inner[M01].y = (outer[0].y + outer[1].y) / 2.0;
186       inner[M01].z = (outer[0].z + outer[1].z) / 2.0;
187
188       inner[M02].x = (outer[0].x + outer[2].x) / 2.0;
189       inner[M02].y = (outer[0].y + outer[2].y) / 2.0;
190       inner[M02].z = (outer[0].z + outer[2].z) / 2.0;
191
192       inner[M03].x = (outer[0].x + outer[3].x) / 2.0;
193       inner[M03].y = (outer[0].y + outer[3].y) / 2.0;
194       inner[M03].z = (outer[0].z + outer[3].z) / 2.0;
195
196       inner[M12].x = (outer[1].x + outer[2].x) / 2.0;
197       inner[M12].y = (outer[1].y + outer[2].y) / 2.0;
198       inner[M12].z = (outer[1].z + outer[2].z) / 2.0;
199
200       inner[M13].x = (outer[1].x + outer[3].x) / 2.0;
201       inner[M13].y = (outer[1].y + outer[3].y) / 2.0;
202       inner[M13].z = (outer[1].z + outer[3].z) / 2.0;
203
204       inner[M23].x = (outer[2].x + outer[3].x) / 2.0;
205       inner[M23].y = (outer[2].y + outer[3].y) / 2.0;
206       inner[M23].z = (outer[2].z + outer[3].z) / 2.0;
207
208       countdown--;
209
210       corner[0] = outer[0];
211       corner[1] = inner[M01];
212       corner[2] = inner[M02];
213       corner[3] = inner[M03];
214       four_tetras (gp, corner, normals, wireframe_p, countdown, which, countP);
215
216       corner[0] = inner[M01];
217       corner[1] = outer[1];
218       corner[2] = inner[M12];
219       corner[3] = inner[M13];
220       four_tetras (gp, corner, normals, wireframe_p, countdown, which, countP);
221
222       corner[0] = inner[M02];
223       corner[1] = inner[M12];
224       corner[2] = outer[2];
225       corner[3] = inner[M23];
226       four_tetras (gp, corner, normals, wireframe_p, countdown, which, countP);
227
228       corner[0] = inner[M03];
229       corner[1] = inner[M13];
230       corner[2] = inner[M23];
231       corner[3] = outer[3];
232       four_tetras (gp, corner, normals, wireframe_p, countdown, which, countP);
233     }
234 }
235
236
237 static void
238 compile_gasket(ModeInfo *mi, int which)
239 {
240   Bool wireframe_p = MI_IS_WIREFRAME(mi);
241   gasketstruct *gp = &gasket[MI_SCREEN(mi)];
242   int count = 0;
243   XYZ vertex[5];
244   XYZ normal[4];
245
246   vertex[0].x = -1; vertex[0].y = -1; vertex[0].z = -1;
247   vertex[1].x =  1; vertex[1].y =  1; vertex[1].z = -1;
248   vertex[2].x =  1; vertex[2].y = -1; vertex[2].z =  1;
249   vertex[3].x = -1; vertex[3].y =  1; vertex[3].z =  1;
250   vertex[4].x =  0; vertex[4].y =  0; vertex[4].z =  0;  /* center */
251
252   normal[0].x =  1; normal[0].y = -1; normal[0].z = -1;
253   normal[1].x = -1; normal[1].y =  1; normal[1].z = -1;
254   normal[2].x = -1; normal[2].y = -1; normal[2].z =  1;
255   normal[3].x =  1; normal[3].y =  1; normal[3].z =  1;
256
257   four_tetras (gp, vertex, normal, wireframe_p,
258                (gp->current_depth < 0
259                 ? -gp->current_depth : gp->current_depth),
260                which,
261                &count);
262   mi->polygon_count += count;
263 }
264
265 static void
266 draw(ModeInfo *mi)
267 {
268   Bool wireframe_p = MI_IS_WIREFRAME(mi);
269   gasketstruct *gp = &gasket[MI_SCREEN(mi)];
270   
271   static const GLfloat pos[]    = {-4.0, 3.0, 10.0, 1.0};
272   static const GLfloat white[]  = {1.0, 1.0, 1.0, 1.0};
273
274   GLfloat color0[] = {0.0, 0.0, 0.0, 1.0};
275   GLfloat color1[] = {0.0, 0.0, 0.0, 1.0};
276   GLfloat color2[] = {0.0, 0.0, 0.0, 1.0};
277   GLfloat color3[] = {0.0, 0.0, 0.0, 1.0};
278
279   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
280
281   if (!wireframe_p)
282     {
283       glColor4fv (white);
284
285       glLightfv(GL_LIGHT0, GL_POSITION,  pos);
286
287       color0[0] = gp->colors[gp->ccolor0].red   / 65536.0;
288       color0[1] = gp->colors[gp->ccolor0].green / 65536.0;
289       color0[2] = gp->colors[gp->ccolor0].blue  / 65536.0;
290
291       color1[0] = gp->colors[gp->ccolor1].red   / 65536.0;
292       color1[1] = gp->colors[gp->ccolor1].green / 65536.0;
293       color1[2] = gp->colors[gp->ccolor1].blue  / 65536.0;
294
295       color2[0] = gp->colors[gp->ccolor2].red   / 65536.0;
296       color2[1] = gp->colors[gp->ccolor2].green / 65536.0;
297       color2[2] = gp->colors[gp->ccolor2].blue  / 65536.0;
298
299       color3[0] = gp->colors[gp->ccolor3].red   / 65536.0;
300       color3[1] = gp->colors[gp->ccolor3].green / 65536.0;
301       color3[2] = gp->colors[gp->ccolor3].blue  / 65536.0;
302
303       gp->ccolor0++;
304       gp->ccolor1++;
305       gp->ccolor2++;
306       gp->ccolor3++;
307       if (gp->ccolor0 >= gp->ncolors) gp->ccolor0 = 0;
308       if (gp->ccolor1 >= gp->ncolors) gp->ccolor1 = 0;
309       if (gp->ccolor2 >= gp->ncolors) gp->ccolor2 = 0;
310       if (gp->ccolor3 >= gp->ncolors) gp->ccolor3 = 0;
311
312       glShadeModel(GL_SMOOTH);
313
314       glEnable(GL_LIGHTING);
315       glEnable(GL_LIGHT0);
316     }
317
318   glEnable(GL_DEPTH_TEST);
319   glEnable(GL_NORMALIZE);
320   glEnable(GL_CULL_FACE);
321
322   glPushMatrix();
323
324   {
325     double x, y, z;
326     get_position (gp->rot, &x, &y, &z, !gp->button_down_p);
327     glTranslatef((x - 0.5) * 10,
328                  (y - 0.5) * 10,
329                  (z - 0.5) * 20);
330
331     gltrackball_rotate (gp->trackball);
332
333     get_rotation (gp->rot, &x, &y, &z, !gp->button_down_p);
334     glRotatef (x * 360, 1.0, 0.0, 0.0);
335     glRotatef (y * 360, 0.0, 1.0, 0.0);
336     glRotatef (z * 360, 0.0, 0.0, 1.0);
337   }
338
339   glScalef (4, 4, 4);
340
341   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color0);
342   glCallList(gp->gasket0);
343   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color1);
344   glCallList(gp->gasket1);
345   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color2);
346   glCallList(gp->gasket2);
347   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color3);
348   glCallList(gp->gasket3);
349
350   glPopMatrix();
351
352
353   if (gp->tick++ >= speed)
354     {
355       gp->tick = 0;
356       if (gp->current_depth >= max_depth)
357         gp->current_depth = -max_depth;
358       gp->current_depth++;
359
360       /* We make four different lists so that each face of the tetrahedrons
361          can have a different color (all triangles facing in the same
362          direction have the same color, which is different from all
363          triangles facing in other directions.)
364        */
365       glDeleteLists (gp->gasket0, 1);
366       glDeleteLists (gp->gasket1, 1);
367       glDeleteLists (gp->gasket2, 1);
368       glDeleteLists (gp->gasket3, 1);
369
370       mi->polygon_count = 0;
371       glNewList (gp->gasket0, GL_COMPILE); compile_gasket (mi, 0); glEndList();
372       glNewList (gp->gasket1, GL_COMPILE); compile_gasket (mi, 1); glEndList();
373       glNewList (gp->gasket2, GL_COMPILE); compile_gasket (mi, 2); glEndList();
374       glNewList (gp->gasket3, GL_COMPILE); compile_gasket (mi, 3); glEndList();
375
376       mi->recursion_depth = (gp->current_depth > 0
377                              ? gp->current_depth
378                              : -gp->current_depth);
379     }
380 }
381
382
383 /* new window size or exposure */
384 ENTRYPOINT void
385 reshape_gasket(ModeInfo *mi, int width, int height)
386 {
387   GLfloat h = (GLfloat) height / (GLfloat) width;
388
389   glViewport(0, 0, (GLint) width, (GLint) height);
390   glMatrixMode(GL_PROJECTION);
391   glLoadIdentity();
392   gluPerspective (30.0, 1/h, 1.0, 100.0);
393
394   glMatrixMode(GL_MODELVIEW);
395   glLoadIdentity();
396   gluLookAt( 0.0, 0.0, 30.0,
397              0.0, 0.0, 0.0,
398              0.0, 1.0, 0.0);
399   
400 # ifdef HAVE_MOBILE     /* Keep it the same relative size when rotated. */
401   {
402     int o = (int) current_device_rotation();
403     if (o != 0 && o != 180 && o != -180)
404       glScalef (1/h, 1/h, 1/h);
405   }
406 # endif
407
408   glClear(GL_COLOR_BUFFER_BIT);
409 }
410
411 static void
412 pinit(ModeInfo *mi)
413 {
414   gasketstruct *gp = &gasket[MI_SCREEN(mi)];
415
416   /* draw the gasket */
417   gp->gasket0 = glGenLists(1);
418   gp->gasket1 = glGenLists(1);
419   gp->gasket2 = glGenLists(1);
420   gp->gasket3 = glGenLists(1);
421   gp->current_depth = 1;       /* start out at level 1, not 0 */
422 }
423
424
425 ENTRYPOINT Bool
426 gasket_handle_event (ModeInfo *mi, XEvent *event)
427 {
428   gasketstruct *gp = &gasket[MI_SCREEN(mi)];
429
430   if (gltrackball_event_handler (event, gp->trackball,
431                                  MI_WIDTH (mi), MI_HEIGHT (mi),
432                                  &gp->button_down_p))
433     return True;
434   else if (event->xany.type == KeyPress)
435     {
436       KeySym keysym;
437       char c = 0;
438       XLookupString (&event->xkey, &c, 1, &keysym, 0);
439       if (c == '+' || c == '=' ||
440           keysym == XK_Up || keysym == XK_Right || keysym == XK_Next)
441         {
442           gp->tick = speed;
443           gp->current_depth += (gp->current_depth > 0 ? 1 : -1);
444           gp->current_depth--;
445           return True;
446         }
447       else if (c == '-' || c == '_' ||
448                keysym == XK_Down || keysym == XK_Left || keysym == XK_Prior)
449         {
450           gp->tick = speed;
451           gp->current_depth -= (gp->current_depth > 0 ? 1 : -1);
452           gp->current_depth--;
453           return True;
454         }
455       else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
456         goto DEF;
457     }
458   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
459     {
460     DEF:
461       gp->tick = speed;
462       return True;
463     }
464
465   return False;
466 }
467
468
469 ENTRYPOINT void
470 init_gasket(ModeInfo *mi)
471 {
472   int           screen = MI_SCREEN(mi);
473   gasketstruct *gp;
474
475   if (gasket == NULL)
476   {
477     if ((gasket = (gasketstruct *) calloc(MI_NUM_SCREENS(mi),
478                                               sizeof (gasketstruct))) == NULL)
479         return;
480   }
481   gp = &gasket[screen];
482
483   gp->window = MI_WINDOW(mi);
484
485   {
486     double spin_speed   = 1.0;
487     double wander_speed = 0.03;
488     gp->rot = make_rotator (do_spin ? spin_speed : 0,
489                             do_spin ? spin_speed : 0,
490                             do_spin ? spin_speed : 0,
491                             1.0,
492                             do_wander ? wander_speed : 0,
493                             True);
494     gp->trackball = gltrackball_init (True);
495   }
496
497   gp->ncolors = 255;
498   gp->colors = (XColor *) calloc(gp->ncolors, sizeof(XColor));
499   make_smooth_colormap (0, 0, 0,
500                         gp->colors, &gp->ncolors,
501                         False, 0, False);
502   gp->ccolor0 = 0;
503   gp->ccolor1 = gp->ncolors * 0.25;
504   gp->ccolor2 = gp->ncolors * 0.5;
505   gp->ccolor3 = gp->ncolors * 0.75;
506   gp->tick = 999999;
507
508   if ((gp->glx_context = init_GL(mi)) != NULL)
509   {
510     reshape_gasket(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
511     pinit(mi);
512   }
513   else
514   {
515     MI_CLEARWINDOW(mi);
516   }
517 }
518
519 ENTRYPOINT void
520 draw_gasket(ModeInfo * mi)
521 {
522   gasketstruct *gp = &gasket[MI_SCREEN(mi)];
523   Display      *display = MI_DISPLAY(mi);
524   Window        window = MI_WINDOW(mi);
525
526   if (!gp->glx_context) return;
527
528   glDrawBuffer(GL_BACK);
529
530   /*  0 =              4 polygons
531       1 =             16 polygons
532       2 =             64 polygons
533       3 =            256 polygons
534       4 =          1,024 polygons
535       5 =          4,096 polygons
536       6 =         16,384 polygons
537       7 =         65,536 polygons,  30 fps (3GHz Core 2 Duo, GeForce 8800 GS)
538       8 =        262,144 polygons,  12 fps
539       9 =      1,048,576 polygons,   4 fps
540      10 =      4,194,304 polygons,   1 fps
541      11 =     16,777,216 polygons, 0.3 fps
542      12 =     67,108,864 polygons,    OOM!
543      13 =    268,435,456 polygons
544      14 =  1,073,741,824 polygons, 31 bits
545      15 =  4,294,967,296 polygons, 33 bits
546      16 = 17,179,869,184 polygons, 35 bits
547    */
548   if (max_depth > 10)
549     max_depth = 10;
550
551   glXMakeCurrent(display, window, *(gp->glx_context));
552   draw(mi);
553   if (mi->fps_p) do_fps (mi);
554   glFinish();
555   glXSwapBuffers(display, window);
556 }
557
558 ENTRYPOINT void
559 release_gasket(ModeInfo * mi)
560 {
561   if (gasket != NULL)
562   {
563     int         screen;
564
565     for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++)
566     {
567       gasketstruct *gp = &gasket[screen];
568
569       if (gp->glx_context)
570       {
571         /* Display lists MUST be freed while their glXContext is current. */
572         glXMakeCurrent(MI_DISPLAY(mi), gp->window, *(gp->glx_context));
573
574         if (glIsList(gp->gasket0)) glDeleteLists(gp->gasket0, 1);
575         if (glIsList(gp->gasket1)) glDeleteLists(gp->gasket1, 1);
576         if (glIsList(gp->gasket2)) glDeleteLists(gp->gasket2, 1);
577         if (glIsList(gp->gasket3)) glDeleteLists(gp->gasket3, 1);
578       }
579     }
580     (void) free((void *) gasket);
581     gasket = NULL;
582   }
583   FreeAllGL(mi);
584 }
585
586 XSCREENSAVER_MODULE_2 ("Sierpinski3D", sierpinski3d, gasket)
587
588 /*********************************************************/
589
590 #endif