rocksndiamonds-2.0.1
[rocksndiamonds.git] / src / libgame / system.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2001 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 "sound.h"
25 #include "misc.h"
26
27
28 /* ========================================================================= */
29 /* exported variables                                                        */
30 /* ========================================================================= */
31
32 struct ProgramInfo      program;
33 struct OptionInfo       options;
34 struct VideoSystemInfo  video;
35 struct AudioSystemInfo  audio;
36 struct GfxInfo          gfx;
37
38 struct LevelDirInfo    *leveldir_first = NULL;
39 struct LevelDirInfo    *leveldir_current = NULL;
40
41 Display        *display = NULL;
42 Visual         *visual = NULL;
43 int             screen = 0;
44 Colormap        cmap = None;
45
46 DrawWindow     *window = NULL;
47 DrawBuffer     *backbuffer = NULL;
48 DrawBuffer     *drawto = NULL;
49
50 int             button_status = MB_NOT_PRESSED;
51 boolean         motion_status = FALSE;
52
53 int             redraw_mask = REDRAW_NONE;
54 int             redraw_tiles = 0;
55
56 int             FrameCounter = 0;
57
58
59 /* ========================================================================= */
60 /* init/close functions                                                      */
61 /* ========================================================================= */
62
63 void InitCommandName(char *argv0)
64 {
65   program.command_basename =
66     (strrchr(argv0, '/') ? strrchr(argv0, '/') + 1 : argv0);
67 }
68
69 void InitExitFunction(void (*exit_function)(int))
70 {
71   program.exit_function = exit_function;
72
73   /* set signal handlers to custom exit function */
74   signal(SIGINT, exit_function);
75   signal(SIGTERM, exit_function);
76
77 #if defined(TARGET_SDL)
78   /* set exit function to automatically cleanup SDL stuff after exit() */
79   atexit(SDL_Quit);
80 #endif
81 }
82
83 void InitPlatformDependantStuff(void)
84 {
85 #if defined(PLATFORM_MSDOS)
86   _fmode = O_BINARY;
87 #endif
88
89 #if !defined(PLATFORM_UNIX)
90   program.userdata_directory = "userdata";
91   initErrorFile();
92 #endif
93
94 #if defined(TARGET_SDL)
95   if (SDL_Init(SDL_INIT_EVENTTHREAD | SDL_INIT_NOPARACHUTE) < 0)
96     Error(ERR_EXIT, "SDL_Init() failed: %s", SDL_GetError());
97 #endif
98 }
99
100 void ClosePlatformDependantStuff(void)
101 {
102 #if !defined(PLATFORM_UNIX)
103   dumpErrorFile();
104 #endif
105 }
106
107 void InitProgramInfo(char *unix_userdata_directory, char *program_title,
108                      char *window_title, char *icon_title,
109                      char *x11_icon_basename, char *x11_iconmask_basename,
110                      char *msdos_pointer_basename)
111 {
112   char *gfx_dir = getPath2(options.ro_base_directory, GRAPHICS_DIRECTORY);
113   char *x11_icon_filename = getPath2(gfx_dir, x11_icon_basename);
114   char *x11_iconmask_filename = getPath2(gfx_dir, x11_iconmask_basename);
115   char *msdos_pointer_filename = getPath2(gfx_dir, msdos_pointer_basename);
116
117   free(gfx_dir);
118
119 #if defined(PLATFORM_UNIX)
120   program.userdata_directory = unix_userdata_directory;
121 #else
122   program.userdata_directory = "userdata";
123 #endif
124
125   program.program_title = program_title;
126   program.window_title = window_title;
127   program.icon_title = icon_title;
128   program.x11_icon_filename = x11_icon_filename;
129   program.x11_iconmask_filename = x11_iconmask_filename;
130   program.msdos_pointer_filename = msdos_pointer_filename;
131 }
132
133 void InitGfxFieldInfo(int sx, int sy, int sxsize, int sysize,
134                       int real_sx, int real_sy,
135                       int full_sxsize, int full_sysize)
136 {
137   gfx.sx = sx;
138   gfx.sy = sy;
139   gfx.sxsize = sxsize;
140   gfx.sysize = sysize;
141   gfx.real_sx = real_sx;
142   gfx.real_sy = real_sy;
143   gfx.full_sxsize = full_sxsize;
144   gfx.full_sysize = full_sysize;
145 }
146
147 void InitGfxDoor1Info(int dx, int dy, int dxsize, int dysize)
148 {
149   gfx.dx = dx;
150   gfx.dy = dy;
151   gfx.dxsize = dxsize;
152   gfx.dysize = dysize;
153 }
154
155 void InitGfxDoor2Info(int vx, int vy, int vxsize, int vysize)
156 {
157   gfx.vx = vx;
158   gfx.vy = vy;
159   gfx.vxsize = vxsize;
160   gfx.vysize = vysize;
161 }
162
163 void InitGfxScrollbufferInfo(int scrollbuffer_width, int scrollbuffer_height)
164 {
165   /* currently only used by MSDOS code to alloc VRAM buffer, if available */
166   gfx.scrollbuffer_width = scrollbuffer_width;
167   gfx.scrollbuffer_height = scrollbuffer_height;
168 }
169
170
171 /* ========================================================================= */
172 /* video functions                                                           */
173 /* ========================================================================= */
174
175 inline static int GetRealDepth(int depth)
176 {
177   return (depth == DEFAULT_DEPTH ? video.default_depth : depth);
178 }
179
180 inline void InitVideoDisplay(void)
181 {
182 #if defined(TARGET_SDL)
183   SDLInitVideoDisplay();
184 #else
185   X11InitVideoDisplay();
186 #endif
187 }
188
189 inline void CloseVideoDisplay(void)
190 {
191   KeyboardAutoRepeatOn();
192
193 #if defined(TARGET_SDL)
194   SDL_QuitSubSystem(SDL_INIT_VIDEO);
195 #else
196   if (display)
197     XCloseDisplay(display);
198 #endif
199 }
200
201 inline void InitVideoBuffer(DrawBuffer **backbuffer, DrawWindow **window,
202                             int width, int height, int depth,
203                             boolean fullscreen)
204 {
205   video.width = width;
206   video.height = height;
207   video.depth = GetRealDepth(depth);
208   video.fullscreen_available = FULLSCREEN_STATUS;
209   video.fullscreen_enabled = FALSE;
210
211 #ifdef TARGET_SDL
212   SDLInitVideoBuffer(backbuffer, window, fullscreen);
213 #else
214   X11InitVideoBuffer(backbuffer, window);
215 #endif
216 }
217
218 inline Bitmap *CreateBitmapStruct(void)
219 {
220 #ifdef TARGET_SDL
221   return checked_calloc(sizeof(struct SDLSurfaceInfo));
222 #else
223   return checked_calloc(sizeof(struct X11DrawableInfo));
224 #endif
225 }
226
227 inline Bitmap *CreateBitmap(int width, int height, int depth)
228 {
229   Bitmap *new_bitmap = CreateBitmapStruct();
230   int real_depth = GetRealDepth(depth);
231
232 #ifdef TARGET_SDL
233   SDL_Surface *surface_tmp, *surface_native;
234
235   if ((surface_tmp = SDL_CreateRGBSurface(SURFACE_FLAGS, width, height,
236                                           real_depth, 0, 0, 0, 0))
237       == NULL)
238     Error(ERR_EXIT, "SDL_CreateRGBSurface() failed: %s", SDL_GetError());
239
240   if ((surface_native = SDL_DisplayFormat(surface_tmp)) == NULL)
241     Error(ERR_EXIT, "SDL_DisplayFormat() failed: %s", SDL_GetError());
242
243   SDL_FreeSurface(surface_tmp);
244
245   new_bitmap->surface = surface_native;
246 #else
247   Pixmap pixmap;
248
249   if ((pixmap = XCreatePixmap(display, window->drawable,
250                               width, height, real_depth))
251       == None)
252     Error(ERR_EXIT, "cannot create pixmap");
253
254   new_bitmap->drawable = pixmap;
255
256   if (window == NULL)
257     Error(ERR_EXIT, "Window GC needed for Bitmap -- create Window first");
258
259   new_bitmap->gc = window->gc;
260
261   new_bitmap->line_gc[0] = window->line_gc[0];
262   new_bitmap->line_gc[1] = window->line_gc[1];
263 #endif
264
265   return new_bitmap;
266 }
267
268 inline void FreeBitmap(Bitmap *bitmap)
269 {
270   if (bitmap == NULL)
271     return;
272
273 #ifdef TARGET_SDL
274   if (bitmap->surface)
275     SDL_FreeSurface(bitmap->surface);
276   if (bitmap->surface_masked)
277     SDL_FreeSurface(bitmap->surface_masked);
278 #else
279   if (bitmap->drawable)
280     XFreePixmap(display, bitmap->drawable);
281   if (bitmap->clip_mask)
282     XFreePixmap(display, bitmap->clip_mask);
283   if (bitmap->stored_clip_gc)
284     XFreeGC(display, bitmap->stored_clip_gc);
285 #endif
286
287   free(bitmap);
288 }
289
290 inline void CloseWindow(DrawWindow *window)
291 {
292 #ifdef TARGET_X11
293   if (window->drawable)
294   {
295     XUnmapWindow(display, window->drawable);
296     XDestroyWindow(display, window->drawable);
297   }
298   if (window->gc)
299     XFreeGC(display, window->gc);
300 #endif
301 }
302
303 inline void BlitBitmap(Bitmap *src_bitmap, Bitmap *dst_bitmap,
304                        int src_x, int src_y,
305                        int width, int height,
306                        int dst_x, int dst_y)
307 {
308 #ifdef TARGET_SDL
309   SDLCopyArea(src_bitmap, dst_bitmap,
310               src_x, src_y, width, height, dst_x, dst_y, SDLCOPYAREA_OPAQUE);
311 #else
312   XCopyArea(display, src_bitmap->drawable, dst_bitmap->drawable,
313             dst_bitmap->gc, src_x, src_y, width, height, dst_x, dst_y);
314 #endif
315 }
316
317 inline void ClearRectangle(Bitmap *bitmap, int x, int y, int width, int height)
318 {
319 #ifdef TARGET_SDL
320   SDLFillRectangle(bitmap, x, y, width, height, 0x000000);
321 #else
322   XFillRectangle(display, bitmap->drawable, bitmap->gc, x, y, width, height);
323 #endif
324 }
325
326 #if 0
327 #ifndef TARGET_SDL
328 static GC last_clip_gc = 0;     /* needed for XCopyArea() through clip mask */
329 #endif
330 #endif
331
332 inline void SetClipMask(Bitmap *bitmap, GC clip_gc, Pixmap clip_pixmap)
333 {
334 #ifdef TARGET_X11
335   if (clip_gc)
336   {
337     bitmap->clip_gc = clip_gc;
338     XSetClipMask(display, bitmap->clip_gc, clip_pixmap);
339   }
340 #if 0
341   last_clip_gc = clip_gc;
342 #endif
343 #endif
344 }
345
346 inline void SetClipOrigin(Bitmap *bitmap, GC clip_gc, int clip_x, int clip_y)
347 {
348 #ifdef TARGET_X11
349   if (clip_gc)
350   {
351     bitmap->clip_gc = clip_gc;
352     XSetClipOrigin(display, bitmap->clip_gc, clip_x, clip_y);
353   }
354 #if 0
355   last_clip_gc = clip_gc;
356 #endif
357 #endif
358 }
359
360 inline void BlitBitmapMasked(Bitmap *src_bitmap, Bitmap *dst_bitmap,
361                              int src_x, int src_y,
362                              int width, int height,
363                              int dst_x, int dst_y)
364 {
365 #ifdef TARGET_SDL
366   SDLCopyArea(src_bitmap, dst_bitmap,
367               src_x, src_y, width, height, dst_x, dst_y, SDLCOPYAREA_MASKED);
368 #else
369   XCopyArea(display, src_bitmap->drawable, dst_bitmap->drawable,
370             src_bitmap->clip_gc, src_x, src_y, width, height, dst_x, dst_y);
371 #endif
372 }
373
374 inline void DrawSimpleWhiteLine(Bitmap *bitmap, int from_x, int from_y,
375                                 int to_x, int to_y)
376 {
377 #ifdef TARGET_SDL
378   SDLDrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, 0xffffff);
379 #else
380   XSetForeground(display, bitmap->gc, WhitePixel(display, screen));
381   XDrawLine(display, bitmap->drawable, bitmap->gc, from_x, from_y, to_x, to_y);
382   XSetForeground(display, bitmap->gc, BlackPixel(display, screen));
383 #endif
384 }
385
386 #if !defined(TARGET_X11_NATIVE)
387 inline void DrawLine(Bitmap *bitmap, int from_x, int from_y,
388                      int to_x, int to_y, Pixel pixel, int line_width)
389 {
390   int x, y;
391
392   for (x=0; x<line_width; x++)
393   {
394     for (y=0; y<line_width; y++)
395     {
396       int dx = x - line_width / 2;
397       int dy = y - line_width / 2;
398
399       if ((x == 0 && y == 0) ||
400           (x == 0 && y == line_width - 1) ||
401           (x == line_width - 1 && y == 0) ||
402           (x == line_width - 1 && y == line_width - 1))
403         continue;
404
405 #if defined(TARGET_SDL)
406       SDLDrawLine(bitmap,
407                   from_x + dx, from_y + dy, to_x + dx, to_y + dy, pixel);
408 #elif defined(TARGET_ALLEGRO)
409       AllegroDrawLine(bitmap->drawable, from_x + dx, from_y + dy,
410                       to_x + dx, to_y + dy, pixel);
411 #endif
412     }
413   }
414 }
415 #endif
416
417 inline void DrawLines(Bitmap *bitmap, struct XY *points, int num_points,
418                       Pixel pixel)
419 {
420 #if !defined(TARGET_X11_NATIVE)
421   int line_width = 4;
422   int i;
423
424   for (i=0; i<num_points - 1; i++)
425     DrawLine(bitmap, points[i].x, points[i].y,
426              points[i + 1].x, points[i + 1].y, pixel, line_width);
427
428   /*
429   SDLDrawLines(bitmap->surface, points, num_points, pixel);
430   */
431 #else
432   XSetForeground(display, bitmap->line_gc[1], pixel);
433   XDrawLines(display, bitmap->drawable, bitmap->line_gc[1],
434              (XPoint *)points, num_points, CoordModeOrigin);
435   /*
436   XSetForeground(display, gc, BlackPixel(display, screen));
437   */
438 #endif
439 }
440
441 inline Pixel GetPixel(Bitmap *bitmap, int x, int y)
442 {
443 #if defined(TARGET_SDL)
444   return SDLGetPixel(bitmap, x, y);
445 #elif defined(TARGET_ALLEGRO)
446   return AllegroGetPixel(bitmap->drawable, x, y);
447 #else
448   unsigned long pixel_value;
449   XImage *pixel_image;
450
451   pixel_image = XGetImage(display, bitmap->drawable, x, y, 1, 1,
452                           AllPlanes, ZPixmap);
453   pixel_value = XGetPixel(pixel_image, 0, 0);
454
455   XDestroyImage(pixel_image);
456
457   return pixel_value;
458 #endif
459 }
460
461 inline Pixel GetPixelFromRGB(Bitmap *bitmap, unsigned int color_r,
462                              unsigned int color_g, unsigned int color_b)
463 {
464   Pixel pixel;
465
466 #if defined(TARGET_SDL)
467   pixel = SDL_MapRGB(bitmap->surface->format, color_r, color_g, color_b);
468 #elif defined(TARGET_ALLEGRO)
469   pixel = AllegroAllocColorCell(color_r << 8, color_g << 8, color_b << 8);
470 #elif defined(TARGET_X11_NATIVE)
471   XColor xcolor;
472
473   xcolor.flags = DoRed | DoGreen | DoBlue;
474   xcolor.red = (color_r << 8);
475   xcolor.green = (color_g << 8);
476   xcolor.blue = (color_b << 8);
477   XAllocColor(display, cmap, &xcolor);
478   pixel = xcolor.pixel;
479 #endif
480
481   return pixel;
482 }
483
484 inline Pixel GetPixelFromRGBcompact(Bitmap *bitmap, unsigned int color)
485 {
486   unsigned int color_r = (color >> 16) & 0xff;
487   unsigned int color_g = (color >>  8) & 0xff;
488   unsigned int color_b = (color >>  0) & 0xff;
489
490   return GetPixelFromRGB(bitmap, color_r, color_g, color_b);
491 }
492
493 /* execute all pending screen drawing operations */
494 inline void FlushDisplay(void)
495 {
496 #ifndef TARGET_SDL
497   XFlush(display);
498 #endif
499 }
500
501 /* execute and wait for all pending screen drawing operations */
502 inline void SyncDisplay(void)
503 {
504 #ifndef TARGET_SDL
505   XSync(display, FALSE);
506 #endif
507 }
508
509 inline void KeyboardAutoRepeatOn(void)
510 {
511 #ifdef TARGET_SDL
512   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY / 2,
513                       SDL_DEFAULT_REPEAT_INTERVAL / 2);
514   SDL_EnableUNICODE(1);
515 #else
516   if (display)
517     XAutoRepeatOn(display);
518 #endif
519 }
520
521 inline void KeyboardAutoRepeatOff(void)
522 {
523 #ifdef TARGET_SDL
524   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
525   SDL_EnableUNICODE(0);
526 #else
527   if (display)
528     XAutoRepeatOff(display);
529 #endif
530 }
531
532 inline boolean PointerInWindow(DrawWindow *window)
533 {
534 #ifdef TARGET_SDL
535   return TRUE;
536 #else
537   Window root, child;
538   int root_x, root_y;
539   unsigned int mask;
540   int win_x, win_y;
541
542   /* if XQueryPointer() returns False, the pointer
543      is not on the same screen as the specified window */
544   return XQueryPointer(display, window->drawable, &root, &child,
545                        &root_x, &root_y, &win_x, &win_y, &mask);
546 #endif
547 }
548
549 inline boolean SetVideoMode(boolean fullscreen)
550 {
551 #ifdef TARGET_SDL
552   return SDLSetVideoMode(&backbuffer, fullscreen);
553 #else
554   boolean success = TRUE;
555
556   if (fullscreen && video.fullscreen_available)
557   {
558     Error(ERR_WARN, "fullscreen not available in X11 version");
559
560     /* display error message only once */
561     video.fullscreen_available = FALSE;
562
563     success = FALSE;
564   }
565
566   return success;
567 #endif
568 }
569
570 inline boolean ChangeVideoModeIfNeeded(boolean fullscreen)
571 {
572 #ifdef TARGET_SDL
573   if ((fullscreen && !video.fullscreen_enabled && video.fullscreen_available)||
574       (!fullscreen && video.fullscreen_enabled))
575     fullscreen = SetVideoMode(fullscreen);
576 #endif
577
578   return fullscreen;
579 }
580
581 Bitmap *LoadImage(char *basename)
582 {
583   Bitmap *new_bitmap;
584   char *filename = getPath3(options.ro_base_directory, GRAPHICS_DIRECTORY,
585                             basename);
586
587 #if defined(TARGET_SDL)
588   new_bitmap = SDLLoadImage(filename);
589 #else
590   new_bitmap = X11LoadImage(filename);
591 #endif
592
593   free(filename);
594
595   return new_bitmap;
596 }
597
598
599 /* ========================================================================= */
600 /* audio functions                                                           */
601 /* ========================================================================= */
602
603 inline void OpenAudio(void)
604 {
605   /* always start with reliable default values */
606   audio.sound_available = FALSE;
607   audio.music_available = FALSE;
608   audio.loops_available = FALSE;
609   audio.mods_available = FALSE;
610   audio.sound_enabled = FALSE;
611
612   audio.soundserver_pipe[0] = audio.soundserver_pipe[1] = 0;
613   audio.soundserver_pid = 0;
614   audio.device_name = NULL;
615   audio.device_fd = 0;
616
617   audio.channels = 0;
618   audio.music_channel = 0;
619   audio.music_nr = 0;
620
621 #if defined(TARGET_SDL)
622   SDLOpenAudio();
623 #elif defined(PLATFORM_MSDOS)
624   MSDOSOpenAudio();
625 #elif defined(PLATFORM_UNIX)
626   UnixOpenAudio();
627 #endif
628 }
629
630 inline void CloseAudio(void)
631 {
632 #if defined(TARGET_SDL)
633   SDLCloseAudio();
634 #elif defined(PLATFORM_MSDOS)
635   MSDOSCloseAudio();
636 #elif defined(PLATFORM_UNIX)
637   UnixCloseAudio();
638 #endif
639
640   audio.sound_enabled = FALSE;
641 }
642
643 inline void SetAudioMode(boolean enabled)
644 {
645   if (!audio.sound_available)
646     return;
647
648   audio.sound_enabled = enabled;
649 }
650
651
652 /* ========================================================================= */
653 /* event functions                                                           */
654 /* ========================================================================= */
655
656 inline void InitEventFilter(EventFilter filter_function)
657 {
658 #ifdef TARGET_SDL
659   /* set event filter to filter out certain events */
660   SDL_SetEventFilter(filter_function);
661 #endif
662 }
663
664 inline boolean PendingEvent(void)
665 {
666 #ifdef TARGET_SDL
667   return (SDL_PollEvent(NULL) ? TRUE : FALSE);
668 #else
669   return (XPending(display) ? TRUE : FALSE);
670 #endif
671 }
672
673 inline void NextEvent(Event *event)
674 {
675 #ifdef TARGET_SDL
676   SDLNextEvent(event);
677 #else
678   XNextEvent(display, event);
679 #endif
680 }
681
682 inline Key GetEventKey(KeyEvent *event, boolean with_modifiers)
683 {
684 #ifdef TARGET_SDL
685 #if 0
686   printf("unicode == '%d', sym == '%d', mod == '0x%04x'\n",
687          (int)event->keysym.unicode,
688          (int)event->keysym.sym,
689          (int)SDL_GetModState());
690 #endif
691
692   if (with_modifiers && event->keysym.unicode != 0)
693     return event->keysym.unicode;
694   else
695     return event->keysym.sym;
696 #else
697 #if 0
698   printf("with modifiers == '0x%04x', without modifiers == '0x%04x'\n",
699          (int)XLookupKeysym(event, event->state),
700          (int)XLookupKeysym(event, 0));
701 #endif
702
703   if (with_modifiers)
704     return XLookupKeysym(event, event->state);
705   else
706     return XLookupKeysym(event, 0);
707 #endif
708 }
709
710 inline boolean CheckCloseWindowEvent(ClientMessageEvent *event)
711 {
712   if (event->type != EVENT_CLIENTMESSAGE)
713     return FALSE;
714
715 #if defined(TARGET_SDL)
716   return TRUE;          /* the only possible message here is SDL_QUIT */
717 #elif defined(PLATFORM_UNIX)
718   if ((event->window == window->drawable) &&
719       (event->data.l[0] == XInternAtom(display, "WM_DELETE_WINDOW", FALSE)))
720     return TRUE;
721 #endif
722
723   return FALSE;
724 }
725
726
727 inline void dummy(void)
728 {
729 #ifdef TARGET_SDL
730 #else
731 #endif
732 }