bfc6d454d9652253e9766676960913783c469a9c
[rocksndiamonds.git] / src / libgame / misc.c
1 /***********************************************************
2 *  Rocks'n'Diamonds -- McDuffin Strikes Back!              *
3 *----------------------------------------------------------*
4 *  (c) 1995-98 Artsoft Entertainment                       *
5 *              Holger Schemel                              *
6 *              Oststrasse 11a                              *
7 *              33604 Bielefeld                             *
8 *              phone: ++49 +521 290471                     *
9 *              email: aeglos@valinor.owl.de                *
10 *----------------------------------------------------------*
11 *  misc.c                                                  *
12 ***********************************************************/
13
14 #include <time.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <stdarg.h>
18 #include <ctype.h>
19
20 #if !defined(PLATFORM_WIN32)
21 #include <pwd.h>
22 #include <sys/param.h>
23 #endif
24
25 #include "libgame.h"
26
27 #include "main_TMP.h"
28
29 #include "misc.h"
30
31 #include "joystick_TMP.h"
32
33 #if defined(PLATFORM_MSDOS)
34 volatile unsigned long counter = 0;
35
36 void increment_counter()
37 {
38   counter++;
39 }
40
41 END_OF_FUNCTION(increment_counter);
42 #endif
43
44
45 /* maximal allowed length of a command line option */
46 #define MAX_OPTION_LEN          256
47
48 #ifdef TARGET_SDL
49 static unsigned long mainCounter(int mode)
50 {
51   static unsigned long base_ms = 0;
52   unsigned long current_ms;
53   unsigned long counter_ms;
54
55   current_ms = SDL_GetTicks();
56
57   /* reset base time in case of counter initializing or wrap-around */
58   if (mode == INIT_COUNTER || current_ms < base_ms)
59     base_ms = current_ms;
60
61   counter_ms = current_ms - base_ms;
62
63   return counter_ms;            /* return milliseconds since last init */
64 }
65
66 #else /* !TARGET_SDL */
67
68 #if defined(PLATFORM_UNIX)
69 static unsigned long mainCounter(int mode)
70 {
71   static struct timeval base_time = { 0, 0 };
72   struct timeval current_time;
73   unsigned long counter_ms;
74
75   gettimeofday(&current_time, NULL);
76
77   /* reset base time in case of counter initializing or wrap-around */
78   if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
79     base_time = current_time;
80
81   counter_ms = (current_time.tv_sec  - base_time.tv_sec)  * 1000
82              + (current_time.tv_usec - base_time.tv_usec) / 1000;
83
84   return counter_ms;            /* return milliseconds since last init */
85 }
86 #endif /* PLATFORM_UNIX */
87 #endif /* !TARGET_SDL */
88
89 void InitCounter()              /* set counter back to zero */
90 {
91 #if !defined(PLATFORM_MSDOS)
92   mainCounter(INIT_COUNTER);
93 #else
94   LOCK_VARIABLE(counter);
95   LOCK_FUNCTION(increment_counter);
96   install_int_ex(increment_counter, BPS_TO_TIMER(100));
97 #endif
98 }
99
100 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
101 {
102 #if !defined(PLATFORM_MSDOS)
103   return mainCounter(READ_COUNTER);
104 #else
105   return (counter * 10);
106 #endif
107 }
108
109 static void sleep_milliseconds(unsigned long milliseconds_delay)
110 {
111   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
112
113 #if defined(PLATFORM_MSDOS)
114   /* don't use select() to perform waiting operations under DOS/Windows
115      environment; always use a busy loop for waiting instead */
116   do_busy_waiting = TRUE;
117 #endif
118
119   if (do_busy_waiting)
120   {
121     /* we want to wait only a few ms -- if we assume that we have a
122        kernel timer resolution of 10 ms, we would wait far to long;
123        therefore it's better to do a short interval of busy waiting
124        to get our sleeping time more accurate */
125
126     unsigned long base_counter = Counter(), actual_counter = Counter();
127
128     while (actual_counter < base_counter + milliseconds_delay &&
129            actual_counter >= base_counter)
130       actual_counter = Counter();
131   }
132   else
133   {
134 #if defined(TARGET_SDL)
135     SDL_Delay(milliseconds_delay);
136 #else
137     struct timeval delay;
138
139     delay.tv_sec  = milliseconds_delay / 1000;
140     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
141
142     if (select(0, NULL, NULL, NULL, &delay) != 0)
143       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
144 #endif
145   }
146 }
147
148 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
149 {
150   sleep_milliseconds(delay);
151 }
152
153 boolean FrameReached(unsigned long *frame_counter_var,
154                      unsigned long frame_delay)
155 {
156   unsigned long actual_frame_counter = FrameCounter;
157
158   if (actual_frame_counter < *frame_counter_var+frame_delay &&
159       actual_frame_counter >= *frame_counter_var)
160     return(FALSE);
161
162   *frame_counter_var = actual_frame_counter;
163   return(TRUE);
164 }
165
166 boolean DelayReached(unsigned long *counter_var,
167                      unsigned long delay)
168 {
169   unsigned long actual_counter = Counter();
170
171   if (actual_counter < *counter_var + delay &&
172       actual_counter >= *counter_var)
173     return(FALSE);
174
175   *counter_var = actual_counter;
176   return(TRUE);
177 }
178
179 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
180 {
181   unsigned long actual_counter;
182
183   while(1)
184   {
185     actual_counter = Counter();
186
187     if (actual_counter < *counter_var + delay &&
188         actual_counter >= *counter_var)
189       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
190     else
191       break;
192   }
193
194   *counter_var = actual_counter;
195 }
196
197 /* int2str() returns a number converted to a string;
198    the used memory is static, but will be overwritten by later calls,
199    so if you want to save the result, copy it to a private string buffer;
200    there can be 10 local calls of int2str() without buffering the result --
201    the 11th call will then destroy the result from the first call and so on.
202 */
203
204 char *int2str(int number, int size)
205 {
206   static char shift_array[10][40];
207   static int shift_counter = 0;
208   char *s = shift_array[shift_counter];
209
210   shift_counter = (shift_counter + 1) % 10;
211
212   if (size > 20)
213     size = 20;
214
215   if (size)
216   {
217     sprintf(s, "                    %09d", number);
218     return &s[strlen(s) - size];
219   }
220   else
221   {
222     sprintf(s, "%d", number);
223     return s;
224   }
225 }
226
227 unsigned int SimpleRND(unsigned int max)
228 {
229 #if defined(TARGET_SDL)
230   static unsigned long root = 654321;
231   unsigned long current_ms;
232
233   current_ms = SDL_GetTicks();
234   root = root * 4253261 + current_ms;
235   return (root % max);
236 #else
237   static unsigned long root = 654321;
238   struct timeval current_time;
239
240   gettimeofday(&current_time, NULL);
241   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
242   return (root % max);
243 #endif
244 }
245
246 #ifdef DEBUG
247 static unsigned int last_RND_value = 0;
248
249 unsigned int last_RND()
250 {
251   return last_RND_value;
252 }
253 #endif
254
255 unsigned int RND(unsigned int max)
256 {
257 #ifdef DEBUG
258   return (last_RND_value = random_linux_libc() % max);
259 #else
260   return (random_linux_libc() % max);
261 #endif
262 }
263
264 unsigned int InitRND(long seed)
265 {
266 #if defined(TARGET_SDL)
267   unsigned long current_ms;
268
269   if (seed == NEW_RANDOMIZE)
270   {
271     current_ms = SDL_GetTicks();
272     srandom_linux_libc((unsigned int) current_ms);
273     return (unsigned int) current_ms;
274   }
275   else
276   {
277     srandom_linux_libc((unsigned int) seed);
278     return (unsigned int) seed;
279   }
280 #else
281   struct timeval current_time;
282
283   if (seed == NEW_RANDOMIZE)
284   {
285     gettimeofday(&current_time, NULL);
286     srandom_linux_libc((unsigned int) current_time.tv_usec);
287     return (unsigned int) current_time.tv_usec;
288   }
289   else
290   {
291     srandom_linux_libc((unsigned int) seed);
292     return (unsigned int) seed;
293   }
294 #endif
295 }
296
297 char *getLoginName()
298 {
299 #if defined(PLATFORM_WIN32)
300   return ANONYMOUS_NAME;
301 #else
302   struct passwd *pwd;
303
304   if ((pwd = getpwuid(getuid())) == NULL)
305     return ANONYMOUS_NAME;
306   else
307     return pwd->pw_name;
308 #endif
309 }
310
311 char *getRealName()
312 {
313 #if defined(PLATFORM_UNIX)
314   struct passwd *pwd;
315
316   if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
317     return ANONYMOUS_NAME;
318   else
319   {
320     static char real_name[1024];
321     char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
322
323     if (strchr(pwd->pw_gecos, 'ß') == NULL)
324       return pwd->pw_gecos;
325
326     /* the user's real name contains a 'ß' character (german sharp s),
327        which has no equivalent in upper case letters (which our fonts use) */
328     while (*from_ptr != '\0' && (long)(to_ptr - real_name) < 1024 - 2)
329     {
330       if (*from_ptr != 'ß')
331         *to_ptr++ = *from_ptr++;
332       else
333       {
334         from_ptr++;
335         *to_ptr++ = 's';
336         *to_ptr++ = 's';
337       }
338     }
339     *to_ptr = '\0';
340
341     return real_name;
342   }
343 #else /* !PLATFORM_UNIX */
344   return ANONYMOUS_NAME;
345 #endif
346 }
347
348 char *getHomeDir()
349 {
350 #if defined(PLATFORM_UNIX)
351   static char *home_dir = NULL;
352
353   if (!home_dir)
354   {
355     if (!(home_dir = getenv("HOME")))
356     {
357       struct passwd *pwd;
358
359       if ((pwd = getpwuid(getuid())))
360         home_dir = pwd->pw_dir;
361       else
362         home_dir = ".";
363     }
364   }
365
366   return home_dir;
367 #else
368   return ".";
369 #endif
370 }
371
372 char *getPath2(char *path1, char *path2)
373 {
374   char *complete_path = checked_malloc(strlen(path1) + 1 +
375                                        strlen(path2) + 1);
376
377   sprintf(complete_path, "%s/%s", path1, path2);
378   return complete_path;
379 }
380
381 char *getPath3(char *path1, char *path2, char *path3)
382 {
383   char *complete_path = checked_malloc(strlen(path1) + 1 +
384                                        strlen(path2) + 1 +
385                                        strlen(path3) + 1);
386
387   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
388   return complete_path;
389 }
390
391 char *getStringCopy(char *s)
392 {
393   char *s_copy;
394
395   if (s == NULL)
396     return NULL;
397
398   s_copy = checked_malloc(strlen(s) + 1);
399
400   strcpy(s_copy, s);
401   return s_copy;
402 }
403
404 char *getStringToLower(char *s)
405 {
406   char *s_copy = checked_malloc(strlen(s) + 1);
407   char *s_ptr = s_copy;
408
409   while (*s)
410     *s_ptr++ = tolower(*s++);
411   *s_ptr = '\0';
412
413   return s_copy;
414 }
415
416 void MarkTileDirty(int x, int y)
417 {
418   int xx = redraw_x1 + x;
419   int yy = redraw_y1 + y;
420
421   if (!redraw[xx][yy])
422     redraw_tiles++;
423
424   redraw[xx][yy] = TRUE;
425   redraw_mask |= REDRAW_TILES;
426 }
427
428 void SetBorderElement()
429 {
430   int x, y;
431
432   BorderElement = EL_LEERRAUM;
433
434   for(y=0; y<lev_fieldy && BorderElement == EL_LEERRAUM; y++)
435   {
436     for(x=0; x<lev_fieldx; x++)
437     {
438       if (!IS_MASSIVE(Feld[x][y]))
439         BorderElement = EL_BETON;
440
441       if (y != 0 && y != lev_fieldy - 1 && x != lev_fieldx - 1)
442         x = lev_fieldx - 2;
443     }
444   }
445 }
446
447 void GetOptions(char *argv[])
448 {
449   char **options_left = &argv[1];
450
451   /* initialize global program options */
452   options.display_name = NULL;
453   options.server_host = NULL;
454   options.server_port = 0;
455   options.ro_base_directory = RO_BASE_PATH;
456   options.rw_base_directory = RW_BASE_PATH;
457   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
458   options.serveronly = FALSE;
459   options.network = FALSE;
460   options.verbose = FALSE;
461   options.debug = FALSE;
462
463   /* initialize some more global variables */
464   global.frames_per_second = 0;
465   global.fps_slowdown = FALSE;
466   global.fps_slowdown_factor = 1;
467
468   while (*options_left)
469   {
470     char option_str[MAX_OPTION_LEN];
471     char *option = options_left[0];
472     char *next_option = options_left[1];
473     char *option_arg = NULL;
474     int option_len = strlen(option);
475
476     if (option_len >= MAX_OPTION_LEN)
477       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
478
479     strcpy(option_str, option);                 /* copy argument into buffer */
480     option = option_str;
481
482     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
483       break;
484
485     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
486       option++;
487
488     option_arg = strchr(option, '=');
489     if (option_arg == NULL)                     /* no '=' in option */
490       option_arg = next_option;
491     else
492     {
493       *option_arg++ = '\0';                     /* cut argument from option */
494       if (*option_arg == '\0')                  /* no argument after '=' */
495         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
496     }
497
498     option_len = strlen(option);
499
500     if (strcmp(option, "-") == 0)
501       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
502     else if (strncmp(option, "-help", option_len) == 0)
503     {
504       printf("Usage: %s [options] [server.name [port]]\n"
505              "Options:\n"
506              "  -d, --display machine:0       X server display\n"
507              "  -b, --basepath directory      alternative base directory\n"
508              "  -l, --level directory         alternative level directory\n"
509              "  -s, --serveronly              only start network server\n"
510              "  -n, --network                 network multiplayer game\n"
511              "  -v, --verbose                 verbose mode\n",
512              program_name);
513       exit(0);
514     }
515     else if (strncmp(option, "-display", option_len) == 0)
516     {
517       if (option_arg == NULL)
518         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
519
520       options.display_name = option_arg;
521       if (option_arg == next_option)
522         options_left++;
523     }
524     else if (strncmp(option, "-basepath", option_len) == 0)
525     {
526       if (option_arg == NULL)
527         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
528
529       /* this should be extended to separate options for ro and rw data */
530       options.ro_base_directory = option_arg;
531       options.rw_base_directory = option_arg;
532       if (option_arg == next_option)
533         options_left++;
534
535       /* adjust path for level directory accordingly */
536       options.level_directory =
537         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
538     }
539     else if (strncmp(option, "-levels", option_len) == 0)
540     {
541       if (option_arg == NULL)
542         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
543
544       options.level_directory = option_arg;
545       if (option_arg == next_option)
546         options_left++;
547     }
548     else if (strncmp(option, "-network", option_len) == 0)
549     {
550       options.network = TRUE;
551     }
552     else if (strncmp(option, "-serveronly", option_len) == 0)
553     {
554       options.serveronly = TRUE;
555     }
556     else if (strncmp(option, "-verbose", option_len) == 0)
557     {
558       options.verbose = TRUE;
559     }
560     else if (strncmp(option, "-debug", option_len) == 0)
561     {
562       options.debug = TRUE;
563     }
564     else if (*option == '-')
565     {
566       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
567     }
568     else if (options.server_host == NULL)
569     {
570       options.server_host = *options_left;
571     }
572     else if (options.server_port == 0)
573     {
574       options.server_port = atoi(*options_left);
575       if (options.server_port < 1024)
576         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
577     }
578     else
579       Error(ERR_EXIT_HELP, "too many arguments");
580
581     options_left++;
582   }
583 }
584
585 void Error(int mode, char *format, ...)
586 {
587   char *process_name = "";
588   FILE *error = stderr;
589
590   /* display warnings only when running in verbose mode */
591   if (mode & ERR_WARN && !options.verbose)
592     return;
593
594 #if !defined(PLATFORM_UNIX)
595   if ((error = openErrorFile()) == NULL)
596   {
597     printf("Cannot write to error output file!\n");
598     CloseAllAndExit(1);
599   }
600 #endif
601
602   if (mode & ERR_SOUND_SERVER)
603     process_name = " sound server";
604   else if (mode & ERR_NETWORK_SERVER)
605     process_name = " network server";
606   else if (mode & ERR_NETWORK_CLIENT)
607     process_name = " network client **";
608
609   if (format)
610   {
611     va_list ap;
612
613     fprintf(error, "%s%s: ", program_name, process_name);
614
615     if (mode & ERR_WARN)
616       fprintf(error, "warning: ");
617
618     va_start(ap, format);
619     vfprintf(error, format, ap);
620     va_end(ap);
621   
622     fprintf(error, "\n");
623   }
624   
625   if (mode & ERR_HELP)
626     fprintf(error, "%s: Try option '--help' for more information.\n",
627             program_name);
628
629   if (mode & ERR_EXIT)
630     fprintf(error, "%s%s: aborting\n", program_name, process_name);
631
632   if (error != stderr)
633     fclose(error);
634
635   if (mode & ERR_EXIT)
636   {
637     if (mode & ERR_FROM_SERVER)
638       exit(1);                          /* child process: normal exit */
639     else
640       CloseAllAndExit(1);               /* main process: clean up stuff */
641   }
642 }
643
644 void *checked_malloc(unsigned long size)
645 {
646   void *ptr;
647
648   ptr = malloc(size);
649
650   if (ptr == NULL)
651     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
652
653   return ptr;
654 }
655
656 void *checked_calloc(unsigned long size)
657 {
658   void *ptr;
659
660   ptr = calloc(1, size);
661
662   if (ptr == NULL)
663     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
664
665   return ptr;
666 }
667
668 short getFile16BitInteger(FILE *file, int byte_order)
669 {
670   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
671     return ((fgetc(file) <<  8) |
672             (fgetc(file) <<  0));
673   else           /* BYTE_ORDER_LITTLE_ENDIAN */
674     return ((fgetc(file) <<  0) |
675             (fgetc(file) <<  8));
676 }
677
678 void putFile16BitInteger(FILE *file, short value, int byte_order)
679 {
680   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
681   {
682     fputc((value >>  8) & 0xff, file);
683     fputc((value >>  0) & 0xff, file);
684   }
685   else           /* BYTE_ORDER_LITTLE_ENDIAN */
686   {
687     fputc((value >>  0) & 0xff, file);
688     fputc((value >>  8) & 0xff, file);
689   }
690 }
691
692 int getFile32BitInteger(FILE *file, int byte_order)
693 {
694   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
695     return ((fgetc(file) << 24) |
696             (fgetc(file) << 16) |
697             (fgetc(file) <<  8) |
698             (fgetc(file) <<  0));
699   else           /* BYTE_ORDER_LITTLE_ENDIAN */
700     return ((fgetc(file) <<  0) |
701             (fgetc(file) <<  8) |
702             (fgetc(file) << 16) |
703             (fgetc(file) << 24));
704 }
705
706 void putFile32BitInteger(FILE *file, int value, int byte_order)
707 {
708   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
709   {
710     fputc((value >> 24) & 0xff, file);
711     fputc((value >> 16) & 0xff, file);
712     fputc((value >>  8) & 0xff, file);
713     fputc((value >>  0) & 0xff, file);
714   }
715   else           /* BYTE_ORDER_LITTLE_ENDIAN */
716   {
717     fputc((value >>  0) & 0xff, file);
718     fputc((value >>  8) & 0xff, file);
719     fputc((value >> 16) & 0xff, file);
720     fputc((value >> 24) & 0xff, file);
721   }
722 }
723
724 void getFileChunk(FILE *file, char *chunk_buffer, int *chunk_length,
725                   int byte_order)
726 {
727   const int chunk_identifier_length = 4;
728
729   /* read chunk identifier */
730   fgets(chunk_buffer, chunk_identifier_length + 1, file);
731
732   /* read chunk length */
733   *chunk_length = getFile32BitInteger(file, byte_order);
734 }
735
736 void putFileChunk(FILE *file, char *chunk_name, int chunk_length,
737                   int byte_order)
738 {
739   /* write chunk identifier */
740   fputs(chunk_name, file);
741
742   /* write chunk length */
743   putFile32BitInteger(file, chunk_length, byte_order);
744 }
745
746 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
747 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
748 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  2
749
750 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
751 {
752   static struct
753   {
754     Key key;
755     char *x11name;
756     char *name;
757   } translate_key[] =
758   {
759     /* normal cursor keys */
760     { KSYM_Left,        "XK_Left",              "cursor left" },
761     { KSYM_Right,       "XK_Right",             "cursor right" },
762     { KSYM_Up,          "XK_Up",                "cursor up" },
763     { KSYM_Down,        "XK_Down",              "cursor down" },
764
765     /* keypad cursor keys */
766 #ifdef KSYM_KP_Left
767     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
768     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
769     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
770     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
771 #endif
772
773     /* other keypad keys */
774 #ifdef KSYM_KP_Enter
775     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
776     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
777     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
778     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
779     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
780     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
781 #endif
782
783     /* modifier keys */
784     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
785     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
786     { KSYM_Control_L,   "XK_Control_L",         "left control" },
787     { KSYM_Control_R,   "XK_Control_R",         "right control" },
788     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
789     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
790     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
791     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
792     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
793     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
794     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
795     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
796
797     /* some special keys */
798     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
799     { KSYM_Delete,      "XK_Delete",            "delete" },
800     { KSYM_Insert,      "XK_Insert",            "insert" },
801     { KSYM_Tab,         "XK_Tab",               "tab" },
802     { KSYM_Home,        "XK_Home",              "home" },
803     { KSYM_End,         "XK_End",               "end" },
804     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
805     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
806     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
807
808     /* ASCII 0x20 to 0x40 keys (except numbers) */
809     { KSYM_space,       "XK_space",             "space" },
810     { KSYM_exclam,      "XK_exclam",            "!" },
811     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
812     { KSYM_numbersign,  "XK_numbersign",        "#" },
813     { KSYM_dollar,      "XK_dollar",            "$" },
814     { KSYM_percent,     "XK_percent",           "%" },
815     { KSYM_ampersand,   "XK_ampersand",         "&" },
816     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
817     { KSYM_parenleft,   "XK_parenleft",         "(" },
818     { KSYM_parenright,  "XK_parenright",        ")" },
819     { KSYM_asterisk,    "XK_asterisk",          "*" },
820     { KSYM_plus,        "XK_plus",              "+" },
821     { KSYM_comma,       "XK_comma",             "," },
822     { KSYM_minus,       "XK_minus",             "-" },
823     { KSYM_period,      "XK_period",            "." },
824     { KSYM_slash,       "XK_slash",             "/" },
825     { KSYM_colon,       "XK_colon",             ":" },
826     { KSYM_semicolon,   "XK_semicolon",         ";" },
827     { KSYM_less,        "XK_less",              "<" },
828     { KSYM_equal,       "XK_equal",             "=" },
829     { KSYM_greater,     "XK_greater",           ">" },
830     { KSYM_question,    "XK_question",          "?" },
831     { KSYM_at,          "XK_at",                "@" },
832
833     /* more ASCII keys */
834     { KSYM_bracketleft, "XK_bracketleft",       "[" },
835     { KSYM_backslash,   "XK_backslash",         "backslash" },
836     { KSYM_bracketright,"XK_bracketright",      "]" },
837     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
838     { KSYM_underscore,  "XK_underscore",        "_" },
839     { KSYM_grave,       "XK_grave",             "grave" },
840     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
841     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
842     { KSYM_bar,         "XK_bar",               "bar" },
843     { KSYM_braceright,  "XK_braceright",        "brace right" },
844     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
845
846     /* special (non-ASCII) keys */
847     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
848     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
849     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
850     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
851     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
852     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
853     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
854
855     /* end-of-array identifier */
856     { 0,                NULL,                   NULL }
857   };
858
859   int i;
860
861   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
862   {
863     static char name_buffer[30];
864     Key key = *keysym;
865
866     if (key >= KSYM_A && key <= KSYM_Z)
867       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
868     else if (key >= KSYM_a && key <= KSYM_z)
869       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
870     else if (key >= KSYM_0 && key <= KSYM_9)
871       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
872     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
873       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
874     else if (key >= KSYM_F1 && key <= KSYM_F24)
875       sprintf(name_buffer, "function F%d", (int)(key - KSYM_F1 + 1));
876     else if (key == KSYM_UNDEFINED)
877       strcpy(name_buffer, "(undefined)");
878     else
879     {
880       i = 0;
881
882       do
883       {
884         if (key == translate_key[i].key)
885         {
886           strcpy(name_buffer, translate_key[i].name);
887           break;
888         }
889       }
890       while (translate_key[++i].name);
891
892       if (!translate_key[i].name)
893         strcpy(name_buffer, "(unknown)");
894     }
895
896     *name = name_buffer;
897   }
898   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
899   {
900     static char name_buffer[30];
901     Key key = *keysym;
902
903     if (key >= KSYM_A && key <= KSYM_Z)
904       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
905     else if (key >= KSYM_a && key <= KSYM_z)
906       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
907     else if (key >= KSYM_0 && key <= KSYM_9)
908       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
909     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
910       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
911     else if (key >= KSYM_F1 && key <= KSYM_F24)
912       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_F1 + 1));
913     else if (key == KSYM_UNDEFINED)
914       strcpy(name_buffer, "[undefined]");
915     else
916     {
917       i = 0;
918
919       do
920       {
921         if (key == translate_key[i].key)
922         {
923           strcpy(name_buffer, translate_key[i].x11name);
924           break;
925         }
926       }
927       while (translate_key[++i].x11name);
928
929       if (!translate_key[i].x11name)
930         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
931     }
932
933     *x11name = name_buffer;
934   }
935   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
936   {
937     Key key = KSYM_UNDEFINED;
938     char *name_ptr = *x11name;
939
940     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
941     {
942       char c = name_ptr[3];
943
944       if (c >= 'A' && c <= 'Z')
945         key = KSYM_A + (Key)(c - 'A');
946       else if (c >= 'a' && c <= 'z')
947         key = KSYM_a + (Key)(c - 'a');
948       else if (c >= '0' && c <= '9')
949         key = KSYM_0 + (Key)(c - '0');
950     }
951     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
952     {
953       char c = name_ptr[6];
954
955       if (c >= '0' && c <= '9')
956         key = KSYM_0 + (Key)(c - '0');
957     }
958     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
959     {
960       char c1 = name_ptr[4];
961       char c2 = name_ptr[5];
962       int d = 0;
963
964       if ((c1 >= '0' && c1 <= '9') &&
965           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
966         d = atoi(&name_ptr[4]);
967
968       if (d >=1 && d <= 24)
969         key = KSYM_F1 + (Key)(d - 1);
970     }
971     else if (strncmp(name_ptr, "XK_", 3) == 0)
972     {
973       i = 0;
974
975       do
976       {
977         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
978         {
979           key = translate_key[i].key;
980           break;
981         }
982       }
983       while (translate_key[++i].x11name);
984     }
985     else if (strncmp(name_ptr, "0x", 2) == 0)
986     {
987       unsigned long value = 0;
988
989       name_ptr += 2;
990
991       while (name_ptr)
992       {
993         char c = *name_ptr++;
994         int d = -1;
995
996         if (c >= '0' && c <= '9')
997           d = (int)(c - '0');
998         else if (c >= 'a' && c <= 'f')
999           d = (int)(c - 'a' + 10);
1000         else if (c >= 'A' && c <= 'F')
1001           d = (int)(c - 'A' + 10);
1002
1003         if (d == -1)
1004         {
1005           value = -1;
1006           break;
1007         }
1008
1009         value = value * 16 + d;
1010       }
1011
1012       if (value != -1)
1013         key = (Key)value;
1014     }
1015
1016     *keysym = key;
1017   }
1018 }
1019
1020 char *getKeyNameFromKey(Key key)
1021 {
1022   char *name;
1023
1024   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1025   return name;
1026 }
1027
1028 char *getX11KeyNameFromKey(Key key)
1029 {
1030   char *x11name;
1031
1032   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1033   return x11name;
1034 }
1035
1036 Key getKeyFromX11KeyName(char *x11name)
1037 {
1038   Key key;
1039
1040   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1041   return key;
1042 }
1043
1044 char getCharFromKey(Key key)
1045 {
1046   char *keyname = getKeyNameFromKey(key);
1047   char letter = 0;
1048
1049   if (strlen(keyname) == 1)
1050     letter = keyname[0];
1051   else if (strcmp(keyname, "space") == 0)
1052     letter = ' ';
1053   else if (strcmp(keyname, "circumflex") == 0)
1054     letter = '^';
1055
1056   return letter;
1057 }
1058
1059 #define TRANSLATE_JOYSYMBOL_TO_JOYNAME  0
1060 #define TRANSLATE_JOYNAME_TO_JOYSYMBOL  1
1061
1062 void translate_joyname(int *joysymbol, char **name, int mode)
1063 {
1064   static struct
1065   {
1066     int joysymbol;
1067     char *name;
1068   } translate_joy[] =
1069   {
1070     { JOY_LEFT,         "joystick_left" },
1071     { JOY_RIGHT,        "joystick_right" },
1072     { JOY_UP,           "joystick_up" },
1073     { JOY_DOWN,         "joystick_down" },
1074     { JOY_BUTTON_1,     "joystick_button_1" },
1075     { JOY_BUTTON_2,     "joystick_button_2" },
1076   };
1077
1078   int i;
1079
1080   if (mode == TRANSLATE_JOYSYMBOL_TO_JOYNAME)
1081   {
1082     *name = "[undefined]";
1083
1084     for (i=0; i<6; i++)
1085     {
1086       if (*joysymbol == translate_joy[i].joysymbol)
1087       {
1088         *name = translate_joy[i].name;
1089         break;
1090       }
1091     }
1092   }
1093   else if (mode == TRANSLATE_JOYNAME_TO_JOYSYMBOL)
1094   {
1095     *joysymbol = 0;
1096
1097     for (i=0; i<6; i++)
1098     {
1099       if (strcmp(*name, translate_joy[i].name) == 0)
1100       {
1101         *joysymbol = translate_joy[i].joysymbol;
1102         break;
1103       }
1104     }
1105   }
1106 }
1107
1108 char *getJoyNameFromJoySymbol(int joysymbol)
1109 {
1110   char *name;
1111
1112   translate_joyname(&joysymbol, &name, TRANSLATE_JOYSYMBOL_TO_JOYNAME);
1113   return name;
1114 }
1115
1116 int getJoySymbolFromJoyName(char *name)
1117 {
1118   int joysymbol;
1119
1120   translate_joyname(&joysymbol, &name, TRANSLATE_JOYNAME_TO_JOYSYMBOL);
1121   return joysymbol;
1122 }
1123
1124 int getJoystickNrFromDeviceName(char *device_name)
1125 {
1126   char c;
1127   int joystick_nr = 0;
1128
1129   if (device_name == NULL || device_name[0] == '\0')
1130     return 0;
1131
1132   c = device_name[strlen(device_name) - 1];
1133
1134   if (c >= '0' && c <= '9')
1135     joystick_nr = (int)(c - '0');
1136
1137   if (joystick_nr < 0 || joystick_nr >= MAX_PLAYERS)
1138     joystick_nr = 0;
1139
1140   return joystick_nr;
1141 }
1142
1143 /* ------------------------------------------------------------------------- */
1144 /* some functions to handle lists of level directories                       */
1145 /* ------------------------------------------------------------------------- */
1146
1147 struct LevelDirInfo *newLevelDirInfo()
1148 {
1149   return checked_calloc(sizeof(struct LevelDirInfo));
1150 }
1151
1152 void pushLevelDirInfo(struct LevelDirInfo **node_first,
1153                       struct LevelDirInfo *node_new)
1154 {
1155   node_new->next = *node_first;
1156   *node_first = node_new;
1157 }
1158
1159 int numLevelDirInfo(struct LevelDirInfo *node)
1160 {
1161   int num = 0;
1162
1163   while (node)
1164   {
1165     num++;
1166     node = node->next;
1167   }
1168
1169   return num;
1170 }
1171
1172 boolean validLevelSeries(struct LevelDirInfo *node)
1173 {
1174   return (node != NULL && !node->node_group && !node->parent_link);
1175 }
1176
1177 struct LevelDirInfo *getFirstValidLevelSeries(struct LevelDirInfo *node)
1178 {
1179   if (node == NULL)
1180   {
1181     if (leveldir_first)         /* start with first level directory entry */
1182       return getFirstValidLevelSeries(leveldir_first);
1183     else
1184       return NULL;
1185   }
1186   else if (node->node_group)    /* enter level group (step down into tree) */
1187     return getFirstValidLevelSeries(node->node_group);
1188   else if (node->parent_link)   /* skip start entry of level group */
1189   {
1190     if (node->next)             /* get first real level series entry */
1191       return getFirstValidLevelSeries(node->next);
1192     else                        /* leave empty level group and go on */
1193       return getFirstValidLevelSeries(node->node_parent->next);
1194   }
1195   else                          /* this seems to be a regular level series */
1196     return node;
1197 }
1198
1199 struct LevelDirInfo *getLevelDirInfoFirstGroupEntry(struct LevelDirInfo *node)
1200 {
1201   if (node == NULL)
1202     return NULL;
1203
1204   if (node->node_parent == NULL)                /* top level group */
1205     return leveldir_first;
1206   else                                          /* sub level group */
1207     return node->node_parent->node_group;
1208 }
1209
1210 int numLevelDirInfoInGroup(struct LevelDirInfo *node)
1211 {
1212   return numLevelDirInfo(getLevelDirInfoFirstGroupEntry(node));
1213 }
1214
1215 int posLevelDirInfo(struct LevelDirInfo *node)
1216 {
1217   struct LevelDirInfo *node_cmp = getLevelDirInfoFirstGroupEntry(node);
1218   int pos = 0;
1219
1220   while (node_cmp)
1221   {
1222     if (node_cmp == node)
1223       return pos;
1224
1225     pos++;
1226     node_cmp = node_cmp->next;
1227   }
1228
1229   return 0;
1230 }
1231
1232 struct LevelDirInfo *getLevelDirInfoFromPos(struct LevelDirInfo *node, int pos)
1233 {
1234   struct LevelDirInfo *node_default = node;
1235   int pos_cmp = 0;
1236
1237   while (node)
1238   {
1239     if (pos_cmp == pos)
1240       return node;
1241
1242     pos_cmp++;
1243     node = node->next;
1244   }
1245
1246   return node_default;
1247 }
1248
1249 struct LevelDirInfo *getLevelDirInfoFromFilenameExt(struct LevelDirInfo *node,
1250                                                     char *filename)
1251 {
1252   if (filename == NULL)
1253     return NULL;
1254
1255   while (node)
1256   {
1257     if (node->node_group)
1258     {
1259       struct LevelDirInfo *node_group;
1260
1261       node_group = getLevelDirInfoFromFilenameExt(node->node_group, filename);
1262
1263       if (node_group)
1264         return node_group;
1265     }
1266     else if (!node->parent_link)
1267     {
1268       if (strcmp(filename, node->filename) == 0)
1269         return node;
1270     }
1271
1272     node = node->next;
1273   }
1274
1275   return NULL;
1276 }
1277
1278 struct LevelDirInfo *getLevelDirInfoFromFilename(char *filename)
1279 {
1280   return getLevelDirInfoFromFilenameExt(leveldir_first, filename);
1281 }
1282
1283 void dumpLevelDirInfo(struct LevelDirInfo *node, int depth)
1284 {
1285   int i;
1286
1287   while (node)
1288   {
1289     for (i=0; i<depth * 3; i++)
1290       printf(" ");
1291
1292     printf("filename == '%s'\n", node->filename);
1293
1294     if (node->node_group != NULL)
1295       dumpLevelDirInfo(node->node_group, depth + 1);
1296
1297     node = node->next;
1298   }
1299 }
1300
1301 void sortLevelDirInfo(struct LevelDirInfo **node_first,
1302                       int (*compare_function)(const void *, const void *))
1303 {
1304   int num_nodes = numLevelDirInfo(*node_first);
1305   struct LevelDirInfo **sort_array;
1306   struct LevelDirInfo *node = *node_first;
1307   int i = 0;
1308
1309   if (num_nodes == 0)
1310     return;
1311
1312   /* allocate array for sorting structure pointers */
1313   sort_array = checked_calloc(num_nodes * sizeof(struct LevelDirInfo *));
1314
1315   /* writing structure pointers to sorting array */
1316   while (i < num_nodes && node)         /* double boundary check... */
1317   {
1318     sort_array[i] = node;
1319
1320     i++;
1321     node = node->next;
1322   }
1323
1324   /* sorting the structure pointers in the sorting array */
1325   qsort(sort_array, num_nodes, sizeof(struct LevelDirInfo *),
1326         compare_function);
1327
1328   /* update the linkage of list elements with the sorted node array */
1329   for (i=0; i<num_nodes - 1; i++)
1330     sort_array[i]->next = sort_array[i + 1];
1331   sort_array[num_nodes - 1]->next = NULL;
1332
1333   /* update the linkage of the main list anchor pointer */
1334   *node_first = sort_array[0];
1335
1336   free(sort_array);
1337
1338   /* now recursively sort the level group structures */
1339   node = *node_first;
1340   while (node)
1341   {
1342     if (node->node_group != NULL)
1343       sortLevelDirInfo(&node->node_group, compare_function);
1344
1345     node = node->next;
1346   }
1347 }
1348
1349 inline void swap_numbers(int *i1, int *i2)
1350 {
1351   int help = *i1;
1352
1353   *i1 = *i2;
1354   *i2 = help;
1355 }
1356
1357 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1358 {
1359   int help_x = *x1;
1360   int help_y = *y1;
1361
1362   *x1 = *x2;
1363   *x2 = help_x;
1364
1365   *y1 = *y2;
1366   *y2 = help_y;
1367 }
1368
1369
1370 /* ------------------------------------------------------------------------- */
1371 /* the following is only for debugging purpose and normally not used         */
1372 /* ------------------------------------------------------------------------- */
1373
1374 #define DEBUG_NUM_TIMESTAMPS    3
1375
1376 void debug_print_timestamp(int counter_nr, char *message)
1377 {
1378   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1379
1380   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1381     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1382
1383   counter[counter_nr][0] = Counter();
1384
1385   if (message)
1386     printf("%s %.2f seconds\n", message,
1387            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1388
1389   counter[counter_nr][1] = Counter();
1390 }