From http://www.jwz.org/xscreensaver/xscreensaver-5.30.tar.gz
[xscreensaver] / hacks / glx / flipscreen3d.c
1 /*
2  * flipscreen3d - takes snapshots of the screen and flips it around
3  *
4  * version 1.0 - Oct 24, 2001
5  *
6  * Copyright (C) 2001 Ben Buxton (bb@cactii.net)
7  *
8  * Permission to use, copy, modify, distribute, and sell this software and its
9  * documentation for any purpose is hereby granted without fee, provided that
10  * the above copyright notice appear in all copies and that both that
11  * copyright notice and this permission notice appear in supporting
12  * documentation.  No representations are made about the suitability of this
13  * software for any purpose.  It is provided "as is" without express or
14  * implied warranty.
15  */
16
17 #ifdef STANDALONE
18 #define DEFAULTS "*delay:     20000 \n" \
19                  "*showFPS:   False \n" \
20                  "*wireframe: False \n" \
21                  "*useSHM:    True  \n"
22
23 # define refresh_screenflip 0
24 # include "xlockmore.h"                         /* from the xscreensaver distribution */
25 # include "gltrackball.h"
26 #else  /* !STANDALONE */
27 # include "xlock.h"                                     /* from the xlockmore distribution */
28 #endif /* !STANDALONE */
29
30 /* lifted from lament.c */
31 #define RAND(n) ((long) ((random() & 0x7fffffff) % ((long) (n))))
32 #define RANDSIGN() ((random() & 1) ? 1 : -1)
33
34
35 #ifdef USE_GL
36
37 /* Should be in <GL/glext.h> */
38 # ifndef  GL_TEXTURE_MAX_ANISOTROPY_EXT
39 #  define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
40 # endif
41 # ifndef  GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
42 #  define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
43 # endif
44
45 #define DEF_ROTATE "True"
46 static int rotate;
47
48 #define QW 12
49 #define QH 12
50
51 #undef countof
52 #define countof(x) (sizeof((x))/sizeof((*x)))
53
54
55 static XrmOptionDescRec opts[] = {
56   {"+rotate", ".screenflip.rotate", XrmoptionNoArg, "false" },
57   {"-rotate", ".screenflip.rotate", XrmoptionNoArg, "true" },
58 };
59
60
61 static argtype vars[] = {
62   {&rotate, "rotate", "Rotate", DEF_ROTATE, t_Bool},
63 };
64
65
66
67 ENTRYPOINT ModeSpecOpt screenflip_opts = {countof(opts), opts, countof(vars), vars, NULL};
68
69
70 #ifdef USE_MODULES
71 ModStruct   screenflip_description =
72 {"screenflip", "init_screenflip", "draw_screenflip", "release_screenflip",
73  "draw_screenflip", "init_screenflip", NULL, &screenflip_opts,
74  1000, 1, 2, 1, 4, 1.0, "",
75  "Screenflips", 0, NULL};
76
77 #endif
78
79
80 typedef struct {
81   GLXContext *glx_context;
82   Window window;
83
84   int winw, winh;
85   int tw, th; /* texture width, height */
86   GLfloat min_tx, min_ty;
87   GLfloat max_tx, max_ty;
88   GLfloat qx, qy, qw, qh; /* the quad we'll draw */
89
90   int regrab;
91   int fadetime; /* fade before regrab */
92
93   trackball_state *trackball;
94   Bool button_down_p;
95
96   GLfloat show_colors[4];
97   GLfloat stretch_val_x, stretch_val_y;
98   GLfloat stretch_val_dx, stretch_val_dy;
99
100   GLfloat curx, cury, curz;
101
102   GLfloat rx, ry, rz;
103   GLfloat rot, drot, odrot, ddrot, orot;
104   float theta, rho, dtheta, drho, gamma, dgamma;
105
106   GLuint texid;
107   Bool mipmap_p;
108   Bool waiting_for_image_p;
109   Bool first_image_p;
110
111   GLfloat anisotropic;
112
113 } Screenflip;
114
115 static Screenflip *screenflip = NULL;
116
117 #include "grab-ximage.h"
118
119 static const GLfloat viewer[] = {0.0, 0.0, 15.0};
120
121
122 static void getSnapshot (ModeInfo *);
123
124
125 ENTRYPOINT Bool
126 screenflip_handle_event (ModeInfo *mi, XEvent *event)
127 {
128   Screenflip *c = &screenflip[MI_SCREEN(mi)];
129
130   if (gltrackball_event_handler (event, c->trackball,
131                                  MI_WIDTH (mi), MI_HEIGHT (mi),
132                                  &c->button_down_p))
133     return True;
134   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
135     {
136       if (!c->waiting_for_image_p)
137         {
138           getSnapshot (mi);
139           return True;
140         }
141     }
142
143   return False;
144 }
145
146
147 /* draw the texture mapped quad (actually two back to back)*/
148 static void showscreen(Screenflip *c, int frozen, int wire)
149 {
150   GLfloat x, y, w, h;
151
152   if (c->fadetime) {
153 /*    r -= 0.02; g -= 0.02; b -= 0.02; */
154     c->show_colors[3] -= 0.02;
155     if (c->show_colors[3] < 0) {
156       c->regrab = 1;
157       c->fadetime = 0;
158     }
159   } else if (c->show_colors[3] < 0) {
160     c->show_colors[0] = c->show_colors[1] = 
161       c->show_colors[2] = c->show_colors[3] = 1;
162     c->stretch_val_x = c->stretch_val_y = 
163       c->stretch_val_dx = c->stretch_val_dy = 0;
164   }
165   if (c->stretch_val_dx == 0 && !frozen && !(random() % 25))
166     c->stretch_val_dx = (float)(random() % 100) / 5000;
167   if (c->stretch_val_dy == 0 && !frozen && !(random() % 25))
168     c->stretch_val_dy = (float)(random() % 100) / 5000;
169     
170   x = c->qx;
171   y = c->qy;
172   w = c->qx+c->qw;
173   h = c->qy-c->qh;
174
175   if (!frozen) {
176      w *= sin (c->stretch_val_x) + 1;
177      x *= sin (c->stretch_val_x) + 1;
178      if (!c->button_down_p) {
179      if (!c->fadetime) c->stretch_val_x += c->stretch_val_dx;
180      if (c->stretch_val_x > 2*M_PI && !(random() % 5))
181        c->stretch_val_dx = (float)(random() % 100) / 5000;
182      else
183        c->stretch_val_x -= 2*M_PI;
184      }
185
186      if (!c->button_down_p && !c->fadetime) c->stretch_val_y += c->stretch_val_dy;
187      h *= sin (c->stretch_val_y) / 2 + 1;
188      y *= sin (c->stretch_val_y) / 2 + 1;
189      if (!c->button_down_p) {
190      if (c->stretch_val_y > 2*M_PI && !(random() % 5))
191        c->stretch_val_dy = (float)(random() % 100) / 5000;
192      else
193        c->stretch_val_y -= 2*M_PI;
194      }
195   }
196
197   glColor4f(c->show_colors[0], c->show_colors[1], 
198             c->show_colors[2], c->show_colors[3]);
199
200   if (!wire)
201     {
202       glEnable(GL_TEXTURE_2D);
203       glEnable(GL_BLEND);
204       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
205       glDepthMask(GL_FALSE);
206     }
207
208   glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
209
210   glNormal3f(0, 0, 1);
211   glTexCoord2f(c->max_tx, c->max_ty); glVertex3f(w, h, 0);
212   glTexCoord2f(c->max_tx, c->min_ty); glVertex3f(w, y, 0);
213   glTexCoord2f(c->min_tx, c->min_ty); glVertex3f(x, y, 0);
214   glTexCoord2f(c->min_tx, c->max_ty); glVertex3f(x, h, 0);
215
216   glNormal3f(0, 0, -1);
217   glTexCoord2f(c->min_tx, c->min_ty); glVertex3f(x, y, -0.05);
218   glTexCoord2f(c->max_tx, c->min_ty); glVertex3f(w, y, -0.05);
219   glTexCoord2f(c->max_tx, c->max_ty); glVertex3f(w, h, -0.05);
220   glTexCoord2f(c->min_tx, c->max_ty); glVertex3f(x, h, -0.05);
221   glEnd();
222
223
224   glDisable(GL_TEXTURE_2D);
225   glDepthMask(GL_TRUE);
226
227   glBegin(GL_LINE_LOOP);
228    glVertex3f(x, y, 0);
229    glVertex3f(x, h, 0);
230    glVertex3f(w, h, 0);
231    glVertex3f(w, y, 0);
232  glEnd();
233   glDisable(GL_BLEND);
234
235 }
236
237 /* This function is responsible for 'zooming back' the square after
238  * a new chunk has been grabbed with getSnapshot(), and positioning
239  * it suitably on the screen. Once positioned (where we begin to rotate),
240  * it just does a glTranslatef() and returns 1
241  */
242
243 static int inposition(Screenflip *c)
244 {
245   GLfloat wx;
246   GLfloat wy;
247   wx = 0 - (c->qw/2);
248   wy = (c->qh/2);
249
250   if (c->curx == 0) c->curx = c->qx;
251   if (c->cury == 0) c->cury = c->qy;
252   if (c->regrab) {
253      c->curz = 0;
254      c->curx = c->qx;
255      c->cury = c->qy;
256      c->regrab = 0;
257   }
258   if (c->curz > -10 || c->curx > wx + 0.1 || c->curx < wx - 0.1 ||
259          c->cury > wy + 0.1 || c->cury < wy - 0.1) {
260     if (c->curz > -10)
261       c->curz -= 0.05;
262     if (c->curx > wx) {
263        c->qx -= 0.02;
264        c->curx -= 0.02;
265     }
266     if (c->curx < wx) {
267        c->qx += 0.02;
268        c->curx += 0.02;
269     }
270     if (c->cury > wy) {
271        c->qy -= 0.02;
272        c->cury -= 0.02;
273     }
274     if (c->cury < wy) {
275        c->qy += 0.02;
276        c->cury += 0.02;
277     }
278     glTranslatef(0, 0, c->curz);
279     return 0;
280   }
281   glTranslatef(0, 0, c->curz);
282   return 1;
283
284 }
285
286 #if 0
287 static void drawgrid(void)
288 {
289   int i;
290
291   glColor3f(0, 0.7, 0);
292   glBegin(GL_LINES);
293   for (i = 0 ; i <= 50; i+=2) {
294       glVertex3f( -25, -15, i-70);
295       glVertex3f( 25, -15, i-70);
296       glVertex3f( i-25, -15, -70);
297       glVertex3f( i-25, -15, -20);
298   }
299   glEnd();
300 }
301 #endif
302
303
304 static void display(Screenflip *c, int wire)
305 {
306   int frozen;
307   GLfloat rot = current_device_rotation();
308
309   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
310   glLoadIdentity();
311   gluLookAt(viewer[0], viewer[1], viewer[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
312   glPushMatrix();
313
314   glRotatef(rot, 0, 0, 1);
315   if ((rot >  45 && rot <  135) ||
316       (rot < -45 && rot > -135))
317     {
318       GLfloat s = c->winw / (GLfloat) c->winh;
319       glScalef (s, 1/s, 1);
320     }
321
322   if (inposition(c)) {
323     frozen = 0;
324     glTranslatef(5 * sin(c->theta), 5 * sin(c->rho), 10 * cos(c->gamma) - 10);
325 /* randomly change the speed */
326     if (!c->button_down_p && !(random() % 300)) {
327       if (random() % 2)
328         c->drho = 1/60 - (float)(random() % 100)/3000;
329       if (random() % 2)
330         c->dtheta = 1/60 - (float)(random() % 100)/3000;
331       if (random() % 2)
332         c->dgamma = 1/60 - (float)(random() % 100)/3000;
333     }
334     glRotatef(-rot, 0, 0, 1);
335     gltrackball_rotate (c->trackball);
336     glRotatef(rot, 0, 0, 1);
337     if (rotate) glRotatef(c->rot, c->rx, c->ry, c->rz);
338 /* update variables with each frame */
339     if(!c->button_down_p && !c->fadetime) {
340       c->theta += c->dtheta;
341       c->rho += c->drho;
342       c->gamma += c->dgamma;
343       c->rot += c->drot;
344       c->drot += c->ddrot;
345     }
346 /* dont let our rotation speed get too high */
347     if (c->drot > 5 && c->ddrot > 0)
348         c->ddrot = 0 - (GLfloat)(random() % 100) / 1000;
349     else if (c->drot < -5 && c->ddrot < 0)
350         c->ddrot = (GLfloat)(random() % 100) / 1000;
351   } else { /* reset some paramaters */
352     c->ddrot = 0.05 - (GLfloat)(random() % 100) / 1000;
353     c->theta = c->rho = c->gamma = 0;
354     c->rot = 0;
355     frozen = 1;
356   }
357   if (!c->button_down_p && !c->fadetime && (c->rot >= 360 || c->rot <= -360) && !(random() % 7)) { /* rotate  change */
358     c->rx = (GLfloat)(random() % 100) / 100;
359     c->ry = (GLfloat)(random() % 100) / 100;
360     c->rz = (GLfloat)(random() % 100) / 100;
361   }
362   if (c->odrot * c->drot < 0 && c->tw < c->winw && !(random() % 10)) {
363     c->fadetime = 1;                /* randomly fade and get new snapshot */
364   }
365   c->orot = c->rot;
366   c->odrot = c->drot;
367   if (c->rot > 360 || c->rot < -360) /* dont overflow rotation! */
368     c->rot -= c->rot;
369   showscreen(c, frozen, wire);
370   glPopMatrix();
371   glFlush();
372 }
373
374 ENTRYPOINT void reshape_screenflip(ModeInfo *mi, int width, int height)
375 {
376  Screenflip *c = &screenflip[MI_SCREEN(mi)];
377  glViewport(0,0,(GLint)width, (GLint) height);
378  glMatrixMode(GL_PROJECTION);
379  glLoadIdentity();
380  gluPerspective(45, 1, 2.0, 85);
381  glMatrixMode(GL_MODELVIEW);
382  c->winw = width;
383  c->winh = height;
384 }
385
386 static void
387 image_loaded_cb (const char *filename, XRectangle *geometry,
388                  int image_width, int image_height, 
389                  int texture_width, int texture_height,
390                  void *closure)
391 {
392   Screenflip *c = (Screenflip *) closure;
393
394   c->tw = texture_width;
395   c->th = texture_height;
396   c->min_tx = (GLfloat) geometry->x / c->tw;
397   c->min_ty = (GLfloat) geometry->y / c->th;
398   c->max_tx = (GLfloat) (geometry->x + geometry->width)  / c->tw;
399   c->max_ty = (GLfloat) (geometry->y + geometry->height) / c->th;
400
401   c->qx = -QW/2 + ((GLfloat) geometry->x * QW / image_width);
402   c->qy =  QH/2 - ((GLfloat) geometry->y * QH / image_height);
403   c->qw =  QW   * ((GLfloat) geometry->width  / image_width);
404   c->qh =  QH   * ((GLfloat) geometry->height / image_height);
405
406   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
407   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
408                    (c->mipmap_p ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR));
409
410   if (c->anisotropic >= 1.0)
411     glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 
412                      c->anisotropic);
413
414   c->waiting_for_image_p = False;
415   c->first_image_p = False;
416 }
417
418
419 static void getSnapshot (ModeInfo *modeinfo)
420 {
421   Screenflip *c = &screenflip[MI_SCREEN(modeinfo)];
422
423   if (MI_IS_WIREFRAME(modeinfo))
424     return;
425
426   c->waiting_for_image_p = True;
427   c->mipmap_p = True;
428   load_texture_async (modeinfo->xgwa.screen, modeinfo->window,
429                       *c->glx_context, 0, 0, c->mipmap_p, c->texid,
430                       image_loaded_cb, c);
431 }
432
433 ENTRYPOINT void init_screenflip(ModeInfo *mi)
434 {
435   int screen = MI_SCREEN(mi);
436   Screenflip *c;
437
438  if (screenflip == NULL) {
439    if ((screenflip = (Screenflip *) calloc(MI_NUM_SCREENS(mi),
440                                         sizeof(Screenflip))) == NULL)
441           return;
442  }
443  c = &screenflip[screen];
444  c->window = MI_WINDOW(mi);
445
446  c->trackball = gltrackball_init (False);
447
448  if ((c->glx_context = init_GL(mi)) != NULL) {
449       reshape_screenflip(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
450  } else {
451      MI_CLEARWINDOW(mi);
452  }
453  c->winh = MI_WIN_HEIGHT(mi);
454  c->winw = MI_WIN_WIDTH(mi);
455  c->qw = QW;
456  c->qh = QH;
457  c->qx = -6;
458  c->qy = 6;
459
460  c->rx = c->ry = 1;
461  c->odrot = 1;
462
463  c->show_colors[0] = c->show_colors[1] = 
464    c->show_colors[2] = c->show_colors[3] = 1;
465
466  if (! MI_IS_WIREFRAME(mi))
467    {
468      glShadeModel(GL_SMOOTH);
469      glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
470      glEnable(GL_DEPTH_TEST);
471      glEnable(GL_CULL_FACE);
472      glCullFace(GL_BACK);
473      glDisable(GL_LIGHTING);
474    }
475
476  if (strstr ((char *) glGetString(GL_EXTENSIONS),
477              "GL_EXT_texture_filter_anisotropic"))
478    glGetFloatv (GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &c->anisotropic);
479  else
480    c->anisotropic = 0.0;
481
482  glGenTextures(1, &c->texid);
483
484  c->first_image_p = True;
485  getSnapshot(mi);
486 }
487
488 ENTRYPOINT void draw_screenflip(ModeInfo *mi)
489 {
490   Screenflip *c = &screenflip[MI_SCREEN(mi)];
491   Window w = MI_WINDOW(mi);
492   Display *disp = MI_DISPLAY(mi);
493
494   if (!c->glx_context)
495       return;
496
497   /* Wait for the first image; for subsequent images, load them in the
498      background while animating. */
499   if (c->waiting_for_image_p && c->first_image_p)
500     return;
501
502   glXMakeCurrent(disp, w, *(c->glx_context));
503
504   glBindTexture(GL_TEXTURE_2D, c->texid);
505
506   if (c->regrab)
507     getSnapshot(mi);
508
509   display(c, MI_IS_WIREFRAME(mi));
510
511   if(mi->fps_p) do_fps(mi);
512   glFinish(); 
513   glXSwapBuffers(disp, w);
514 }
515
516 ENTRYPOINT void release_screenflip(ModeInfo *mi)
517 {
518   if (screenflip != NULL) {
519    (void) free((void *) screenflip);
520    screenflip = NULL;
521   }
522   FreeAllGL(mi);
523 }
524
525 XSCREENSAVER_MODULE_2 ("FlipScreen3D", flipscreen3d, screenflip)
526
527 #endif