From http://www.jwz.org/xscreensaver/xscreensaver-5.39.tar.gz
[xscreensaver] / hacks / glx / carousel.c
1 /* carousel, Copyright (c) 2005-2018 Jamie Zawinski <jwz@jwz.org>
2  * Loads a sequence of images and rotates them around.
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation.  No representations are made about the suitability of this
9  * software for any purpose.  It is provided "as is" without express or
10  * implied warranty.
11  *
12  * Created: 21-Feb-2005
13  */
14
15 #if defined(HAVE_COCOA) || defined(HAVE_ANDROID)
16 # define DEF_FONT "OCR A Std 48, Lucida Console 48, Monaco 48"
17 #elif 0  /* real X11, XQueryFont() */
18 # define DEF_FONT "-*-helvetica-bold-r-normal-*-*-480-*-*-*-*-*-*"
19 #else    /* real X11, load_font_retry() */
20 # define DEF_FONT "-*-ocr a std-medium-r-*-*-*-480-*-*-m-*-*-*"
21 #endif
22
23 #define DEF_TITLE_FONT "-*-helvetica-bold-r-normal-*-*-480-*-*-*-*-*-*"
24
25 #define DEFAULTS  "*count:           7         \n" \
26                   "*delay:           10000     \n" \
27                   "*wireframe:       False     \n" \
28                   "*showFPS:         False     \n" \
29                   "*fpsSolid:        True      \n" \
30                   "*useSHM:          True      \n" \
31                   "*font:          " DEF_FONT "\n" \
32                   "*titleFont:     " DEF_TITLE_FONT "\n" \
33                   "*desktopGrabber:  xscreensaver-getimage -no-desktop %s\n" \
34                   "*grabDesktopImages:   False \n" \
35                   "*chooseRandomImages:  True  \n"
36
37 # define free_carousel 0
38 # define release_carousel 0
39 # include "xlockmore.h"
40
41 #undef countof
42 #define countof(x) (sizeof((x))/sizeof((*x)))
43
44 #ifdef USE_GL
45
46 # define DEF_SPEED          "1.0"
47 # define DEF_DURATION       "20"
48 # define DEF_TITLES         "True"
49 # define DEF_ZOOM           "True"
50 # define DEF_TILT           "XY"
51 # define DEF_MIPMAP         "True"
52 # define DEF_DEBUG          "False"
53
54 #include "rotator.h"
55 #include "gltrackball.h"
56 #include "grab-ximage.h"
57 #include "texfont.h"
58
59 # ifndef HAVE_JWXYZ
60 #  include <X11/Intrinsic.h>     /* for XrmDatabase in -debug mode */
61 # endif
62
63 /* Should be in <GL/glext.h> */
64 # ifndef  GL_TEXTURE_MAX_ANISOTROPY_EXT
65 #  define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
66 # endif
67 # ifndef  GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
68 #  define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
69 # endif
70
71 typedef struct {
72   double x, y, w, h;
73 } rect;
74
75 typedef enum { EARLY, NORMAL, LOADING, OUT, IN, DEAD } fade_mode;
76 static int fade_ticks = 60;
77
78 typedef struct {
79   char *title;                  /* the filename of this image */
80   int w, h;                     /* size in pixels of the image */
81   int tw, th;                   /* size in pixels of the texture */
82   XRectangle geom;              /* where in the image the bits are */
83   GLuint texid;
84 } image;
85
86 typedef struct {
87   ModeInfo *mi;
88   image current, loading;
89   GLfloat r, theta;             /* radius and rotation on the tube */
90   rotator *rot;                 /* for zoomery */
91   Bool from_top_p;              /* whether this image drops in or rises up */
92   time_t expires;               /* when this image should be replaced */
93   fade_mode mode;               /* in/out animation state */
94   int mode_tick;
95   Bool loaded_p;                /* whether background load is done */
96 } image_frame;
97
98
99 typedef struct {
100   GLXContext *glx_context;
101   GLfloat anisotropic;
102   rotator *rot;
103   trackball_state *trackball;
104   Bool button_down_p;
105   time_t button_down_time;
106
107   int nframes;                  /* how many frames are loaded */
108   int frames_size;
109   image_frame **frames;         /* pointers to the frames */
110
111   Bool awaiting_first_images_p;
112   int loads_in_progress;
113
114   texture_font_data *texfont, *titlefont;
115
116   fade_mode mode;
117   int mode_tick;
118
119   int loading_sw, loading_sh;
120
121   time_t last_time, now;
122   int draw_tick;
123
124 } carousel_state;
125
126 static carousel_state *sss = NULL;
127
128
129 /* Command-line arguments
130  */
131 static GLfloat speed;       /* animation speed scale factor */
132 static int duration;        /* reload images after this long */
133 static Bool mipmap_p;       /* Use mipmaps instead of single textures. */
134 static Bool titles_p;       /* Display image titles. */
135 static Bool zoom_p;         /* Throb the images in and out as they spin. */
136 static char *tilt_str;
137 static Bool tilt_x_p;       /* Tilt axis towards the viewer */
138 static Bool tilt_y_p;       /* Tilt axis side to side */
139 static Bool debug_p;        /* Be loud and do weird things. */
140
141
142 static XrmOptionDescRec opts[] = {
143   {"-zoom",         ".zoom",          XrmoptionNoArg, "True"  },
144   {"-no-zoom",      ".zoom",          XrmoptionNoArg, "False" },
145   {"-tilt",         ".tilt",          XrmoptionSepArg, 0  },
146   {"-no-tilt",      ".tilt",          XrmoptionNoArg, ""  },
147   {"-titles",       ".titles",        XrmoptionNoArg, "True"  },
148   {"-no-titles",    ".titles",        XrmoptionNoArg, "False" },
149   {"-mipmaps",      ".mipmap",        XrmoptionNoArg, "True"  },
150   {"-no-mipmaps",   ".mipmap",        XrmoptionNoArg, "False" },
151   {"-duration",     ".duration",      XrmoptionSepArg, 0 },
152   {"-debug",        ".debug",         XrmoptionNoArg, "True"  },
153   {"-font",         ".font",          XrmoptionSepArg, 0 },
154   {"-speed",        ".speed",         XrmoptionSepArg, 0 },
155 };
156
157 static argtype vars[] = {
158   { &mipmap_p,      "mipmap",       "Mipmap",       DEF_MIPMAP,      t_Bool},
159   { &debug_p,       "debug",        "Debug",        DEF_DEBUG,       t_Bool},
160   { &titles_p,      "titles",       "Titles",       DEF_TITLES,      t_Bool},
161   { &zoom_p,        "zoom",         "Zoom",         DEF_ZOOM,        t_Bool},
162   { &tilt_str,      "tilt",         "Tilt",         DEF_TILT,        t_String},
163   { &speed,         "speed",        "Speed",        DEF_SPEED,       t_Float},
164   { &duration,      "duration",     "Duration",     DEF_DURATION,    t_Int},
165 };
166
167 ENTRYPOINT ModeSpecOpt carousel_opts = {countof(opts), opts, countof(vars), vars, NULL};
168
169
170 /* Allocates a frame structure and stores it in the list.
171  */
172 static image_frame *
173 alloc_frame (ModeInfo *mi)
174 {
175   carousel_state *ss = &sss[MI_SCREEN(mi)];
176   image_frame *frame = (image_frame *) calloc (1, sizeof (*frame));
177
178   frame->mi = mi;
179   frame->mode = EARLY;
180   frame->rot = make_rotator (0, 0, 0, 0, 0.04 * frand(1.0) * speed, False);
181
182   glGenTextures (1, &frame->current.texid);
183   glGenTextures (1, &frame->loading.texid);
184   if (frame->current.texid <= 0) abort();
185   if (frame->loading.texid <= 0) abort();
186
187   if (ss->frames_size <= ss->nframes)
188     {
189       ss->frames_size = (ss->frames_size * 1.2) + ss->nframes;
190       ss->frames = (image_frame **)
191         realloc (ss->frames, ss->frames_size * sizeof(*ss->frames));
192       if (! ss->frames)
193         {
194           fprintf (stderr, "%s: out of memory (%d images)\n",
195                    progname, ss->frames_size);
196           exit (1);
197         }
198     }
199
200   ss->frames[ss->nframes++] = frame;
201
202   return frame;
203 }
204
205
206 static void image_loaded_cb (const char *filename, XRectangle *geom,
207                              int image_width, int image_height,
208                              int texture_width, int texture_height,
209                              void *closure);
210
211
212 /* Load a new file into the given image struct.
213  */
214 static void
215 load_image (ModeInfo *mi, image_frame *frame)
216 {
217   carousel_state *ss = &sss[MI_SCREEN(mi)];
218   int wire = MI_IS_WIREFRAME(mi);
219
220   if (debug_p && !wire && frame->current.w != 0)
221     fprintf (stderr, "%s:  dropped %4d x %-4d  %4d x %-4d  \"%s\"\n",
222              progname, 
223              frame->current.geom.width, 
224              frame->current.geom.height, 
225              frame->current.tw, frame->current.th,
226              (frame->current.title ? frame->current.title : "(null)"));
227
228   switch (frame->mode) 
229     {
230     case EARLY:  break;
231     case NORMAL: frame->mode = LOADING; break;
232     default: abort();
233     }
234
235   ss->loads_in_progress++;
236
237   if (wire)
238     image_loaded_cb (0, 0, 0, 0, 0, 0, frame);
239   else
240     {
241       int w = (MI_WIDTH(mi)  / 2) - 1;
242       int h = (MI_HEIGHT(mi) / 2) - 1;
243       if (w <= 10) w = 10;
244       if (h <= 10) h = 10;
245
246       if (w > h * 5) {   /* tiny window: use 16:9 boxes */
247         h = w * 9/16;
248       }
249
250       load_texture_async (mi->xgwa.screen, mi->window, *ss->glx_context, w, h,
251                           mipmap_p, frame->loading.texid, 
252                           image_loaded_cb, frame);
253     }
254 }
255
256
257 /* Callback that tells us that the texture has been loaded.
258  */
259 static void
260 image_loaded_cb (const char *filename, XRectangle *geom,
261                  int image_width, int image_height,
262                  int texture_width, int texture_height,
263                  void *closure)
264 {
265   image_frame *frame = (image_frame *) closure;
266   ModeInfo *mi = frame->mi;
267   carousel_state *ss = &sss[MI_SCREEN(mi)];
268   int wire = MI_IS_WIREFRAME(mi);
269
270   if (wire)
271     {
272       frame->loading.w = MI_WIDTH (mi) * (0.5 + frand (1.0));
273       frame->loading.h = MI_HEIGHT (mi);
274       frame->loading.geom.width  = frame->loading.w;
275       frame->loading.geom.height = frame->loading.h;
276       goto DONE;
277     }
278
279   if (image_width == 0 || image_height == 0)
280     exit (1);
281
282   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
283   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
284                    mipmap_p ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
285
286   if (ss->anisotropic >= 1.0)
287     glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 
288                      ss->anisotropic);
289
290   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
291   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
292
293   frame->loading.w  = image_width;
294   frame->loading.h  = image_height;
295   frame->loading.tw = texture_width;
296   frame->loading.th = texture_height;
297   frame->loading.geom = *geom;
298
299   if (frame->loading.title)
300     free (frame->loading.title);
301   frame->loading.title = (filename ? strdup (filename) : 0);
302
303   /* xscreensaver-getimage returns paths relative to the image directory
304      now, so leave the sub-directory part in.  Unless it's an absolute path.
305   */
306   if (frame->loading.title && frame->loading.title[0] == '/')
307     {    /* strip filename to part after last /. */
308       char *s = strrchr (frame->loading.title, '/');
309       if (s) strcpy (frame->loading.title, s+1);
310     }
311
312   if (debug_p)
313     fprintf (stderr, "%s:   loaded %4d x %-4d  %4d x %-4d  \"%s\"\n",
314              progname,
315              frame->loading.geom.width, 
316              frame->loading.geom.height, 
317              frame->loading.tw, frame->loading.th,
318              (frame->loading.title ? frame->loading.title : "(null)"));
319
320  DONE:
321
322   frame->loaded_p = True;
323
324   if (ss->loads_in_progress <= 0) abort();
325   ss->loads_in_progress--;
326
327   /* This image expires N seconds after it finished loading. */
328   frame->expires = time((time_t *) 0) + (duration * MI_COUNT(mi));
329
330   switch (frame->mode) 
331     {
332     case EARLY:         /* part of the initial batch of images */
333       {
334         image swap = frame->current;
335         frame->current = frame->loading;
336         frame->loading = swap;
337       }
338       break;
339     case LOADING:       /* start dropping the old image out */
340       {
341         frame->mode = OUT;
342         frame->mode_tick = fade_ticks / speed;
343         frame->from_top_p = random() & 1;
344       }
345       break;
346     default:
347       abort();
348     }
349 }
350
351
352 static void loading_msg (ModeInfo *mi, int n);
353
354 static Bool
355 load_initial_images (ModeInfo *mi)
356 {
357   carousel_state *ss = &sss[MI_SCREEN(mi)];
358   int i;
359   Bool all_loaded_p = True;
360   for (i = 0; i < ss->nframes; i++)
361     if (! ss->frames[i]->loaded_p)
362       all_loaded_p = False;
363
364   if (all_loaded_p)
365     {
366       if (ss->nframes < MI_COUNT (mi))
367         {
368           /* The frames currently on the list are fully loaded.
369              Start the next one loading.  (We run the image loader
370              asynchronously, but we load them one at a time.)
371            */
372           load_image (mi, alloc_frame (mi));
373         }
374       else
375         {
376           /* The first batch of images are now all loaded!
377              Stagger the expire times so that they don't all drop out at once.
378            */
379           time_t now = time((time_t *) 0);
380           int i;
381
382           for (i = 0; i < ss->nframes; i++)
383             {
384               image_frame *frame = ss->frames[i];
385               frame->r = 1.0;
386               frame->theta = i * 360.0 / ss->nframes;
387               frame->expires = now + (duration * (i + 1));
388               frame->mode = NORMAL;
389             }
390
391           /* Instead of always going clockwise, shuffle the expire times
392              of the frames so that they drop out in a random order.
393           */
394           for (i = 0; i < ss->nframes; i++)
395             {
396               image_frame *frame1 = ss->frames[i];
397               image_frame *frame2 = ss->frames[random() % ss->nframes];
398               time_t swap = frame1->expires;
399               frame1->expires = frame2->expires;
400               frame2->expires = swap;
401             }
402
403           ss->awaiting_first_images_p = False;
404         }
405     }
406       
407   loading_msg (mi, ss->nframes-1);
408
409   return !ss->awaiting_first_images_p;
410 }
411
412
413 ENTRYPOINT void
414 reshape_carousel (ModeInfo *mi, int width, int height)
415 {
416   GLfloat h = (GLfloat) height / (GLfloat) width;
417   int y = 0;
418
419   if (width > height * 5) {   /* tiny window: show middle */
420     height = width * 9/16;
421     y = -height/2;
422     h = height / (GLfloat) width;
423   }
424
425   glViewport (0, y, (GLint) width, (GLint) height);
426
427   glMatrixMode(GL_PROJECTION);
428   glLoadIdentity();
429   gluPerspective (60.0, 1/h, 1.0, 8.0);
430
431   glMatrixMode(GL_MODELVIEW);
432   glLoadIdentity();
433   gluLookAt( 0.0, 0.0, 2.6,
434              0.0, 0.0, 0.0,
435              0.0, 1.0, 0.0);
436
437   glClear(GL_COLOR_BUFFER_BIT);
438 }
439
440
441 ENTRYPOINT Bool
442 carousel_handle_event (ModeInfo *mi, XEvent *event)
443 {
444   carousel_state *ss = &sss[MI_SCREEN(mi)];
445
446   if (event->xany.type == ButtonPress &&
447       event->xbutton.button == Button1)
448     {
449       if (! ss->button_down_p)
450         ss->button_down_time = time((time_t *) 0);
451     }
452   else if (event->xany.type == ButtonRelease &&
453            event->xbutton.button == Button1)
454     {
455       if (ss->button_down_p)
456         {
457           /* Add the time the mouse was held to the expire times of all
458              frames, so that mouse-dragging doesn't count against
459              image expiration.
460            */
461           int secs = time((time_t *) 0) - ss->button_down_time;
462           int i;
463           for (i = 0; i < ss->nframes; i++)
464             ss->frames[i]->expires += secs;
465         }
466     }
467
468   if (gltrackball_event_handler (event, ss->trackball,
469                                  MI_WIDTH (mi), MI_HEIGHT (mi),
470                                  &ss->button_down_p))
471     return True;
472   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
473     {
474       int i = random() % ss->nframes;
475       ss->frames[i]->expires  = 0;
476       return True;
477     }
478
479   return False;
480 }
481
482
483 /* Kludge to add "-v" to invocation of "xscreensaver-getimage" in -debug mode
484  */
485 static void
486 hack_resources (Display *dpy)
487 {
488 # ifndef HAVE_JWXYZ
489   char *res = "desktopGrabber";
490   char *val = get_string_resource (dpy, res, "DesktopGrabber");
491   char buf1[255];
492   char buf2[255];
493   XrmValue value;
494   XrmDatabase db = XtDatabase (dpy);
495   sprintf (buf1, "%.100s.%.100s", progname, res);
496   sprintf (buf2, "%.200s -v", val);
497   value.addr = buf2;
498   value.size = strlen(buf2);
499   XrmPutResource (&db, buf1, "String", &value);
500 # endif /* !HAVE_JWXYZ */
501 }
502
503
504 static void
505 loading_msg (ModeInfo *mi, int n)
506 {
507   carousel_state *ss = &sss[MI_SCREEN(mi)];
508   int wire = MI_IS_WIREFRAME(mi);
509   char text[100];
510
511   if (wire) return;
512
513   if (n == 0)
514     sprintf (text, "Loading images...");
515   else
516     sprintf (text, "Loading images...  (%d%%)",
517              (int) (n * 100 / MI_COUNT(mi)));
518
519   if (ss->loading_sw == 0)
520     {
521       /* only do this once, so that the string doesn't move. */
522       XCharStruct e;
523       texture_string_metrics (ss->titlefont, text, &e, 0, 0);
524       ss->loading_sw = e.width;
525       ss->loading_sh = e.ascent + e.descent;
526     }
527
528   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
529
530   glMatrixMode(GL_PROJECTION);
531   glPushMatrix();
532   glLoadIdentity();
533
534   glMatrixMode(GL_MODELVIEW);
535   glPushMatrix();
536   glLoadIdentity();
537
538 /*
539   {
540     double rot = current_device_rotation();
541     glRotatef(rot, 0, 0, 1);
542     if ((rot >  45 && rot <  135) ||
543         (rot < -45 && rot > -135))
544       {
545         GLfloat s = MI_WIDTH(mi) / (GLfloat) MI_HEIGHT(mi);
546         glScalef (s, 1/s, 1);
547       }
548   }
549 */
550
551 # ifdef HAVE_MOBILE
552   if (MI_WIDTH(mi) < MI_HEIGHT(mi))  /* portrait orientation */
553     {
554       GLfloat s = (MI_WIDTH(mi) / (GLfloat) MI_HEIGHT(mi));
555       glScalef (s, s, s);
556       glTranslatef(-s/2, 0, 0);
557     }
558 # endif
559
560   glOrtho(0, MI_WIDTH(mi), 0, MI_HEIGHT(mi), -1, 1);
561   glTranslatef ((MI_WIDTH(mi)  - ss->loading_sw) / 2,
562                 (MI_HEIGHT(mi) - ss->loading_sh) / 2,
563                 0);
564   glColor3f (1, 1, 0);
565   glEnable (GL_TEXTURE_2D);
566   glDisable (GL_DEPTH_TEST);
567   print_texture_string (ss->titlefont, text);
568   glEnable (GL_DEPTH_TEST);
569   glPopMatrix();
570
571   glMatrixMode(GL_PROJECTION);
572   glPopMatrix();
573
574   glMatrixMode(GL_MODELVIEW);
575
576   glFinish();
577   glXSwapBuffers (MI_DISPLAY (mi), MI_WINDOW(mi));
578 }
579
580
581 ENTRYPOINT void
582 init_carousel (ModeInfo *mi)
583 {
584   int screen = MI_SCREEN(mi);
585   carousel_state *ss;
586   int wire = MI_IS_WIREFRAME(mi);
587   
588   MI_INIT (mi, sss);
589   ss = &sss[screen];
590
591   if ((ss->glx_context = init_GL(mi)) != NULL) {
592     reshape_carousel (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
593     clear_gl_error(); /* WTF? sometimes "invalid op" from glViewport! */
594   } else {
595     MI_CLEARWINDOW(mi);
596   }
597
598   if (!tilt_str || !*tilt_str)
599     ;
600   else if (!strcasecmp (tilt_str, "0"))
601     ;
602   else if (!strcasecmp (tilt_str, "X"))
603     tilt_x_p = 1;
604   else if (!strcasecmp (tilt_str, "Y"))
605     tilt_y_p = 1;
606   else if (!strcasecmp (tilt_str, "XY"))
607     tilt_x_p = tilt_y_p = 1;
608   else
609     {
610       fprintf (stderr, "%s: tilt must be 'X', 'Y', 'XY' or '', not '%s'\n",
611                progname, tilt_str);
612       exit (1);
613     }
614
615   {
616     double spin_speed   = speed * 0.2;    /* rotation of tube around axis */
617     double spin_accel   = speed * 0.1;
618     double wander_speed = speed * 0.001;  /* tilting of axis */
619
620     spin_speed   *= 0.9 + frand(0.2);
621     wander_speed *= 0.9 + frand(0.2);
622
623     ss->rot = make_rotator (spin_speed, spin_speed, spin_speed,
624                             spin_accel, wander_speed, True);
625
626     ss->trackball = gltrackball_init (False);
627   }
628
629   if (strstr ((char *) glGetString(GL_EXTENSIONS),
630               "GL_EXT_texture_filter_anisotropic"))
631     glGetFloatv (GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &ss->anisotropic);
632   else
633     ss->anisotropic = 0.0;
634
635   glDisable (GL_LIGHTING);
636   glEnable (GL_DEPTH_TEST);
637   glDisable (GL_CULL_FACE);
638
639   if (! wire)
640     {
641       glShadeModel (GL_SMOOTH);
642       glEnable (GL_LINE_SMOOTH);
643       /* This gives us a transparent diagonal slice through each image! */
644       /* glEnable (GL_POLYGON_SMOOTH); */
645       glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);
646       glEnable (GL_BLEND);
647       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
648       glEnable (GL_ALPHA_TEST);
649
650       glEnable (GL_POLYGON_OFFSET_FILL);
651       glPolygonOffset (1.0, 1.0);
652
653     }
654
655   ss->texfont = load_texture_font (MI_DISPLAY(mi), "font");
656   ss->titlefont = load_texture_font (MI_DISPLAY(mi), "titleFont");
657
658   if (debug_p)
659     hack_resources (MI_DISPLAY (mi));
660
661   ss->nframes = 0;
662   ss->frames_size = 10;
663   ss->frames = (image_frame **)
664     calloc (1, ss->frames_size * sizeof(*ss->frames));
665
666   ss->mode = IN;
667   ss->mode_tick = fade_ticks / speed;
668
669   ss->awaiting_first_images_p = True;
670 }
671
672
673 static void
674 draw_frame (ModeInfo *mi, image_frame *frame, time_t now, Bool body_p)
675 {
676   carousel_state *ss = &sss[MI_SCREEN(mi)];
677   int wire = MI_IS_WIREFRAME(mi);
678
679   GLfloat texw  = frame->current.geom.width  / (GLfloat) frame->current.tw;
680   GLfloat texh  = frame->current.geom.height / (GLfloat) frame->current.th;
681   GLfloat texx1 = frame->current.geom.x / (GLfloat) frame->current.tw;
682   GLfloat texy1 = frame->current.geom.y / (GLfloat) frame->current.th;
683   GLfloat texx2 = texx1 + texw;
684   GLfloat texy2 = texy1 + texh;
685   GLfloat aspect = ((GLfloat) frame->current.geom.height /
686                     (GLfloat) frame->current.geom.width);
687
688   glBindTexture (GL_TEXTURE_2D, frame->current.texid);
689
690   glPushMatrix();
691
692   /* Position this image on the wheel.
693    */
694   glRotatef (frame->theta, 0, 1, 0);
695   glTranslatef (0, 0, frame->r);
696
697   /* Scale down the image so that all N frames fit on the wheel
698      without bumping in to each other.
699   */
700   {
701     GLfloat t, s;
702     switch (ss->nframes)
703       {
704       case 1:  t = -1.0; s = 1.7; break;
705       case 2:  t = -0.8; s = 1.6; break;
706       case 3:  t = -0.4; s = 1.5; break;
707       case 4:  t = -0.2; s = 1.3; break;
708       default: t =  0.0; s = 6.0 / ss->nframes; break;
709       }
710     glTranslatef (0, 0, t);
711     glScalef (s, s, s);
712   }
713
714   /* Center this image on the wheel plane.
715    */
716   glTranslatef (-0.5, -(aspect/2), 0);
717
718   /* Move as per the "zoom in and out" setting.
719    */
720   if (zoom_p)
721     {
722       double x, y, z;
723       /* Only use the Z component of the rotator for in/out position. */
724       get_position (frame->rot, &x, &y, &z, !ss->button_down_p);
725       glTranslatef (0, 0, z/2);
726     }
727
728   /* Compute the "drop in and out" state.
729    */
730   switch (frame->mode)
731     {
732     case EARLY:
733       abort();
734       break;
735     case NORMAL:
736       if (!ss->button_down_p &&
737           now >= frame->expires &&
738           ss->loads_in_progress == 0)  /* only load one at a time */
739         load_image (mi, frame);
740       break;
741     case LOADING:
742       break;
743     case OUT:
744       if (--frame->mode_tick <= 0) {
745         image swap = frame->current;
746         frame->current = frame->loading;
747         frame->loading = swap;
748
749         frame->mode = IN;
750         frame->mode_tick = fade_ticks / speed;
751       }
752       break;
753     case IN:
754       if (--frame->mode_tick <= 0)
755         frame->mode = NORMAL;
756       break;
757     default:
758       abort();
759     }
760
761   /* Now translate for current in/out state.
762    */
763   if (frame->mode == OUT || frame->mode == IN)
764     {
765       GLfloat t = (frame->mode == OUT
766                    ? frame->mode_tick / (fade_ticks / speed)
767                    : (((fade_ticks / speed) - frame->mode_tick + 1) /
768                       (fade_ticks / speed)));
769       t = 5 * (1 - t);
770       if (frame->from_top_p) t = -t;
771       glTranslatef (0, t, 0);
772     }
773
774   if (body_p)                                   /* Draw the image quad. */
775     {
776       if (! wire)
777         {
778           glColor3f (1, 1, 1);
779           glNormal3f (0, 0, 1);
780           glEnable (GL_TEXTURE_2D);
781           glBegin (GL_QUADS);
782           glNormal3f (0, 0, 1);
783           glTexCoord2f (texx1, texy2); glVertex3f (0, 0, 0);
784           glTexCoord2f (texx2, texy2); glVertex3f (1, 0, 0);
785           glTexCoord2f (texx2, texy1); glVertex3f (1, aspect, 0);
786           glTexCoord2f (texx1, texy1); glVertex3f (0, aspect, 0);
787           glEnd();
788         }
789
790       /* Draw a box around it.
791        */
792       glLineWidth (2.0);
793       glColor3f (0.5, 0.5, 0.5);
794       glDisable (GL_TEXTURE_2D);
795       glBegin (GL_LINE_LOOP);
796       glVertex3f (0, 0, 0);
797       glVertex3f (1, 0, 0);
798       glVertex3f (1, aspect, 0);
799       glVertex3f (0, aspect, 0);
800       glEnd();
801
802     }
803   else                                  /* Draw a title under the image. */
804     {
805       XCharStruct e;
806       int sw, sh;
807       GLfloat scale = 0.05;
808       char *title = frame->current.title ? frame->current.title : "(untitled)";
809       texture_string_metrics (ss->texfont, title, &e, 0, 0);
810       sw = e.width;
811       sh = e.ascent + e.descent;
812
813       glTranslatef (0, -scale, 0);
814
815       scale /= sh;
816       glScalef (scale, scale, scale);
817
818       glTranslatef (((1/scale) - sw) / 2, 0, 0);
819       glColor3f (1, 1, 1);
820
821       if (!wire)
822         {
823           glEnable (GL_TEXTURE_2D);
824           print_texture_string (ss->texfont, title);
825         }
826       else
827         {
828           glBegin (GL_LINE_LOOP);
829           glVertex3f (0,  0,  0);
830           glVertex3f (sw, 0,  0);
831           glVertex3f (sw, sh, 0);
832           glVertex3f (0,  sh, 0);
833           glEnd();
834         }
835     }
836
837   glPopMatrix();
838 }
839
840
841 ENTRYPOINT void
842 draw_carousel (ModeInfo *mi)
843 {
844   carousel_state *ss = &sss[MI_SCREEN(mi)];
845   int i;
846
847   if (!ss->glx_context)
848     return;
849
850   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(ss->glx_context));
851
852   if (ss->awaiting_first_images_p)
853     if (!load_initial_images (mi))
854       return;
855
856   /* Only check the wall clock every 10 frames */
857   {
858     if (ss->now == 0 || ss->draw_tick++ > 10)
859       {
860         ss->now = time((time_t *) 0);
861         if (ss->last_time == 0) ss->last_time = ss->now;
862         ss->draw_tick = 0;
863       }
864   }
865
866
867   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
868
869   glPushMatrix();
870
871   glRotatef(current_device_rotation(), 0, 0, 1);
872
873
874   /* Run the startup "un-shrink" animation.
875    */
876   switch (ss->mode)
877     {
878     case IN:
879       if (--ss->mode_tick <= 0)
880         {
881           ss->mode = NORMAL;
882           ss->last_time = time((time_t *) 0);
883         }
884       break;
885     case NORMAL:
886       break;
887     default:
888       abort();
889     }
890
891
892   /* Scale as per the startup "un-shrink" animation.
893    */
894   if (ss->mode != NORMAL)
895     {
896       GLfloat s = (ss->mode == OUT
897                    ? ss->mode_tick / (fade_ticks / speed)
898                    : (((fade_ticks / speed) - ss->mode_tick + 1) /
899                       (fade_ticks / speed)));
900       glScalef (s, s, s);
901     }
902
903   /* Rotate and tilt as per the user, and the motion modeller.
904    */
905   {
906     double x, y, z;
907     gltrackball_rotate (ss->trackball);
908
909     /* Tilt the tube up or down by up to 30 degrees */
910     get_position (ss->rot, &x, &y, &z, !ss->button_down_p);
911     if (tilt_x_p)
912       glRotatef (15 - (x * 30), 1, 0, 0);
913     if (tilt_y_p)
914       glRotatef (7  - (y * 14), 0, 0, 1);
915
916     /* Only use the Y component of the rotator. */
917     get_rotation (ss->rot, &x, &y, &z, !ss->button_down_p);
918     glRotatef (y * 360, 0, 1, 0);
919   }
920
921   /* First draw each image, then draw the titles.  GL insists that you
922      draw back-to-front in order to make alpha blending work properly,
923      so we need to draw all of the 100% opaque images before drawing
924      any of the not-100%-opaque titles.
925    */
926   for (i = 0; i < ss->nframes; i++)
927     draw_frame (mi, ss->frames[i], ss->now, True);
928   if (titles_p)
929     for (i = 0; i < ss->nframes; i++)
930       draw_frame (mi, ss->frames[i], ss->now, False);
931
932   glPopMatrix();
933
934   if (mi->fps_p) do_fps (mi);
935   glFinish();
936   glXSwapBuffers (MI_DISPLAY (mi), MI_WINDOW(mi));
937 }
938
939 XSCREENSAVER_MODULE ("Carousel", carousel)
940
941 #endif /* USE_GL */