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