rnd-20020315-1-src
[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 GetPixelFromRGB(Bitmap *bitmap, unsigned int color_r,
442                              unsigned int color_g, unsigned int color_b)
443 {
444   Pixel pixel;
445
446 #if defined(TARGET_SDL)
447   pixel = SDL_MapRGB(bitmap->surface->format, color_r, color_g, color_b);
448 #elif defined(TARGET_ALLEGRO)
449   pixel = AllegroAllocColorCell(color_r << 8, color_g << 8, color_b << 8);
450 #elif defined(TARGET_X11_NATIVE)
451   XColor xcolor;
452
453   xcolor.flags = DoRed | DoGreen | DoBlue;
454   xcolor.red = (color_r << 8);
455   xcolor.green = (color_g << 8);
456   xcolor.blue = (color_b << 8);
457   XAllocColor(display, cmap, &xcolor);
458   pixel = xcolor.pixel;
459 #endif
460
461   return pixel;
462 }
463
464 inline Pixel GetPixelFromRGBcompact(Bitmap *bitmap, unsigned int color)
465 {
466   unsigned int color_r = (color >> 16) & 0xff;
467   unsigned int color_g = (color >>  8) & 0xff;
468   unsigned int color_b = (color >>  0) & 0xff;
469
470   return GetPixelFromRGB(bitmap, color_r, color_g, color_b);
471 }
472
473 /* execute all pending screen drawing operations */
474 inline void FlushDisplay(void)
475 {
476 #ifndef TARGET_SDL
477   XFlush(display);
478 #endif
479 }
480
481 /* execute and wait for all pending screen drawing operations */
482 inline void SyncDisplay(void)
483 {
484 #ifndef TARGET_SDL
485   XSync(display, FALSE);
486 #endif
487 }
488
489 inline void KeyboardAutoRepeatOn(void)
490 {
491 #ifdef TARGET_SDL
492   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY / 2,
493                       SDL_DEFAULT_REPEAT_INTERVAL / 2);
494   SDL_EnableUNICODE(1);
495 #else
496   if (display)
497     XAutoRepeatOn(display);
498 #endif
499 }
500
501 inline void KeyboardAutoRepeatOff(void)
502 {
503 #ifdef TARGET_SDL
504   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
505   SDL_EnableUNICODE(0);
506 #else
507   if (display)
508     XAutoRepeatOff(display);
509 #endif
510 }
511
512 inline boolean PointerInWindow(DrawWindow *window)
513 {
514 #ifdef TARGET_SDL
515   return TRUE;
516 #else
517   Window root, child;
518   int root_x, root_y;
519   unsigned int mask;
520   int win_x, win_y;
521
522   /* if XQueryPointer() returns False, the pointer
523      is not on the same screen as the specified window */
524   return XQueryPointer(display, window->drawable, &root, &child,
525                        &root_x, &root_y, &win_x, &win_y, &mask);
526 #endif
527 }
528
529 inline boolean SetVideoMode(boolean fullscreen)
530 {
531 #ifdef TARGET_SDL
532   return SDLSetVideoMode(&backbuffer, fullscreen);
533 #else
534   boolean success = TRUE;
535
536   if (fullscreen && video.fullscreen_available)
537   {
538     Error(ERR_WARN, "fullscreen not available in X11 version");
539
540     /* display error message only once */
541     video.fullscreen_available = FALSE;
542
543     success = FALSE;
544   }
545
546   return success;
547 #endif
548 }
549
550 inline boolean ChangeVideoModeIfNeeded(boolean fullscreen)
551 {
552 #ifdef TARGET_SDL
553   if ((fullscreen && !video.fullscreen_enabled && video.fullscreen_available)||
554       (!fullscreen && video.fullscreen_enabled))
555     fullscreen = SetVideoMode(fullscreen);
556 #endif
557
558   return fullscreen;
559 }
560
561 Bitmap *LoadImage(char *basename)
562 {
563   Bitmap *new_bitmap;
564   char *filename = getPath3(options.ro_base_directory, GRAPHICS_DIRECTORY,
565                             basename);
566
567 #if defined(TARGET_SDL)
568   new_bitmap = SDLLoadImage(filename);
569 #else
570   new_bitmap = X11LoadImage(filename);
571 #endif
572
573   free(filename);
574
575   return new_bitmap;
576 }
577
578
579 /* ========================================================================= */
580 /* audio functions                                                           */
581 /* ========================================================================= */
582
583 inline void OpenAudio(void)
584 {
585   /* always start with reliable default values */
586   audio.sound_available = FALSE;
587   audio.music_available = FALSE;
588   audio.loops_available = FALSE;
589   audio.mods_available = FALSE;
590   audio.sound_enabled = FALSE;
591
592   audio.soundserver_pipe[0] = audio.soundserver_pipe[1] = 0;
593   audio.soundserver_pid = 0;
594   audio.device_name = NULL;
595   audio.device_fd = 0;
596
597   audio.channels = 0;
598   audio.music_channel = 0;
599   audio.music_nr = 0;
600
601 #if defined(TARGET_SDL)
602   SDLOpenAudio();
603 #elif defined(PLATFORM_MSDOS)
604   MSDOSOpenAudio();
605 #elif defined(PLATFORM_UNIX)
606   UnixOpenAudio();
607 #endif
608 }
609
610 inline void CloseAudio(void)
611 {
612 #if defined(TARGET_SDL)
613   SDLCloseAudio();
614 #elif defined(PLATFORM_MSDOS)
615   MSDOSCloseAudio();
616 #elif defined(PLATFORM_UNIX)
617   UnixCloseAudio();
618 #endif
619
620   audio.sound_enabled = FALSE;
621 }
622
623 inline void SetAudioMode(boolean enabled)
624 {
625   if (!audio.sound_available)
626     return;
627
628   audio.sound_enabled = enabled;
629 }
630
631
632 /* ========================================================================= */
633 /* event functions                                                           */
634 /* ========================================================================= */
635
636 inline void InitEventFilter(EventFilter filter_function)
637 {
638 #ifdef TARGET_SDL
639   /* set event filter to filter out certain events */
640   SDL_SetEventFilter(filter_function);
641 #endif
642 }
643
644 inline boolean PendingEvent(void)
645 {
646 #ifdef TARGET_SDL
647   return (SDL_PollEvent(NULL) ? TRUE : FALSE);
648 #else
649   return (XPending(display) ? TRUE : FALSE);
650 #endif
651 }
652
653 inline void NextEvent(Event *event)
654 {
655 #ifdef TARGET_SDL
656   SDLNextEvent(event);
657 #else
658   XNextEvent(display, event);
659 #endif
660 }
661
662 inline Key GetEventKey(KeyEvent *event, boolean with_modifiers)
663 {
664 #ifdef TARGET_SDL
665 #if 0
666   printf("unicode == '%d', sym == '%d', mod == '0x%04x'\n",
667          (int)event->keysym.unicode,
668          (int)event->keysym.sym,
669          (int)SDL_GetModState());
670 #endif
671
672   if (with_modifiers && event->keysym.unicode != 0)
673     return event->keysym.unicode;
674   else
675     return event->keysym.sym;
676 #else
677 #if 0
678   printf("with modifiers == '0x%04x', without modifiers == '0x%04x'\n",
679          (int)XLookupKeysym(event, event->state),
680          (int)XLookupKeysym(event, 0));
681 #endif
682
683   if (with_modifiers)
684     return XLookupKeysym(event, event->state);
685   else
686     return XLookupKeysym(event, 0);
687 #endif
688 }
689
690 inline boolean CheckCloseWindowEvent(ClientMessageEvent *event)
691 {
692   if (event->type != EVENT_CLIENTMESSAGE)
693     return FALSE;
694
695 #if defined(TARGET_SDL)
696   return TRUE;          /* the only possible message here is SDL_QUIT */
697 #elif defined(PLATFORM_UNIX)
698   if ((event->window == window->drawable) &&
699       (event->data.l[0] == XInternAtom(display, "WM_DELETE_WINDOW", FALSE)))
700     return TRUE;
701 #endif
702
703   return FALSE;
704 }
705
706
707 inline void dummy(void)
708 {
709 #ifdef TARGET_SDL
710 #else
711 #endif
712 }