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