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