ftp://ftp.linux.ncsu.edu/mirror/ftp.redhat.com/pub/redhat/linux/enterprise/4/en/os...
[xscreensaver] / hacks / glx / queens.c
1 /*
2  * queens - solves n queens problem, displays
3  * i make no claims that this is an optimal solution to the problem,
4  * good enough for xss
5  * hacked from glchess
6  *
7  * version 1.0 - May 10, 2002
8  *
9  * Copyright (C) 2002 Blair Tennessy (tennessy@cs.ubc.ca)
10  *
11  * Permission to use, copy, modify, distribute, and sell this software and its
12  * documentation for any purpose is hereby granted without fee, provided that
13  * the above copyright notice appear in all copies and that both that
14  * copyright notice and this permission notice appear in supporting
15  * documentation.  No representations are made about the suitability of this
16  * software for any purpose.  It is provided "as is" without express or
17  * implied warranty.
18  */
19
20 #include <X11/Intrinsic.h>
21
22 #ifdef STANDALONE
23 # define PROGCLASS        "Queens"
24 # define HACK_INIT        init_queens
25 # define HACK_DRAW        draw_queens
26 # define HACK_RESHAPE     reshape_queens
27 # define HACK_HANDLE_EVENT queens_handle_event
28 # define EVENT_MASK       PointerMotionMask
29 # define queens_opts  xlockmore_opts
30
31 #define DEFAULTS       "*delay:       20000       \n" \
32                        "*showFPS:       False       \n" \
33                        "*wireframe:     False     \n"   \
34
35 # include "xlockmore.h"
36
37 #else
38 # include "xlock.h"
39 #endif
40
41 #ifdef USE_GL
42
43 #include <GL/glu.h>
44 #include "gltrackball.h"
45
46 #undef countof
47 #define countof(x) (sizeof((x))/sizeof((*x)))
48
49 static XrmOptionDescRec opts[] = {
50   {"+rotate", ".queens.rotate", XrmoptionNoArg, "false" },
51   {"-rotate", ".queens.rotate", XrmoptionNoArg, "true" },
52   {"+flat", ".queens.flat", XrmoptionNoArg, "false" },
53   {"-flat", ".queens.flat", XrmoptionNoArg, "true" },
54 };
55
56 int rotate, wire, clearbits, flat;
57
58 static argtype vars[] = {
59   {&rotate, "rotate", "Rotate", "True",  t_Bool},
60   {&flat,   "flat",   "Flat",   "False", t_Bool},
61 };
62
63 ModeSpecOpt queens_opts = {countof(opts), opts, countof(vars), vars, NULL};
64
65 #ifdef USE_MODULES
66 ModStruct   queens_description =
67 {"queens", "init_queens", "draw_queens", "release_queens",
68  "draw_queens", "init_queens", NULL, &queens_opts,
69  1000, 1, 2, 1, 4, 1.0, "",
70  "Queens", 0, NULL};
71
72 #endif
73
74 typedef struct {
75   GLXContext *glx_context;
76   Window window;
77   trackball_state *trackball;
78   Bool button_down_p;
79 } Queenscreen;
80
81 static Queenscreen *qs = NULL;
82
83 #include <math.h>
84 #include <sys/time.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87
88 #ifndef M_PI
89 #define M_PI 3.14159265
90 #endif
91
92 #define NONE 0
93 #define QUEEN 1
94 #define MINBOARD 5
95 #define MAXBOARD 10
96 #define COLORSETS 5
97
98 /* definition of white/black colors */
99 GLfloat colors[COLORSETS][2][3] = 
100   { 
101     {{0.43, 0.54, 0.76}, {0.8, 0.8, 0.8}},
102     {{0.5, 0.7, 0.9}, {0.2, 0.3, 0.6}},
103     {{0.53725490196, 0.360784313725, 0.521568627451}, {0.6, 0.6, 0.6}},
104     {{0.15, 0.77, 0.54}, {0.5, 0.5, 0.5}},
105     {{0.9, 0.45, 0.0}, {0.5, 0.5, 0.5}},
106   };
107
108 int board[MAXBOARD][MAXBOARD];
109 int steps = 0, colorset = 0, BOARDSIZE = 8; /* 8 cuz its classic */
110 double theta = 0.0;
111
112 Bool
113 queens_handle_event (ModeInfo *mi, XEvent *event)
114 {
115   Queenscreen *c = &qs[MI_SCREEN(mi)];
116
117   if (event->xany.type == ButtonPress &&
118       event->xbutton.button & Button1)
119     {
120       c->button_down_p = True;
121       gltrackball_start (c->trackball,
122                          event->xbutton.x, event->xbutton.y,
123                          MI_WIDTH (mi), MI_HEIGHT (mi));
124       return True;
125     }
126   else if (event->xany.type == ButtonRelease &&
127            event->xbutton.button & Button1)
128     {
129       c->button_down_p = False;
130       return True;
131     }
132   else if (event->xany.type == MotionNotify &&
133            c->button_down_p)
134     {
135       gltrackball_track (c->trackball,
136                          event->xmotion.x, event->xmotion.y,
137                          MI_WIDTH (mi), MI_HEIGHT (mi));
138       return True;
139     }
140
141   return False;
142 }
143
144
145
146 /* returns true if placing a queen on column c causes a conflict */
147 int conflictsCols(int c) {
148   int i;
149
150   for(i = 0; i < BOARDSIZE; ++i)
151     if(board[i][c])
152       return 1;
153
154   return 0;
155 }
156
157 /* returns true if placing a queen on (r,c) causes a diagonal conflict */
158 int conflictsDiag(int r, int c) {
159   int i;
160
161   /* positive slope */
162   int n = r < c ? r : c;
163   for(i = 0; i < BOARDSIZE-abs(r-c); ++i)
164     if(board[r-n+i][c-n+i])
165       return 1;
166
167   /* negative slope */
168   n = r < BOARDSIZE - (c+1) ? r : BOARDSIZE - (c+1);
169   for(i = 0; i < BOARDSIZE-abs(BOARDSIZE - (1+r+c)); ++i)
170     if(board[r-n+i][c+n-i])
171       return 1;
172   
173   return 0;
174 }
175
176 /* returns true if placing a queen at (r,c) causes a conflict */
177 int conflicts(int r, int c) {
178   return !conflictsCols(c) ? conflictsDiag(r, c) : 1;
179 }
180
181 /* clear board */
182 void blank(void) {
183   int i, j;
184
185   for(i = 0; i < MAXBOARD; ++i)
186     for(j = 0; j < MAXBOARD; ++j)
187       board[i][j] = NONE;
188 }
189
190 /* recursively determine solution */
191 int findSolution(int row, int col) {
192   if(row == BOARDSIZE)
193     return 1;
194   
195   while(col < BOARDSIZE) {
196     if(!conflicts(row, col)) {
197       board[row][col] = 1;
198
199       if(findSolution(row+1, 0))
200         return 1;
201
202       board[row][col] = 0;
203     }
204
205     ++col;
206   }
207
208   return 0;
209 }
210
211 /** driver for finding solution */
212 void go(void) { while(!findSolution(0, random()%BOARDSIZE)); }
213
214 /* lighting variables */
215 GLfloat front_shininess[] = {60.0};
216 GLfloat front_specular[] = {0.4, 0.4, 0.4, 1.0};
217 GLfloat ambient[] = {0.3, 0.3, 0.3, 1.0};
218 GLfloat diffuse[] = {0.8, 0.8, 0.8, 1.0};
219 GLfloat position[] = { 0.0, 5.0, 5.0, 1.0 };
220 GLfloat lmodel_ambient[] = {0.6, 0.6, 0.6, 1.0};
221 GLfloat lmodel_twoside[] = {GL_TRUE};
222
223 /* configure lighting */
224 void setup_lights(void) {
225
226   /* setup twoside lighting */
227   glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
228   glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
229   glLightfv(GL_LIGHT0, GL_POSITION, position);
230   glEnable(GL_LIGHTING);
231   glEnable(GL_LIGHT0);
232
233   /* setup material properties */
234   glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, front_shininess);
235   glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, front_specular);
236
237   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
238 }
239
240 #define    checkImageWidth 8
241 #define    checkImageHeight 8
242 GLubyte checkImage[checkImageWidth][checkImageHeight][3];
243
244 /* return alpha value for fading */
245 GLfloat findAlpha(void) {
246   return steps < 128 ? steps/128.0 : steps < 1024-128 ?1.0:(1024-steps)/128.0;
247 }
248
249 /* draw pieces */
250 void drawPieces(void) {
251   int i, j;
252
253   for(i = 0; i < BOARDSIZE; ++i) {
254     for(j = 0; j < BOARDSIZE; ++j) {
255       if(board[i][j]) {
256         glColor3fv(colors[colorset][i%2]);
257         glCallList(QUEEN);
258       }
259       
260       glTranslatef(1.0, 0.0, 0.0);
261     }
262     
263     glTranslatef(-1.0*BOARDSIZE, 0.0, 1.0);
264   }
265 }
266
267 /** reflectionboard */
268 void draw_reflections(void) {
269   int i, j;
270
271   glEnable(GL_STENCIL_TEST);
272   glStencilFunc(GL_ALWAYS, 1, 1);
273   glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
274   glColorMask(0,0,0,0);
275   glDisable(GL_CULL_FACE);
276
277   glDisable(GL_DEPTH_TEST);
278   glBegin(GL_QUADS);
279
280   /* only draw white squares */
281   for(i = 0; i < BOARDSIZE; ++i) {
282     for(j = (BOARDSIZE+i) % 2; j < BOARDSIZE; j += 2) {
283       glVertex3f(i, 0.0, j + 1.0);
284       glVertex3f(i + 1.0, 0.0, j + 1.0);
285       glVertex3f(i + 1.0, 0.0, j);
286       glVertex3f(i, 0.0, j);
287     }
288   }
289   glEnd();
290   glEnable(GL_DEPTH_TEST);
291
292   glColorMask(1, 1, 1, 1);
293   glStencilFunc(GL_EQUAL, 1, 1);
294   glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
295   
296   glPushMatrix(); 
297   glScalef(1.0, -1.0, 1.0);
298   glTranslatef(0.5, 0.001, 0.5);
299   glLightfv(GL_LIGHT0, GL_POSITION, position);
300   drawPieces();
301   glPopMatrix();
302   glDisable(GL_STENCIL_TEST);
303
304   /* replace lights */
305   glLightfv(GL_LIGHT0, GL_POSITION, position);
306
307   glEnable(GL_CULL_FACE);
308   glCullFace(GL_BACK);
309   glColorMask(1,1,1,1);
310 }
311
312 /* draw board */
313 void drawBoard(void) {
314   int i, j;
315
316   glBegin(GL_QUADS);
317
318   for(i = 0; i < BOARDSIZE; ++i)
319     for(j = 0; j < BOARDSIZE; ++j) {
320       int par = (i-j+BOARDSIZE)%2;
321       glColor4f(colors[colorset][par][0],
322                 colors[colorset][par][1],
323                 colors[colorset][par][2],
324                 0.70);
325       glNormal3f(0.0, 1.0, 0.0);
326       glVertex3f(i, 0.0, j + 1.0);
327       glVertex3f(i + 1.0, 0.0, j + 1.0);
328       glVertex3f(i + 1.0, 0.0, j);
329       glVertex3f(i, 0.0, j);
330     }
331
332   glEnd();
333 }
334
335 void display(Queenscreen *c) {
336   glClear(clearbits);
337   
338   glMatrixMode(GL_MODELVIEW);
339   glLoadIdentity();
340
341   /* setup light attenuation */
342   glEnable(GL_COLOR_MATERIAL);
343   glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.8/(0.01+findAlpha()));
344   glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.06);
345
346   /** setup perspective */
347   glTranslatef(0.0, 0.0, -1.5*BOARDSIZE);
348   glRotatef(30.0, 1.0, 0.0, 0.0);
349   gltrackball_rotate (c->trackball);
350   glRotatef(theta*100, 0.0, 1.0, 0.0);
351   glTranslatef(-0.5*BOARDSIZE, 0.0, -0.5*BOARDSIZE);
352
353   /* find light positions */
354   position[0] = BOARDSIZE/2.0 + BOARDSIZE/1.4*-sin(theta*100*M_PI/180.0);
355   position[2] = BOARDSIZE/2.0 + BOARDSIZE/1.4*cos(theta*100*M_PI/180.0);
356   position[1] = 6.0;
357
358   if(!wire) {
359     glEnable(GL_LIGHTING);
360     glLightfv(GL_LIGHT0, GL_POSITION, position);
361     glEnable(GL_LIGHT0);
362   }
363
364   /* draw reflections */
365   if(!wire) {
366     draw_reflections();
367     glEnable(GL_BLEND);
368   }
369   drawBoard();
370   if(!wire)
371     glDisable(GL_BLEND);
372
373   glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.1);
374
375   glTranslatef(0.5, 0.0, 0.5);
376   drawPieces();
377
378   /* rotate camera */
379   if(!c->button_down_p)
380     theta += .002;
381
382   /* zero out board, find new solution of size MINBOARD <= i <= MAXBOARD */
383   if(++steps == 1024) {
384     steps = 0;
385     blank();
386     BOARDSIZE = MINBOARD + (random() % (MAXBOARD - MINBOARD + 1));
387     colorset = (colorset+1)%COLORSETS;
388     go();
389   }
390 }
391
392 int schunks = 15;
393 GLfloat spidermodel[][3] =
394   {
395     {0.48, 0.48, 0.22},
396     {0.48, 0.34, 0.18},
397     {0.34, 0.34, 0.10},
398     {0.34, 0.18, 0.30},
399     {0.18, 0.14, 0.38},
400     {0.14, 0.29, 0.01},
401     {0.29, 0.18, 0.18},
402     {0.18, 0.18, 0.16},
403     {0.18, 0.20, 0.26},
404     {0.20, 0.27, 0.14},
405     {0.27, 0.24, 0.08},
406     {0.24, 0.17, 0.00},
407     {0.17, 0.095, 0.08},
408     {0.095, 0.07, 0.00},
409     {0.07, 0.00, 0.12},
410   };
411
412 #define EPSILON 0.001
413
414 /** draws cylindermodel */
415 void draw_model(int chunks, GLfloat model[][3], int r) {
416   int i = 0;
417   GLUquadricObj *quadric = gluNewQuadric();
418   glPushMatrix();
419   glRotatef(-90.0, 1.0, 0.0, 0.0);
420   
421   for(i = 0; i < chunks; ++i) {
422     if(model[i][0] > EPSILON || model[i][1] > EPSILON)
423       gluCylinder(quadric, model[i][0], model[i][1], model[i][2], r, 1);
424     glTranslatef(0.0, 0.0, model[i][2]);
425   }
426   
427   glPopMatrix();
428 }
429
430 void reshape_queens(ModeInfo *mi, int width, int height) {
431   GLfloat h = (GLfloat) height / (GLfloat) width;
432   glViewport(0,0, width, height);
433   glMatrixMode(GL_PROJECTION);
434   glLoadIdentity();
435   gluPerspective(45, 1/h, 2.0, 30.0);
436   glMatrixMode(GL_MODELVIEW);
437 }
438
439 void init_queens(ModeInfo *mi) {
440   int screen = MI_SCREEN(mi);
441   Queenscreen *c;
442   wire = MI_IS_WIREFRAME(mi);
443
444   if(!qs && 
445      !(qs = (Queenscreen *) calloc(MI_NUM_SCREENS(mi), sizeof(Queenscreen))))
446     return;
447   
448   c = &qs[screen];
449   c->window = MI_WINDOW(mi);
450   c->trackball = gltrackball_init ();
451   
452   if((c->glx_context = init_GL(mi)))
453     reshape_queens(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
454   else
455     MI_CLEARWINDOW(mi);
456
457   glClearColor(0.0, 0.0, 0.0, 0.0);
458   glNewList(QUEEN, GL_COMPILE);
459   draw_model(schunks, spidermodel, 24);
460   glEndList();
461
462   if(flat)
463     glShadeModel(GL_FLAT);
464   
465   clearbits = GL_COLOR_BUFFER_BIT;
466
467   glColorMaterial(GL_FRONT, GL_DIFFUSE);
468   glEnable(GL_COLOR_MATERIAL);
469
470   if(!wire) {
471     setup_lights();
472     glEnable(GL_DEPTH_TEST);
473     clearbits |= GL_DEPTH_BUFFER_BIT;
474     clearbits |= GL_STENCIL_BUFFER_BIT;
475     glEnable(GL_CULL_FACE);
476     glCullFace(GL_BACK);
477   }
478   else
479     glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
480
481   /* find a solution */
482   go();
483 }
484
485 void draw_queens(ModeInfo *mi) {
486   Queenscreen *c = &qs[MI_SCREEN(mi)];
487   Window w = MI_WINDOW(mi);
488   Display *disp = MI_DISPLAY(mi);
489
490   if(!c->glx_context)
491     return;
492
493   glXMakeCurrent(disp, w, *(c->glx_context));
494
495   display(c);
496
497   if(mi->fps_p) do_fps(mi);
498   glFinish(); 
499   glXSwapBuffers(disp, w);
500 }
501
502 void release_queens(ModeInfo *mi) {
503   if(qs)
504     free((void *) qs);
505
506   FreeAllGL(MI);
507 }
508
509 #endif