rnd-20060430-3-src
[rocksndiamonds.git] / src / libgame / system.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2002 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * system.c                                                 *
12 ***********************************************************/
13
14 #include <string.h>
15 #include <signal.h>
16
17 #include "platform.h"
18
19 #if defined(PLATFORM_MSDOS)
20 #include <fcntl.h>
21 #endif
22
23 #include "system.h"
24 #include "image.h"
25 #include "sound.h"
26 #include "setup.h"
27 #include "joystick.h"
28 #include "misc.h"
29
30
31 /* ========================================================================= */
32 /* exported variables                                                        */
33 /* ========================================================================= */
34
35 struct ProgramInfo      program;
36 struct OptionInfo       options;
37 struct VideoSystemInfo  video;
38 struct AudioSystemInfo  audio;
39 struct GfxInfo          gfx;
40 struct ArtworkInfo      artwork;
41 struct JoystickInfo     joystick;
42 struct SetupInfo        setup;
43
44 LevelDirTree           *leveldir_first_all = NULL;
45 LevelDirTree           *leveldir_first = NULL;
46 LevelDirTree           *leveldir_current = NULL;
47 int                     level_nr;
48
49 Display                *display = NULL;
50 Visual                 *visual = NULL;
51 int                     screen = 0;
52 Colormap                cmap = None;
53
54 DrawWindow             *window = NULL;
55 DrawBuffer             *backbuffer = NULL;
56 DrawBuffer             *drawto = NULL;
57
58 int                     button_status = MB_NOT_PRESSED;
59 boolean                 motion_status = FALSE;
60
61 int                     redraw_mask = REDRAW_NONE;
62 int                     redraw_tiles = 0;
63
64 int                     FrameCounter = 0;
65
66
67 /* ========================================================================= */
68 /* init/close functions                                                      */
69 /* ========================================================================= */
70
71 void InitProgramInfo(char *argv0,
72                      char *userdata_directory, char *program_title,
73                      char *window_title, char *icon_title,
74                      char *x11_icon_filename, char *x11_iconmask_filename,
75                      char *msdos_cursor_filename,
76                      char *cookie_prefix, char *filename_prefix,
77                      int program_version)
78 {
79   program.command_basepath = getBasePath(argv0);
80   program.command_basename = getBaseName(argv0);
81
82   program.userdata_directory = userdata_directory;
83   program.program_title = program_title;
84   program.window_title = window_title;
85   program.icon_title = icon_title;
86   program.x11_icon_filename = x11_icon_filename;
87   program.x11_iconmask_filename = x11_iconmask_filename;
88   program.msdos_cursor_filename = msdos_cursor_filename;
89
90   program.cookie_prefix = cookie_prefix;
91   program.filename_prefix = filename_prefix;
92
93   program.version_major = VERSION_MAJOR(program_version);
94   program.version_minor = VERSION_MINOR(program_version);
95   program.version_patch = VERSION_PATCH(program_version);
96 }
97
98 void InitExitFunction(void (*exit_function)(int))
99 {
100   program.exit_function = exit_function;
101
102   /* set signal handlers to custom exit function */
103   signal(SIGINT, exit_function);
104   signal(SIGTERM, exit_function);
105
106 #if defined(TARGET_SDL)
107   /* set exit function to automatically cleanup SDL stuff after exit() */
108   atexit(SDL_Quit);
109 #endif
110 }
111
112 void InitPlatformDependentStuff(void)
113 {
114 #if defined(PLATFORM_MSDOS)
115   _fmode = O_BINARY;
116   initErrorFile();
117 #endif
118
119 #if defined(TARGET_SDL)
120   if (SDL_Init(SDL_INIT_EVENTTHREAD | SDL_INIT_NOPARACHUTE) < 0)
121     Error(ERR_EXIT, "SDL_Init() failed: %s", SDL_GetError());
122
123   SDLNet_Init();
124 #endif
125 }
126
127 void ClosePlatformDependentStuff(void)
128 {
129 #if defined(PLATFORM_MSDOS)
130   dumpErrorFile();
131 #endif
132 }
133
134 void InitGfxFieldInfo(int sx, int sy, int sxsize, int sysize,
135                       int real_sx, int real_sy,
136                       int full_sxsize, int full_sysize,
137                       Bitmap *field_save_buffer)
138 {
139   gfx.sx = sx;
140   gfx.sy = sy;
141   gfx.sxsize = sxsize;
142   gfx.sysize = sysize;
143   gfx.real_sx = real_sx;
144   gfx.real_sy = real_sy;
145   gfx.full_sxsize = full_sxsize;
146   gfx.full_sysize = full_sysize;
147
148   gfx.field_save_buffer = field_save_buffer;
149
150   gfx.background_bitmap = NULL;
151   gfx.background_bitmap_mask = REDRAW_NONE;
152
153   SetDrawDeactivationMask(REDRAW_NONE);         /* do not deactivate drawing */
154   SetDrawBackgroundMask(REDRAW_NONE);           /* deactivate masked drawing */
155 }
156
157 void InitGfxDoor1Info(int dx, int dy, int dxsize, int dysize)
158 {
159   gfx.dx = dx;
160   gfx.dy = dy;
161   gfx.dxsize = dxsize;
162   gfx.dysize = dysize;
163 }
164
165 void InitGfxDoor2Info(int vx, int vy, int vxsize, int vysize)
166 {
167   gfx.vx = vx;
168   gfx.vy = vy;
169   gfx.vxsize = vxsize;
170   gfx.vysize = vysize;
171 }
172
173 void InitGfxScrollbufferInfo(int scrollbuffer_width, int scrollbuffer_height)
174 {
175   /* currently only used by MSDOS code to alloc VRAM buffer, if available */
176   gfx.scrollbuffer_width = scrollbuffer_width;
177   gfx.scrollbuffer_height = scrollbuffer_height;
178 }
179
180 void SetDrawDeactivationMask(int draw_deactivation_mask)
181 {
182   gfx.draw_deactivation_mask = draw_deactivation_mask;
183 }
184
185 void SetDrawBackgroundMask(int draw_background_mask)
186 {
187   gfx.draw_background_mask = draw_background_mask;
188 }
189
190 static void DrawBitmapFromTile(Bitmap *bitmap, Bitmap *tile,
191                                int dest_x, int dest_y, int width, int height)
192 {
193   int bitmap_xsize = width;
194   int bitmap_ysize = height;
195   int tile_xsize = tile->width;
196   int tile_ysize = tile->height;
197   int tile_xsteps = (bitmap_xsize + tile_xsize - 1) / tile_xsize;
198   int tile_ysteps = (bitmap_ysize + tile_ysize - 1) / tile_ysize;
199   int x, y;
200
201   for (y = 0; y < tile_ysteps; y++)
202   {
203     for (x = 0; x < tile_xsteps; x++)
204     {
205       int draw_x = dest_x + x * tile_xsize;
206       int draw_y = dest_y + y * tile_ysize;
207       int draw_xsize = MIN(tile_xsize, bitmap_xsize - x * tile_xsize);
208       int draw_ysize = MIN(tile_ysize, bitmap_ysize - y * tile_ysize);
209
210       BlitBitmap(tile, bitmap, 0, 0, draw_xsize, draw_ysize, draw_x, draw_y);
211     }
212   }
213 }
214
215 void SetBackgroundBitmap(Bitmap *background_bitmap_tile, int mask)
216 {
217   if (background_bitmap_tile != NULL)
218     gfx.background_bitmap_mask |= mask;
219   else
220     gfx.background_bitmap_mask &= ~mask;
221
222   if (gfx.background_bitmap == NULL)
223     gfx.background_bitmap = CreateBitmap(video.width, video.height,
224                                          DEFAULT_DEPTH);
225
226   if (background_bitmap_tile == NULL)   /* empty background requested */
227     return;
228
229   if (mask == REDRAW_FIELD)
230     DrawBitmapFromTile(gfx.background_bitmap, background_bitmap_tile,
231                        gfx.real_sx, gfx.real_sy,
232                        gfx.full_sxsize, gfx.full_sysize);
233   else if (mask == REDRAW_DOOR_1)
234   {
235     DrawBitmapFromTile(gfx.background_bitmap, background_bitmap_tile,
236                        gfx.dx, gfx.dy,
237                        gfx.dxsize, gfx.dysize);
238   }
239 }
240
241 void SetMainBackgroundBitmap(Bitmap *background_bitmap_tile)
242 {
243   SetBackgroundBitmap(background_bitmap_tile, REDRAW_FIELD);
244 }
245
246 void SetDoorBackgroundBitmap(Bitmap *background_bitmap_tile)
247 {
248   SetBackgroundBitmap(background_bitmap_tile, REDRAW_DOOR_1);
249 }
250
251
252 /* ========================================================================= */
253 /* video functions                                                           */
254 /* ========================================================================= */
255
256 inline static int GetRealDepth(int depth)
257 {
258   return (depth == DEFAULT_DEPTH ? video.default_depth : depth);
259 }
260
261 inline static void sysFillRectangle(Bitmap *bitmap, int x, int y,
262                                int width, int height, Pixel color)
263 {
264 #if defined(TARGET_SDL)
265   SDLFillRectangle(bitmap, x, y, width, height, color);
266 #else
267   X11FillRectangle(bitmap, x, y, width, height, color);
268 #endif
269 }
270
271 inline static void sysCopyArea(Bitmap *src_bitmap, Bitmap *dst_bitmap,
272                                int src_x, int src_y, int width, int height,
273                                int dst_x, int dst_y, int mask_mode)
274 {
275 #if defined(TARGET_SDL)
276   SDLCopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
277               dst_x, dst_y, mask_mode);
278 #else
279   X11CopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
280               dst_x, dst_y, mask_mode);
281 #endif
282 }
283
284 void InitVideoDisplay(void)
285 {
286 #if defined(TARGET_SDL)
287   SDLInitVideoDisplay();
288 #else
289   X11InitVideoDisplay();
290 #endif
291 }
292
293 void CloseVideoDisplay(void)
294 {
295   KeyboardAutoRepeatOn();
296
297 #if defined(TARGET_SDL)
298   SDL_QuitSubSystem(SDL_INIT_VIDEO);
299 #else
300   if (display)
301     XCloseDisplay(display);
302 #endif
303 }
304
305 void InitVideoBuffer(DrawBuffer **backbuffer, DrawWindow **window,
306                      int width, int height, int depth, boolean fullscreen)
307 {
308   video.width = width;
309   video.height = height;
310   video.depth = GetRealDepth(depth);
311   video.fullscreen_available = FULLSCREEN_STATUS;
312   video.fullscreen_enabled = FALSE;
313
314 #if defined(TARGET_SDL)
315   SDLInitVideoBuffer(backbuffer, window, fullscreen);
316 #else
317   X11InitVideoBuffer(backbuffer, window);
318 #endif
319 }
320
321 Bitmap *CreateBitmapStruct(void)
322 {
323 #if defined(TARGET_SDL)
324   return checked_calloc(sizeof(struct SDLSurfaceInfo));
325 #else
326   return checked_calloc(sizeof(struct X11DrawableInfo));
327 #endif
328 }
329
330 Bitmap *CreateBitmap(int width, int height, int depth)
331 {
332   Bitmap *new_bitmap = CreateBitmapStruct();
333   int real_depth = GetRealDepth(depth);
334
335 #if defined(TARGET_SDL)
336   SDLCreateBitmapContent(new_bitmap, width, height, real_depth);
337 #else
338   X11CreateBitmapContent(new_bitmap, width, height, real_depth);
339 #endif
340
341   new_bitmap->width = width;
342   new_bitmap->height = height;
343
344   return new_bitmap;
345 }
346
347 inline static void FreeBitmapPointers(Bitmap *bitmap)
348 {
349   if (bitmap == NULL)
350     return;
351
352 #if defined(TARGET_SDL)
353   SDLFreeBitmapPointers(bitmap);
354 #else
355   X11FreeBitmapPointers(bitmap);
356 #endif
357
358   checked_free(bitmap->source_filename);
359   bitmap->source_filename = NULL;
360 }
361
362 inline static void TransferBitmapPointers(Bitmap *src_bitmap,
363                                           Bitmap *dst_bitmap)
364 {
365   if (src_bitmap == NULL || dst_bitmap == NULL)
366     return;
367
368   FreeBitmapPointers(dst_bitmap);
369
370   *dst_bitmap = *src_bitmap;
371 }
372
373 void FreeBitmap(Bitmap *bitmap)
374 {
375   if (bitmap == NULL)
376     return;
377
378   FreeBitmapPointers(bitmap);
379
380   free(bitmap);
381 }
382
383 void CloseWindow(DrawWindow *window)
384 {
385 #if defined(TARGET_X11)
386   if (window->drawable)
387   {
388     XUnmapWindow(display, window->drawable);
389     XDestroyWindow(display, window->drawable);
390   }
391   if (window->gc)
392     XFreeGC(display, window->gc);
393 #endif
394 }
395
396 inline static boolean CheckDrawingArea(int x, int y, int width, int height,
397                                        int draw_mask)
398 {
399   if (draw_mask == REDRAW_NONE)
400     return FALSE;
401
402   if (draw_mask & REDRAW_ALL)
403     return TRUE;
404
405   if ((draw_mask & REDRAW_FIELD) && x < gfx.real_sx + gfx.full_sxsize)
406     return TRUE;
407
408   if ((draw_mask & REDRAW_DOOR_1) && x >= gfx.dx && y < gfx.dy + gfx.dysize)
409     return TRUE;
410
411   if ((draw_mask & REDRAW_DOOR_2) && x >= gfx.dx && y >= gfx.vy)
412     return TRUE;
413
414   return FALSE;
415 }
416
417 boolean DrawingDeactivated(int x, int y, int width, int height)
418 {
419   return CheckDrawingArea(x, y, width, height, gfx.draw_deactivation_mask);
420 }
421
422 boolean DrawingOnBackground(int x, int y)
423 {
424   return (CheckDrawingArea(x, y, 1, 1, gfx.background_bitmap_mask) &&
425           CheckDrawingArea(x, y, 1, 1, gfx.draw_background_mask));
426 }
427
428 void BlitBitmap(Bitmap *src_bitmap, Bitmap *dst_bitmap,
429                 int src_x, int src_y, int width, int height,
430                 int dst_x, int dst_y)
431 {
432   if (DrawingDeactivated(dst_x, dst_y, width, height))
433     return;
434
435   sysCopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
436               dst_x, dst_y, BLIT_OPAQUE);
437 }
438
439 void FadeScreen(Bitmap *bitmap_cross, int fade_mode, int fade_delay,
440                 int post_delay)
441 {
442 #if defined(TARGET_SDL)
443   SDLFadeScreen(bitmap_cross, fade_mode, fade_delay, post_delay);
444 #else
445   X11FadeScreen(bitmap_cross, fade_mode, fade_delay, post_delay);
446 #endif
447 }
448
449 void FillRectangle(Bitmap *bitmap, int x, int y, int width, int height,
450                    Pixel color)
451 {
452   if (DrawingDeactivated(x, y, width, height))
453     return;
454
455   sysFillRectangle(bitmap, x, y, width, height, color);
456 }
457
458 void ClearRectangle(Bitmap *bitmap, int x, int y, int width, int height)
459 {
460   FillRectangle(bitmap, x, y, width, height, BLACK_PIXEL);
461 }
462
463 void ClearRectangleOnBackground(Bitmap *bitmap, int x, int y,
464                                 int width, int height)
465 {
466   if (DrawingOnBackground(x, y))
467     BlitBitmap(gfx.background_bitmap, bitmap, x, y, width, height, x, y);
468   else
469     ClearRectangle(bitmap, x, y, width, height);
470 }
471
472 void SetClipMask(Bitmap *bitmap, GC clip_gc, Pixmap clip_pixmap)
473 {
474 #if defined(TARGET_X11)
475   if (clip_gc)
476   {
477     bitmap->clip_gc = clip_gc;
478     XSetClipMask(display, bitmap->clip_gc, clip_pixmap);
479   }
480 #endif
481 }
482
483 void SetClipOrigin(Bitmap *bitmap, GC clip_gc, int clip_x, int clip_y)
484 {
485 #if defined(TARGET_X11)
486   if (clip_gc)
487   {
488     bitmap->clip_gc = clip_gc;
489     XSetClipOrigin(display, bitmap->clip_gc, clip_x, clip_y);
490   }
491 #endif
492 }
493
494 void BlitBitmapMasked(Bitmap *src_bitmap, Bitmap *dst_bitmap,
495                       int src_x, int src_y, int width, int height,
496                       int dst_x, int dst_y)
497 {
498   if (DrawingDeactivated(dst_x, dst_y, width, height))
499     return;
500
501   sysCopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
502               dst_x, dst_y, BLIT_MASKED);
503 }
504
505 void BlitBitmapOnBackground(Bitmap *src_bitmap, Bitmap *dst_bitmap,
506                             int src_x, int src_y, int width, int height,
507                             int dst_x, int dst_y)
508 {
509   if (DrawingOnBackground(dst_x, dst_y))
510   {
511     /* draw background */
512     BlitBitmap(gfx.background_bitmap, dst_bitmap, dst_x, dst_y, width, height,
513                dst_x, dst_y);
514
515     /* draw foreground */
516     SetClipOrigin(src_bitmap, src_bitmap->stored_clip_gc,
517                   dst_x - src_x, dst_y - src_y);
518     BlitBitmapMasked(src_bitmap, dst_bitmap, src_x, src_y, width, height,
519                      dst_x, dst_y);
520   }
521   else
522     BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y, width, height,
523                dst_x, dst_y);
524 }
525
526 void DrawSimpleBlackLine(Bitmap *bitmap, int from_x, int from_y,
527                          int to_x, int to_y)
528 {
529 #if defined(TARGET_SDL)
530   SDLDrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, BLACK_PIXEL);
531 #else
532   X11DrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, BLACK_PIXEL);
533 #endif
534 }
535
536 void DrawSimpleWhiteLine(Bitmap *bitmap, int from_x, int from_y,
537                          int to_x, int to_y)
538 {
539 #if defined(TARGET_SDL)
540   SDLDrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, WHITE_PIXEL);
541 #else
542   X11DrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, WHITE_PIXEL);
543 #endif
544 }
545
546 #if !defined(TARGET_X11_NATIVE)
547 void DrawLine(Bitmap *bitmap, int from_x, int from_y,
548               int to_x, int to_y, Pixel pixel, int line_width)
549 {
550   int x, y;
551
552   for (x = 0; x < line_width; x++)
553   {
554     for (y = 0; y < line_width; y++)
555     {
556       int dx = x - line_width / 2;
557       int dy = y - line_width / 2;
558
559       if ((x == 0 && y == 0) ||
560           (x == 0 && y == line_width - 1) ||
561           (x == line_width - 1 && y == 0) ||
562           (x == line_width - 1 && y == line_width - 1))
563         continue;
564
565 #if defined(TARGET_SDL)
566       SDLDrawLine(bitmap,
567                   from_x + dx, from_y + dy, to_x + dx, to_y + dy, pixel);
568 #elif defined(TARGET_ALLEGRO)
569       AllegroDrawLine(bitmap->drawable, from_x + dx, from_y + dy,
570                       to_x + dx, to_y + dy, pixel);
571 #endif
572     }
573   }
574 }
575 #endif
576
577 void DrawLines(Bitmap *bitmap, struct XY *points, int num_points, Pixel pixel)
578 {
579 #if !defined(TARGET_X11_NATIVE)
580   int line_width = 4;
581   int i;
582
583   for (i = 0; i < num_points - 1; i++)
584     DrawLine(bitmap, points[i].x, points[i].y,
585              points[i + 1].x, points[i + 1].y, pixel, line_width);
586
587   /*
588   SDLDrawLines(bitmap->surface, points, num_points, pixel);
589   */
590 #else
591   XSetForeground(display, bitmap->line_gc[1], pixel);
592   XDrawLines(display, bitmap->drawable, bitmap->line_gc[1],
593              (XPoint *)points, num_points, CoordModeOrigin);
594 #endif
595 }
596
597 Pixel GetPixel(Bitmap *bitmap, int x, int y)
598 {
599   if (x < 0 || x >= bitmap->width ||
600       y < 0 || y >= bitmap->height)
601     return BLACK_PIXEL;
602
603 #if defined(TARGET_SDL)
604   return SDLGetPixel(bitmap, x, y);
605 #elif defined(TARGET_ALLEGRO)
606   return AllegroGetPixel(bitmap->drawable, x, y);
607 #else
608   return X11GetPixel(bitmap, x, y);
609 #endif
610 }
611
612 Pixel GetPixelFromRGB(Bitmap *bitmap, unsigned int color_r,
613                       unsigned int color_g, unsigned int color_b)
614 {
615 #if defined(TARGET_SDL)
616   return SDL_MapRGB(bitmap->surface->format, color_r, color_g, color_b);
617 #elif defined(TARGET_ALLEGRO)
618   return AllegroAllocColorCell(color_r << 8, color_g << 8, color_b << 8);
619 #else
620   return X11GetPixelFromRGB(color_r, color_g, color_b);
621 #endif
622 }
623
624 Pixel GetPixelFromRGBcompact(Bitmap *bitmap, unsigned int color)
625 {
626   unsigned int color_r = (color >> 16) & 0xff;
627   unsigned int color_g = (color >>  8) & 0xff;
628   unsigned int color_b = (color >>  0) & 0xff;
629
630   return GetPixelFromRGB(bitmap, color_r, color_g, color_b);
631 }
632
633 /* execute all pending screen drawing operations */
634 void FlushDisplay(void)
635 {
636 #ifndef TARGET_SDL
637   XFlush(display);
638 #endif
639 }
640
641 /* execute and wait for all pending screen drawing operations */
642 void SyncDisplay(void)
643 {
644 #ifndef TARGET_SDL
645   XSync(display, FALSE);
646 #endif
647 }
648
649 void KeyboardAutoRepeatOn(void)
650 {
651 #if defined(TARGET_SDL)
652   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY / 2,
653                       SDL_DEFAULT_REPEAT_INTERVAL / 2);
654   SDL_EnableUNICODE(1);
655 #else
656   if (display)
657     XAutoRepeatOn(display);
658 #endif
659 }
660
661 void KeyboardAutoRepeatOff(void)
662 {
663 #if defined(TARGET_SDL)
664   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
665   SDL_EnableUNICODE(0);
666 #else
667   if (display)
668     XAutoRepeatOff(display);
669 #endif
670 }
671
672 boolean PointerInWindow(DrawWindow *window)
673 {
674 #if defined(TARGET_SDL)
675   return TRUE;
676 #else
677   Window root, child;
678   int root_x, root_y;
679   unsigned int mask;
680   int win_x, win_y;
681
682   /* if XQueryPointer() returns False, the pointer
683      is not on the same screen as the specified window */
684   return XQueryPointer(display, window->drawable, &root, &child,
685                        &root_x, &root_y, &win_x, &win_y, &mask);
686 #endif
687 }
688
689 boolean SetVideoMode(boolean fullscreen)
690 {
691 #if defined(TARGET_SDL)
692   return SDLSetVideoMode(&backbuffer, fullscreen);
693 #else
694   boolean success = TRUE;
695
696   if (fullscreen && video.fullscreen_available)
697   {
698     Error(ERR_WARN, "fullscreen not available in X11 version");
699
700     /* display error message only once */
701     video.fullscreen_available = FALSE;
702
703     success = FALSE;
704   }
705
706   return success;
707 #endif
708 }
709
710 boolean ChangeVideoModeIfNeeded(boolean fullscreen)
711 {
712 #if defined(TARGET_SDL)
713   if ((fullscreen && !video.fullscreen_enabled && video.fullscreen_available)||
714       (!fullscreen && video.fullscreen_enabled))
715     fullscreen = SetVideoMode(fullscreen);
716 #endif
717
718   return fullscreen;
719 }
720
721 Bitmap *LoadImage(char *filename)
722 {
723   Bitmap *new_bitmap;
724
725 #if defined(TARGET_SDL)
726   new_bitmap = SDLLoadImage(filename);
727 #else
728   new_bitmap = X11LoadImage(filename);
729 #endif
730
731   if (new_bitmap)
732     new_bitmap->source_filename = getStringCopy(filename);
733
734   return new_bitmap;
735 }
736
737 Bitmap *LoadCustomImage(char *basename)
738 {
739   char *filename = getCustomImageFilename(basename);
740   Bitmap *new_bitmap;
741
742   if (filename == NULL)
743     Error(ERR_EXIT, "LoadCustomImage(): cannot find file '%s'", basename);
744
745   if ((new_bitmap = LoadImage(filename)) == NULL)
746     Error(ERR_EXIT, "LoadImage() failed: %s", GetError());
747
748   return new_bitmap;
749 }
750
751 void ReloadCustomImage(Bitmap *bitmap, char *basename)
752 {
753   char *filename = getCustomImageFilename(basename);
754   Bitmap *new_bitmap;
755
756   if (filename == NULL)         /* (should never happen) */
757   {
758     Error(ERR_WARN, "ReloadCustomImage(): cannot find file '%s'", basename);
759     return;
760   }
761
762   if (strEqual(filename, bitmap->source_filename))
763   {
764     /* The old and new image are the same (have the same filename and path).
765        This usually means that this image does not exist in this graphic set
766        and a fallback to the existing image is done. */
767
768     return;
769   }
770
771   if ((new_bitmap = LoadImage(filename)) == NULL)
772   {
773     Error(ERR_WARN, "LoadImage() failed: %s", GetError());
774     return;
775   }
776
777   if (bitmap->width != new_bitmap->width ||
778       bitmap->height != new_bitmap->height)
779   {
780     Error(ERR_WARN, "ReloadCustomImage: new image '%s' has wrong dimensions",
781           filename);
782     FreeBitmap(new_bitmap);
783     return;
784   }
785
786   TransferBitmapPointers(new_bitmap, bitmap);
787   free(new_bitmap);
788 }
789
790 Bitmap *ZoomBitmap(Bitmap *src_bitmap, int zoom_width, int zoom_height)
791 {
792   Bitmap *dst_bitmap = CreateBitmap(zoom_width, zoom_height, DEFAULT_DEPTH);
793
794 #if defined(TARGET_SDL)
795   SDLZoomBitmap(src_bitmap, dst_bitmap);
796 #else
797   X11ZoomBitmap(src_bitmap, dst_bitmap);
798 #endif
799
800   return dst_bitmap;
801 }
802
803 static void CreateScaledBitmaps(Bitmap *old_bitmap, int zoom_factor,
804                                 boolean create_small_bitmaps)
805 {
806   Bitmap swap_bitmap;
807   Bitmap *new_bitmap, *tmp_bitmap_1, *tmp_bitmap_2, *tmp_bitmap_8;
808   int width_1, height_1, width_2, height_2, width_8, height_8;
809   int new_width, new_height;
810
811   /* calculate new image dimensions for normal sized image */
812   width_1  = old_bitmap->width  * zoom_factor;
813   height_1 = old_bitmap->height * zoom_factor;
814
815   /* get image with normal size (this might require scaling up) */
816   if (zoom_factor != 1)
817     tmp_bitmap_1 = ZoomBitmap(old_bitmap, width_1, height_1);
818   else
819     tmp_bitmap_1 = old_bitmap;
820
821   if (create_small_bitmaps)
822   {
823     /* calculate new image dimensions for small images */
824     width_2  = width_1  / 2;
825     height_2 = height_1 / 2;
826     width_8  = width_1  / 8;
827     height_8 = height_1 / 8;
828
829     /* get image with 1/2 of normal size (for use in the level editor) */
830     if (zoom_factor != 2)
831       tmp_bitmap_2 = ZoomBitmap(tmp_bitmap_1, width_1 / 2, height_1 / 2);
832     else
833       tmp_bitmap_2 = old_bitmap;
834
835     /* get image with 1/8 of normal size (for use on the preview screen) */
836     if (zoom_factor != 8)
837       tmp_bitmap_8 = ZoomBitmap(tmp_bitmap_1, width_1 / 8, height_1 / 8);
838     else
839       tmp_bitmap_8 = old_bitmap;
840   }
841
842   /* if image was scaled up, create new clipmask for normal size image */
843   if (zoom_factor != 1)
844   {
845 #if defined(TARGET_X11)
846     if (old_bitmap->clip_mask)
847       XFreePixmap(display, old_bitmap->clip_mask);
848
849     old_bitmap->clip_mask =
850       Pixmap_to_Mask(tmp_bitmap_1->drawable, width_1, height_1);
851
852     XSetClipMask(display, old_bitmap->stored_clip_gc, old_bitmap->clip_mask);
853 #else
854     SDL_Surface *tmp_surface_1 = tmp_bitmap_1->surface;
855
856     if (old_bitmap->surface_masked)
857       SDL_FreeSurface(old_bitmap->surface_masked);
858
859     SDL_SetColorKey(tmp_surface_1, SDL_SRCCOLORKEY,
860                     SDL_MapRGB(tmp_surface_1->format, 0x00, 0x00, 0x00));
861     if ((old_bitmap->surface_masked = SDL_DisplayFormat(tmp_surface_1)) ==NULL)
862       Error(ERR_EXIT, "SDL_DisplayFormat() failed");
863     SDL_SetColorKey(tmp_surface_1, 0, 0);       /* reset transparent pixel */
864 #endif
865   }
866
867   if (create_small_bitmaps)
868   {
869     new_width  = width_1;
870     new_height = height_1 + (height_1 + 1) / 2;     /* prevent odd height */
871
872     new_bitmap = CreateBitmap(new_width, new_height, DEFAULT_DEPTH);
873
874     BlitBitmap(tmp_bitmap_1, new_bitmap, 0, 0, width_1, height_1, 0, 0);
875     BlitBitmap(tmp_bitmap_2, new_bitmap, 0, 0, width_1 / 2, height_1 / 2,
876                0, height_1);
877     BlitBitmap(tmp_bitmap_8, new_bitmap, 0, 0, width_1 / 8, height_1 / 8,
878                3 * width_1 / 4, height_1);
879   }
880   else
881   {
882     new_width  = width_1;
883     new_height = height_1;
884
885     new_bitmap = tmp_bitmap_1;  /* directly use tmp_bitmap_1 as new bitmap */
886   }
887
888   if (create_small_bitmaps)
889   {
890     /* if no small bitmaps created, tmp_bitmap_1 is used as new bitmap now */
891     if (zoom_factor != 1)
892       FreeBitmap(tmp_bitmap_1);
893
894     if (zoom_factor != 2)
895       FreeBitmap(tmp_bitmap_2);
896
897     if (zoom_factor != 8)
898       FreeBitmap(tmp_bitmap_8);
899   }
900
901   /* replace image with extended image (containing normal, 1/2 and 1/8 size) */
902 #if defined(TARGET_SDL)
903   swap_bitmap.surface = old_bitmap->surface;
904   old_bitmap->surface = new_bitmap->surface;
905   new_bitmap->surface = swap_bitmap.surface;
906 #else
907   swap_bitmap.drawable = old_bitmap->drawable;
908   old_bitmap->drawable = new_bitmap->drawable;
909   new_bitmap->drawable = swap_bitmap.drawable;
910 #endif
911
912   old_bitmap->width  = new_bitmap->width;
913   old_bitmap->height = new_bitmap->height;
914
915   FreeBitmap(new_bitmap);       /* this actually frees the _old_ bitmap now */
916 }
917
918 void CreateBitmapWithSmallBitmaps(Bitmap *old_bitmap, int zoom_factor)
919 {
920   CreateScaledBitmaps(old_bitmap, zoom_factor, TRUE);
921 }
922
923 void ScaleBitmap(Bitmap *old_bitmap, int zoom_factor)
924 {
925   CreateScaledBitmaps(old_bitmap, zoom_factor, FALSE);
926 }
927
928
929 /* ------------------------------------------------------------------------- */
930 /* mouse pointer functions                                                   */
931 /* ------------------------------------------------------------------------- */
932
933 #if !defined(PLATFORM_MSDOS)
934 /* XPM */
935 static const char *cursor_image_playfield[] =
936 {
937   /* width height num_colors chars_per_pixel */
938   "    16    16        3            1",
939
940   /* colors */
941   "X c #000000",
942   ". c #ffffff",
943   "  c None",
944
945 #if 1
946   /* some people complained about a "white dot" on the screen and thought it
947      was a graphical error... OK, let's just remove the whole pointer :-) */
948
949   /* pixels */
950   "                ",
951   "                ",
952   "                ",
953   "                ",
954   "                ",
955   "                ",
956   "                ",
957   "                ",
958   "                ",
959   "                ",
960   "                ",
961   "                ",
962   "                ",
963   "                ",
964   "                ",
965   "                ",
966
967   /* hot spot */
968   "0,0"
969
970 #else
971
972   /* pixels */
973   " X              ",
974   "X.X             ",
975   " X              ",
976   "                ",
977   "                ",
978   "                ",
979   "                ",
980   "                ",
981   "                ",
982   "                ",
983   "                ",
984   "                ",
985   "                ",
986   "                ",
987   "                ",
988   "                ",
989
990   /* hot spot */
991   "1,1"
992 #endif
993 };
994
995 #if defined(TARGET_SDL)
996 static const int cursor_bit_order = BIT_ORDER_MSB;
997 #elif defined(TARGET_X11_NATIVE)
998 static const int cursor_bit_order = BIT_ORDER_LSB;
999 #endif
1000
1001 static struct MouseCursorInfo *get_cursor_from_image(const char **image)
1002 {
1003   struct MouseCursorInfo *cursor;
1004   boolean bit_order_msb = (cursor_bit_order == BIT_ORDER_MSB);
1005   int header_lines = 4;
1006   int x, y, i;
1007
1008   cursor = checked_calloc(sizeof(struct MouseCursorInfo));
1009
1010   sscanf(image[0], " %d %d ", &cursor->width, &cursor->height);
1011
1012   i = -1;
1013   for (y = 0; y < cursor->width; y++)
1014   {
1015     for (x = 0; x < cursor->height; x++)
1016     {
1017       int bit_nr = x % 8;
1018       int bit_mask = 0x01 << (bit_order_msb ? 7 - bit_nr : bit_nr );
1019
1020       if (bit_nr == 0)
1021       {
1022         i++;
1023         cursor->data[i] = cursor->mask[i] = 0;
1024       }
1025
1026       switch (image[header_lines + y][x])
1027       {
1028         case 'X':
1029           cursor->data[i] |= bit_mask;
1030           cursor->mask[i] |= bit_mask;
1031           break;
1032
1033         case '.':
1034           cursor->mask[i] |= bit_mask;
1035           break;
1036
1037         case ' ':
1038           break;
1039       }
1040     }
1041   }
1042
1043   sscanf(image[header_lines + y], "%d,%d", &cursor->hot_x, &cursor->hot_y);
1044
1045   return cursor;
1046 }
1047 #endif  /* !PLATFORM_MSDOS */
1048
1049 void SetMouseCursor(int mode)
1050 {
1051 #if !defined(PLATFORM_MSDOS)
1052   static struct MouseCursorInfo *cursor_playfield = NULL;
1053
1054   if (cursor_playfield == NULL)
1055     cursor_playfield = get_cursor_from_image(cursor_image_playfield);
1056
1057 #if defined(TARGET_SDL)
1058   SDLSetMouseCursor(mode == CURSOR_PLAYFIELD ? cursor_playfield : NULL);
1059 #elif defined(TARGET_X11_NATIVE)
1060   X11SetMouseCursor(mode == CURSOR_PLAYFIELD ? cursor_playfield : NULL);
1061 #endif
1062 #endif
1063 }
1064
1065
1066 /* ========================================================================= */
1067 /* audio functions                                                           */
1068 /* ========================================================================= */
1069
1070 void OpenAudio(void)
1071 {
1072   /* always start with reliable default values */
1073   audio.sound_available = FALSE;
1074   audio.music_available = FALSE;
1075   audio.loops_available = FALSE;
1076
1077   audio.sound_enabled = FALSE;
1078   audio.sound_deactivated = FALSE;
1079
1080   audio.mixer_pipe[0] = audio.mixer_pipe[1] = 0;
1081   audio.mixer_pid = 0;
1082   audio.device_name = NULL;
1083   audio.device_fd = -1;
1084
1085   audio.num_channels = 0;
1086   audio.music_channel = 0;
1087   audio.first_sound_channel = 0;
1088
1089 #if defined(TARGET_SDL)
1090   SDLOpenAudio();
1091 #elif defined(PLATFORM_UNIX)
1092   UnixOpenAudio();
1093 #elif defined(PLATFORM_MSDOS)
1094   MSDOSOpenAudio();
1095 #endif
1096 }
1097
1098 void CloseAudio(void)
1099 {
1100 #if defined(TARGET_SDL)
1101   SDLCloseAudio();
1102 #elif defined(PLATFORM_UNIX)
1103   UnixCloseAudio();
1104 #elif defined(PLATFORM_MSDOS)
1105   MSDOSCloseAudio();
1106 #endif
1107
1108   audio.sound_enabled = FALSE;
1109 }
1110
1111 void SetAudioMode(boolean enabled)
1112 {
1113   if (!audio.sound_available)
1114     return;
1115
1116   audio.sound_enabled = enabled;
1117 }
1118
1119
1120 /* ========================================================================= */
1121 /* event functions                                                           */
1122 /* ========================================================================= */
1123
1124 void InitEventFilter(EventFilter filter_function)
1125 {
1126 #if defined(TARGET_SDL)
1127   /* set event filter to filter out certain events */
1128   SDL_SetEventFilter(filter_function);
1129 #endif
1130 }
1131
1132 boolean PendingEvent(void)
1133 {
1134 #if defined(TARGET_SDL)
1135   return (SDL_PollEvent(NULL) ? TRUE : FALSE);
1136 #else
1137   return (XPending(display) ? TRUE : FALSE);
1138 #endif
1139 }
1140
1141 void NextEvent(Event *event)
1142 {
1143 #if defined(TARGET_SDL)
1144   SDLNextEvent(event);
1145 #else
1146   XNextEvent(display, event);
1147 #endif
1148 }
1149
1150 void PeekEvent(Event *event)
1151 {
1152 #if defined(TARGET_SDL)
1153   SDL_PeepEvents(event, 1, SDL_PEEKEVENT, SDL_ALLEVENTS);
1154 #else
1155   XPeekEvent(display, event);
1156 #endif
1157 }
1158
1159 Key GetEventKey(KeyEvent *event, boolean with_modifiers)
1160 {
1161 #if defined(TARGET_SDL)
1162
1163 #if 0
1164   printf("unicode == '%d', sym == '%d', mod == '0x%04x'\n",
1165          (int)event->keysym.unicode,
1166          (int)event->keysym.sym,
1167          (int)SDL_GetModState());
1168 #endif
1169
1170   if (with_modifiers &&
1171       event->keysym.unicode > 0x0000 &&
1172       event->keysym.unicode < 0x2000)
1173     return event->keysym.unicode;
1174   else
1175     return event->keysym.sym;
1176
1177 #else
1178
1179 #if 0
1180   printf("with modifiers == '0x%04x', without modifiers == '0x%04x'\n",
1181          (int)XLookupKeysym(event, event->state),
1182          (int)XLookupKeysym(event, 0));
1183 #endif
1184
1185   if (with_modifiers)
1186     return XLookupKeysym(event, event->state);
1187   else
1188     return XLookupKeysym(event, 0);
1189 #endif
1190 }
1191
1192 KeyMod HandleKeyModState(Key key, int key_status)
1193 {
1194   static KeyMod current_modifiers = KMOD_None;
1195
1196 #if !defined(TARGET_SDL)
1197   if (key != KSYM_UNDEFINED)    /* new key => check for modifier key change */
1198   {
1199     KeyMod new_modifier = KMOD_None;
1200
1201     switch(key)
1202     {
1203       case KSYM_Shift_L:
1204         new_modifier = KMOD_Shift_L;
1205         break;
1206       case KSYM_Shift_R:
1207         new_modifier = KMOD_Shift_R;
1208         break;
1209       case KSYM_Control_L:
1210         new_modifier = KMOD_Control_L;
1211         break;
1212       case KSYM_Control_R:
1213         new_modifier = KMOD_Control_R;
1214         break;
1215       case KSYM_Meta_L:
1216         new_modifier = KMOD_Meta_L;
1217         break;
1218       case KSYM_Meta_R:
1219         new_modifier = KMOD_Meta_R;
1220         break;
1221       case KSYM_Alt_L:
1222         new_modifier = KMOD_Alt_L;
1223         break;
1224       case KSYM_Alt_R:
1225         new_modifier = KMOD_Alt_R;
1226         break;
1227       default:
1228         break;
1229     }
1230
1231     if (key_status == KEY_PRESSED)
1232       current_modifiers |= new_modifier;
1233     else
1234       current_modifiers &= ~new_modifier;
1235   }
1236 #endif
1237
1238   return current_modifiers;
1239 }
1240
1241 KeyMod GetKeyModState()
1242 {
1243 #if defined(TARGET_SDL)
1244   return (KeyMod)SDL_GetModState();
1245 #else
1246   return HandleKeyModState(KSYM_UNDEFINED, 0);
1247 #endif
1248 }
1249
1250 boolean CheckCloseWindowEvent(ClientMessageEvent *event)
1251 {
1252   if (event->type != EVENT_CLIENTMESSAGE)
1253     return FALSE;
1254
1255 #if defined(TARGET_SDL)
1256   return TRUE;          /* the only possible message here is SDL_QUIT */
1257 #elif defined(PLATFORM_UNIX)
1258   if ((event->window == window->drawable) &&
1259       (event->data.l[0] == XInternAtom(display, "WM_DELETE_WINDOW", FALSE)))
1260     return TRUE;
1261 #endif
1262
1263   return FALSE;
1264 }
1265
1266
1267 /* ========================================================================= */
1268 /* joystick functions                                                        */
1269 /* ========================================================================= */
1270
1271 void InitJoysticks()
1272 {
1273   int i;
1274
1275 #if defined(NO_JOYSTICK)
1276   return;       /* joysticks generally deactivated by compile-time directive */
1277 #endif
1278
1279   /* always start with reliable default values */
1280   joystick.status = JOYSTICK_NOT_AVAILABLE;
1281   for (i = 0; i < MAX_PLAYERS; i++)
1282     joystick.fd[i] = -1;                /* joystick device closed */
1283
1284 #if defined(TARGET_SDL)
1285   SDLInitJoysticks();
1286 #elif defined(PLATFORM_UNIX)
1287   UnixInitJoysticks();
1288 #elif defined(PLATFORM_MSDOS)
1289   MSDOSInitJoysticks();
1290 #endif
1291
1292 #if 0
1293   for (i = 0; i < MAX_PLAYERS; i++)
1294     printf("::: Joystick for player %d: %d\n", i, joystick.fd[i]);
1295 #endif
1296 }
1297
1298 boolean ReadJoystick(int nr, int *x, int *y, boolean *b1, boolean *b2)
1299 {
1300 #if defined(TARGET_SDL)
1301   return SDLReadJoystick(nr, x, y, b1, b2);
1302 #elif defined(PLATFORM_UNIX)
1303   return UnixReadJoystick(nr, x, y, b1, b2);
1304 #elif defined(PLATFORM_MSDOS)
1305   return MSDOSReadJoystick(nr, x, y, b1, b2);
1306 #endif
1307 }