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