Debian Codegraph @

terps/level9/Glk/glk.c

raw symbols SCIP
1 /* vi: set ts=2 shiftwidth=2 expandtab:
2 *
3 * Copyright (C) 2002-2011 Simon Baldwin, [email protected]
4 * Mac portions Copyright (C) 2002 Ben Hines
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of version 2 of the GNU General Public License
8 * as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 * USA
19 */
20
21 /*
22 * Glk interface for Level 9
23 * -------------------------
24 *
25 * This module contains the the Glk porting layer for the Level 9
26 * interpreter. It defines the Glk arguments list structure, the
27 * entry points for the Glk library framework to use, and all
28 * platform-abstracted I/O to link to Glk's I/O.
29 *
30 * The following items are omitted from this Glk port:
31 *
32 * o Glk tries to assert control over _all_ file I/O. It's just too
33 * disruptive to add it to existing code, so for now, the Level 9
34 * interpreter is still dependent on stdio and the like.
35 *
36 */
37
38 #include <assert.h>
39 #include <errno.h>
40 #include <stdio.h>
41 #include <ctype.h>
42 #include <time.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <limits.h>
46 #include <stddef.h>
47
48 #include "level9.h"
49
50 #include "glk.h"
51
52 /*
53 * True and false definitions -- usually defined in glkstart.h, but we need
54 * them early, so we'll define them here too. We also need NULL, but that's
55 * normally from stdio.h or one of it's cousins.
56 */
57 #ifndef FALSE
58 # define FALSE 0
59 #endif
60 #ifndef TRUE
61 # define TRUE (!FALSE)
62 #endif
63
64 /* File path delimiter, used to be #defined in v2 interpreter. */
65 #if defined(_Windows) || defined(__MSDOS__) \
66 || defined (_WIN32) || defined (__WIN32__)
67 static const char GLN_FILE_DELIM = '\\';
68 #else
69 static const char GLN_FILE_DELIM = '/';
70 #endif
71
72
73 /*---------------------------------------------------------------------*/
74 /* Module variables, miscellaneous other stuff */
75 /*---------------------------------------------------------------------*/
76
77 /* Glk Level 9 port version number. */
78 static const glui32 GLN_PORT_VERSION = 0x00020201;
79
80 /*
81 * We use a maximum of three Glk windows, one for status, one for pictures,
82 * and one for everything else. The status and pictures windows may be
83 * NULL, depending on user selections and the capabilities of the Glk
84 * library.
85 */
86 static winid_t gln_main_window = NULL,
87 gln_status_window = NULL,
88 gln_graphics_window = NULL;
89
90 /*
91 * Transcript stream and input log. These are NULL if there is no current
92 * collection of these strings.
93 */
94 static strid_t gln_transcript_stream = NULL,
95 gln_inputlog_stream = NULL;
96
97 /* Input read log stream, for reading back an input log. */
98 static strid_t gln_readlog_stream = NULL;
99
100 /* Note about whether graphics is possible, or not. */
101 static int gln_graphics_possible = TRUE;
102
103 /* Options that may be turned off by command line flags. */
104 static int gln_graphics_enabled = TRUE,
105 gln_intercept_enabled = TRUE,
106 gln_prompt_enabled = TRUE,
107 gln_loopcheck_enabled = TRUE,
108 gln_abbreviations_enabled = TRUE,
109 gln_commands_enabled = TRUE;
110
111 /* Reason for stopping the game, used to detect restarts and ^C exits. */
112 static enum {
113 STOP_NONE, STOP_FORCE, STOP_RESTART, STOP_EXIT
114 }
115 gln_stop_reason = STOP_NONE;
116
117 /* Level 9 standard input prompt string. */
118 static const char * const GLN_INPUT_PROMPT = "> ";
119
120 /*
121 * Typedef equivalents for interpreter types (uncapitalized to avoid appearing
122 * as macros), and some internal interpreter symbols symbols used for our own
123 * deviant purposes.
124 */
125 typedef L9BOOL gln_bool;
126 typedef L9BYTE gln_byte;
127 typedef L9UINT16 gln_uint16;
128 typedef L9UINT32 gln_uint32;
129
130 extern void save (void);
131 extern void restore (void);
132 extern gln_bool Cheating;
133 extern gln_byte *startdata;
134 extern gln_uint32 FileSize;
135 extern int L9V1Game;
136
137 /* Forward declarations of event wait and other miscellaneous functions. */
138 static void gln_event_wait (glui32 wait_type, event_t * event);
139 static void gln_event_wait_2 (glui32 wait_type_1,
140 glui32 wait_type_2, event_t * event);
141
142 static void gln_watchdog_tick (void);
143 static void gln_standout_string (const char *message);
144
145 static int gln_confirm (const char *prompt);
146
147
148 /*---------------------------------------------------------------------*/
149 /* Glk port utility functions */
150 /*---------------------------------------------------------------------*/
151
152 /*
153 * gln_fatal()
154 *
155 * Fatal error handler. The function returns, expecting the caller to
156 * abort() or otherwise handle the error.
157 */
158 static void
159 gln_fatal (const char *string)
160 {
161 /*
162 * If the failure happens too early for us to have a window, print
163 * the message to stderr.
164 */
165 if (!gln_main_window)
166 {
167 fprintf (stderr, "\n\nINTERNAL ERROR: %s\n", string);
168
169 fprintf (stderr, "\nPlease record the details of this error, try to"
170 " note down everything you did to cause it, and email"
171 " this information to [email protected].\n\n");
172 return;
173 }
174
175 /* Cancel all possible pending window input events. */
176 glk_cancel_line_event (gln_main_window, NULL);
177 glk_cancel_char_event (gln_main_window);
178
179 /* Print a message indicating the error. */
180 glk_set_window (gln_main_window);
181 glk_set_style (style_Normal);
182 glk_put_string ("\n\nINTERNAL ERROR: ");
183 glk_put_string ((char *) string);
184
185 glk_put_string ("\n\nPlease record the details of this error, try to"
186 " note down everything you did to cause it, and email"
187 " this information to [email protected].\n\n");
188 }
189
190
191 /*
192 * gln_malloc()
193 * gln_realloc()
194 *
195 * Non-failing malloc and realloc; call gln_fatal and exit if memory
196 * allocation fails.
197 */
198 static void *
199 gln_malloc (size_t size)
200 {
201 void *pointer;
202
203 pointer = malloc (size);
204 if (!pointer)
205 {
206 gln_fatal ("GLK: Out of system memory");
207 glk_exit ();
208 }
209
210 return pointer;
211 }
212
213 static void *
214 gln_realloc (void *ptr, size_t size)
215 {
216 void *pointer;
217
218 pointer = realloc (ptr, size);
219 if (!pointer)
220 {
221 gln_fatal ("GLK: Out of system memory");
222 glk_exit ();
223 }
224
225 return pointer;
226 }
227
228
229 /*
230 * gln_strncasecmp()
231 * gln_strcasecmp()
232 *
233 * Strncasecmp and strcasecmp are not ANSI functions, so here are local
234 * definitions to do the same jobs.
235 *
236 * They're global here so that the core interpreter can use them; otherwise
237 * it tries to use the non-ANSI str[n]icmp() functions.
238 */
239 int
240 gln_strncasecmp (const char *s1, const char *s2, size_t n)
241 {
242 size_t index;
243
244 for (index = 0; index < n; index++)
245 {
246 int diff;
247
248 diff = glk_char_to_lower (s1[index]) - glk_char_to_lower (s2[index]);
249 if (diff < 0 || diff > 0)
250 return diff < 0 ? -1 : 1;
251 }
252
253 return 0;
254 }
255
256 int
257 gln_strcasecmp (const char *s1, const char *s2)
258 {
259 size_t s1len, s2len;
260 int result;
261
262 s1len = strlen (s1);
263 s2len = strlen (s2);
264
265 result = gln_strncasecmp (s1, s2, s1len < s2len ? s1len : s2len);
266 if (result < 0 || result > 0)
267 return result;
268 else
269 return s1len < s2len ? -1 : s1len > s2len ? 1 : 0;
270 }
271
272
273 /*---------------------------------------------------------------------*/
274 /* Glk port stub graphics functions */
275 /*---------------------------------------------------------------------*/
276
277 /*
278 * If we're working with a very stripped down, old, or lazy Glk library
279 * that neither offers Glk graphics nor graphics stubs functions, here
280 * we define our own stubs, to avoid link-time errors.
281 */
282 #ifndef GLK_MODULE_IMAGE
283 static glui32
284 glk_image_draw (winid_t win, glui32 image, glsi32 val1, glsi32 val2)
285 {
286 return FALSE;
287 }
288 static glui32
289 glk_image_draw_scaled (winid_t win, glui32 image, glsi32 val1, glsi32 val2,
290 glui32 width, glui32 height)
291 {
292 return FALSE;
293 }
294 static glui32
295 glk_image_get_info (glui32 image, glui32 * width, glui32 * height)
296 {
297 return FALSE;
298 }
299 static void
300 glk_window_flow_break (winid_t win)
301 {
302 }
303 static void
304 glk_window_erase_rect (winid_t win, glsi32 left, glsi32 top,
305 glui32 width, glui32 height)
306 {
307 }
308 static void
309 glk_window_fill_rect (winid_t win, glui32 color, glsi32 left, glsi32 top,
310 glui32 width, glui32 height)
311 {
312 }
313 static void
314 glk_window_set_background_color (winid_t win, glui32 color)
315 {
316 }
317 #endif
318
319
320 /*---------------------------------------------------------------------*/
321 /* Glk port CRC functions */
322 /*---------------------------------------------------------------------*/
323
324 /* CRC table initialization polynomial. */
325 static const gln_uint16 GLN_CRC_POLYNOMIAL = 0xa001;
326
327
328 /*
329 * gln_get_buffer_crc()
330 *
331 * Return the CRC of the bytes buffer[0..length-1].
332 *
333 * This algorithm is selected to match the CRCs used in L9cut. Because of
334 * the odd way CRCs are padded when L9cut calculates the CRC, this function
335 * allows a count of NUL padding bytes to be included within the return CRC.
336 */
337 static gln_uint16
338 gln_get_buffer_crc (const void *void_buffer, size_t length, size_t padding)
339 {
340 static int is_initialized = FALSE;
341 static gln_uint16 crc_table[UCHAR_MAX + 1];
342
343 const char *buffer = (const char *) void_buffer;
344 gln_uint16 crc;
345 size_t index;
346
347 /* Build the static CRC lookup table on first call. */
348 if (!is_initialized)
349 {
350 for (index = 0; index < UCHAR_MAX + 1; index++)
351 {
352 int bit;
353
354 crc = (gln_uint16) index;
355 for (bit = 0; bit < CHAR_BIT; bit++)
356 crc = crc & 1 ? GLN_CRC_POLYNOMIAL ^ (crc >> 1) : crc >> 1;
357
358 crc_table[index] = crc;
359 }
360
361 is_initialized = TRUE;
362
363 /* CRC lookup table self-test, after is_initialized set -- recursion. */
364 assert (gln_get_buffer_crc ("123456789", 9, 0) == 0xbb3d);
365 }
366
367 /* Start with zero in the crc, then update using table entries. */
368 crc = 0;
369 for (index = 0; index < length; index++)
370 crc = crc_table[(crc ^ buffer[index]) & UCHAR_MAX] ^ (crc >> CHAR_BIT);
371
372 /* Add in any requested NUL padding bytes. */
373 for (index = 0; index < padding; index++)
374 crc = crc_table[crc & UCHAR_MAX] ^ (crc >> CHAR_BIT);
375
376 return crc;
377 }
378
379
380 /*---------------------------------------------------------------------*/
381 /* Glk port game identification data and identification functions */
382 /*---------------------------------------------------------------------*/
383
384 /*
385 * The game's name, suitable for printing out on a status line, or other
386 * location where game information is relevant. It's generated on demand,
387 * and may be re-requested when, say, the game changes, perhaps by moving to
388 * the next part of a multipart game.
389 */
390 static const char *gln_gameid_game_name = NULL;
391
392
393 /*
394 * The following game database is obtained from L9cut's l9data_d.h, and
395 * lets us find a game's name from its data CRC. Entries marked "WANTED" in
396 * l9data_d.h, and file commentary, have been removed for brevity, and the
397 * file has been reformatted (patchlevel data removed).
398 *
399 * The version of l9data_d.h used is 050 (22 Oct 2002).
400 * A number of MSX entries have been added on top of that.
401 */
402 typedef const struct
403 {
404 const gln_uint16 length; /* Datafile length in bytes */
405 const gln_byte checksum; /* 8-bit checksum, last datafile byte */
406 const gln_uint16 crc; /* 16-bit CRC, L9cut-internal */
407 const char * const name; /* Game title and platform */
408 } gln_game_table_t;
409 typedef gln_game_table_t *gln_game_tableref_t;
410
411 static gln_game_table_t GLN_V1GAME_TABLE[] = {
412 {0x0001, 0x01, 0x0001, "Colossal Adventure (v1)"},
413 {0x0002, 0x02, 0x0002, "Adventure Quest (v1)"},
414 {0x0003, 0x03, 0x0003, "Dungeon Adventure (v1)"},
415 {0x0004, 0x04, 0x0004, "Lords of Time (v1)"},
416 {0x0005, 0x05, 0x0005, "Snowball (v1)"},
417
418 {0x0000, 0x00, 0x0000, NULL}
419 };
420
421 static gln_game_table_t GLN_GAME_TABLE[] = {
422 {0x6155, 0xe8, 0xe6f4, "Colossal Adventure (MSX[A])"},
423 {0x616a, 0x90, 0x7482, "Colossal Adventure (MSX[B])"},
424
425 {0x5323, 0xb7, 0x8af7, "Adventure Quest (Amstrad CPC/Spectrum)"},
426 {0x5323, 0x11, 0xaf28, "Adventure Quest (MSX)"},
427
428 {0x630e, 0x8d, 0x7d7d, "Dungeon Adventure (Amstrad CPC)"},
429 {0x630e, 0xbe, 0x3374, "Dungeon Adventure (MSX)"},
430
431 {0x5eb9, 0x30, 0xe99a, "Lords of Time (Amstrad CPC)"},
432 {0x5eb9, 0x5d, 0xc098, "Lords of Time (MSX *corrupt*)"},
433 {0x5eb9, 0x6e, 0xc689, "Lords of Time (Spectrum/MSX *fixed*)"},
434
435 {0x5fab, 0x5c, 0xa309, "Snowball (Amstrad CPC)"},
436 {0x5fab, 0x2f, 0x8aa2, "Snowball (MSX)"},
437
438 {0x60c4, 0x28, 0x0154, "Return to Eden (Amstrad CPC/Commodore 64[v1])"},
439 {0x6064, 0x01, 0x5b3c, "Return to Eden (BBC[v1])"},
440 {0x6064, 0x95, 0x510c, "Return to Eden (Commodore 64[v2])"},
441 {0x6064, 0xda, 0xe610, "Return to Eden (Commodore 64[v2] *corrupt*)"},
442 {0x6064, 0xbd, 0x73ec, "Return to Eden (Atari *corrupt*)"},
443 {0x6047, 0x6c, 0x17ab, "Return to Eden (BBC[v2])"},
444 {0x5ca1, 0x33, 0x1c43, "Return to Eden (Spectrum[v1])"},
445 {0x5cb7, 0x64, 0x0790, "Return to Eden (Spectrum[v2])"},
446 {0x5cb7, 0xfe, 0x3533, "Return to Eden (MSX)"},
447
448 {0x34b3, 0x20, 0xccda, "Erik the Viking (BBC/Commodore 64)"},
449 {0x34b3, 0x53, 0x8f00, "Erik the Viking (Spectrum)"},
450 {0x34b3, 0xc7, 0x9058, "Erik the Viking (Amstrad CPC)"},
451 {0x34b3, 0xa8, 0x2cf2, "Erik the Viking (MSX *converted*)"},
452
453 {0x63be, 0xd6, 0xcf5d,
454 "Emerald Isle (Atari/Commodore 64/Amstrad CPC/Spectrum/MSX)"},
455 {0x63be, 0x0a, 0x21ed, "Emerald Isle (MSX *corrupt*)"},
456 {0x378c, 0x8d, 0x3a21, "Emerald Isle (BBC)"},
457
458 {0x506c, 0xf0, 0xba72, "Red Moon (BBC/Commodore 64/Amstrad CPC/MSX)"},
459 {0x505d, 0x32, 0x2dcf, "Red Moon (Spectrum)"},
460
461 {0x772b, 0xcd, 0xa503, "Worm in Paradise (Spectrum 128/MSX)"},
462 {0x546c, 0xb7, 0x9420, "Worm in Paradise (Spectrum 48)"},
463 {0x6d84, 0xf9, 0x49ae, "Worm in Paradise (Commodore 64 *corrupt*)"},
464 {0x6d84, 0xc8, 0x943f, "Worm in Paradise (Commodore 64 *fixed*)"},
465 {0x6030, 0x47, 0x46ad, "Worm in Paradise (Amstrad CPC)"},
466 {0x5828, 0xbd, 0xe7cb, "Worm in Paradise (BBC)"},
467
468 {0x7410, 0x5e, 0x60be, "Price of Magik (Spectrum 128)"},
469 {0x5aa4, 0xc1, 0x10a0, "Price of Magik (Spectrum 48[v1])"},
470 {0x5aa4, 0xc1, 0xeda4, "Price of Magik (Spectrum 48[v2])"},
471 {0x6fc6, 0x14, 0xf9b6, "Price of Magik (Commodore 64)"},
472 {0x5aa4, 0xc1, 0xbbf4, "Price of Magik (Amstrad CPC)"},
473 {0x5671, 0xbc, 0xff35, "Price of Magik (BBC)"},
474 {0x7334, 0x87, 0x8b5d, "Price of Magik (MSX)"},
475
476 {0x76f4, 0x5e, 0x1fe5, "Colossal Adventure /JoD (Amiga/PC)"},
477 {0x76f4, 0x5a, 0xcf4b, "Colossal Adventure /JoD (ST)"},
478 {0x6e60, 0x83, 0x18e0, "Adventure Quest /JoD (Amiga/PC)"},
479 {0x6e5c, 0xf6, 0xd356, "Adventure Quest /JoD (ST)"},
480 {0x6f0c, 0x95, 0x1f64, "Dungeon Adventure /JoD (Amiga/PC/ST)"},
481
482 {0x6f6e, 0x78, 0x28cd, "Colossal Adventure /JoD (Spectrum 128)"},
483 {0x6970, 0xd6, 0xa820, "Adventure Quest /JoD (Spectrum 128)"},
484 {0x6de8, 0x4c, 0xd795, "Dungeon Adventure /JoD (Spectrum 128)"},
485
486 {0x6f4d, 0xcb, 0xe8f2,
487 "Colossal Adventure /JoD (Amstrad CPC128[v1]/Spectrum +3)"},
488 {0x6f6a, 0xa5, 0x8dd2, "Colossal Adventure /JoD (Amstrad CPC128[v2])"},
489 {0x6968, 0x32, 0x0c01, "Adventure Quest /JoD (Amstrad CPC128/Spectrum +3)"},
490 {0x6dc0, 0x63, 0x5d95, "Dungeon Adventure /JoD (Amstrad CPC128/Spectrum +3)"},
491
492 {0x5e31, 0x7c, 0xaa54, "Colossal Adventure /JoD (Amstrad CPC64)"},
493 {0x5b50, 0x66, 0x1800, "Adventure Quest /JoD (Amstrad CPC64)"},
494 {0x58a6, 0x24, 0xb50f, "Dungeon Adventure /JoD (Amstrad CPC64)"},
495
496 {0x6c8e, 0xb6, 0x9be3, "Colossal Adventure /JoD (Commodore 64)"},
497 {0x63b6, 0x2e, 0xef38, "Adventure Quest /JoD (Commodore 64)"},
498 {0x6bd2, 0x65, 0xa41f, "Dungeon Adventure /JoD (Commodore 64)"},
499
500 {0x5b16, 0x3b, 0xe2aa, "Colossal Adventure /JoD (Atari)"},
501 {0x5b58, 0x50, 0x332e, "Adventure Quest /JoD (Atari)"},
502 {0x593a, 0x80, 0x7a34, "Dungeon Adventure /JoD (Atari)"},
503
504 {0x5a8e, 0xf2, 0x7cca, "Colossal Adventure /JoD (Spectrum 48)"},
505 {0x5ace, 0x11, 0xdc12, "Adventure Quest /JoD (Spectrum 48)"},
506 {0x58a3, 0x38, 0x8ce4, "Dungeon Adventure /JoD (Spectrum 48)"},
507
508 {0x7b31, 0x6e, 0x2e2b, "Snowball /SD (Amiga/ST)"},
509 {0x7d16, 0xe6, 0x5438, "Return to Eden /SD (Amiga/ST)"},
510 {0x7cd9, 0x0c, 0x4df1, "Worm in Paradise /SD (Amiga/ST)"},
511
512 {0x6f70, 0x40, 0xbd91, "Colossal Adventure /JoD (MSX)"},
513 {0x6972, 0x55, 0x042e, "Adventure Quest /JoD (MSX)"},
514 {0x6dea, 0x50, 0xe4f7, "Dungeon Adventure /JoD (MSX)"},
515
516 {0x7b2f, 0x70, 0x6955, "Snowball /SD (Mac/PC/Spectrum 128)"},
517 {0x7b2f, 0x70, 0x6f6c, "Snowball /SD (Amstrad CPC/Spectrum +3)"},
518 {0x7d14, 0xe8, 0xfbab, "Return to Eden /SD (PC)"},
519 {0x7cff, 0xf8, 0x6044, "Return to Eden /SD (Amstrad CPC/Spectrum +3)"},
520 {0x7cf8, 0x24, 0x9c1c, "Return to Eden /SD (Mac)"},
521 {0x7c55, 0x18, 0xdaee, "Return to Eden /SD (Spectrum 128)"},
522 {0x7cd7, 0x0e, 0x4feb,
523 "Worm in Paradise /SD (Amstrad CPC/Mac/PC/Spectrum 128/Spectrum +3)"},
524
525 {0x7363, 0x65, 0xa0ab, "Snowball /SD (Commodore 64/MSX)"},
526 {0x772f, 0xca, 0x8602, "Return to Eden /SD (Commodore 64/MSX)"},
527 {0x788d, 0x72, 0x888a, "Worm in Paradise /SD (Commodore 64/MSX)"},
528
529 {0x6bf8, 0x3f, 0xc9f7, "Snowball /SD (Atari)"},
530 {0x60f7, 0x68, 0xc2bc, "Return to Eden /SD (Atari)"},
531 {0x6161, 0xf3, 0xe6d7, "Worm in Paradise /SD (Atari)"},
532
533 {0x67a3, 0x9d, 0x1d05, "Snowball /SD (Apple ][)"},
534 {0x639c, 0x8b, 0x06e2, "Return to Eden /SD (Apple ][)"},
535 {0x60dd, 0xf2, 0x5bb8, "Worm in Paradise /SD (Apple ][)"},
536
537 {0x6541, 0x02, 0x2e6c, "Snowball /SD (Spectrum 48)"},
538 {0x5f43, 0xca, 0x828c, "Return to Eden /SD (Spectrum 48)"},
539 {0x5ebb, 0xf1, 0x4dec, "Worm in Paradise /SD (Spectrum 48)"},
540
541 {0x8333, 0xb7, 0xe2ac, "Adrian Mole I, pt. 1 (Commodore 64)"},
542 {0x844d, 0x50, 0x5353, "Adrian Mole I, pt. 2 (Commodore 64)"},
543 {0x8251, 0x5f, 0x862a, "Adrian Mole I, pt. 3 (Commodore 64)"},
544 {0x7a78, 0x5e, 0x6ea3, "Adrian Mole I, pt. 4 (Commodore 64)"},
545
546 {0x7c6f, 0x0f, 0xba24, "Adrian Mole I, pt. 1 (Amstrad CPC)"},
547
548 {0x72fa, 0x8b, 0x6f12, "Adrian Mole I, pt. 1 (Spectrum)"},
549 {0x738e, 0x5b, 0x7e3d, "Adrian Mole I, pt. 2 (Spectrum)"},
550 {0x7375, 0xe5, 0x3f3e, "Adrian Mole I, pt. 3 (Spectrum)"},
551 {0x78d5, 0xe3, 0xcd7d, "Adrian Mole I, pt. 4 (Spectrum)"},
552
553 {0x3a31, 0xe5, 0x0bdb, "Adrian Mole I, pt. 1 (BBC)"},
554 {0x37f1, 0x77, 0xd231, "Adrian Mole I, pt. 2 (BBC)"},
555 {0x3900, 0x1c, 0x5d9a, "Adrian Mole I, pt. 3 (BBC)"},
556 {0x3910, 0xac, 0x07f9, "Adrian Mole I, pt. 4 (BBC)"},
557 {0x3ad6, 0xa7, 0x95d2, "Adrian Mole I, pt. 5 (BBC)"},
558 {0x38a5, 0x0f, 0xdefc, "Adrian Mole I, pt. 6 (BBC)"},
559 {0x361e, 0x7e, 0xfd9f, "Adrian Mole I, pt. 7 (BBC)"},
560 {0x3934, 0x75, 0xe141, "Adrian Mole I, pt. 8 (BBC)"},
561 {0x3511, 0xcc, 0xd829, "Adrian Mole I, pt. 9 (BBC)"},
562 {0x38dd, 0x31, 0x2534, "Adrian Mole I, pt. 10 (BBC)"},
563 {0x39c0, 0x44, 0x89df, "Adrian Mole I, pt. 11 (BBC)"},
564 {0x3a12, 0x8f, 0xc2bd, "Adrian Mole I, pt. 12 (BBC)"},
565
566 {0x8324, 0x87, 0xb9ae, "Adrian Mole I, pt. 1 (MSX *corrupt*)"},
567 {0x8324, 0x87, 0x2736, "Adrian Mole I, pt. 1 (MSX *fixed*)"},
568 {0x8442, 0x0f, 0x8e7a, "Adrian Mole I, pt. 2 (MSX *corrupt*)"},
569 {0x8442, 0x0f, 0xe1f7, "Adrian Mole I, pt. 2 (MSX *fixed*)"},
570 {0x823e, 0x5c, 0x82d9, "Adrian Mole I, pt. 3 (MSX)"},
571 {0x824e, 0x77, 0xffa3, "Adrian Mole I, pt. 3 (MSX *reconstructed*)"},
572 {0x7a71, 0xfb, 0x945e, "Adrian Mole I, pt. 4 (MSX)"},
573 {0x7a75, 0xe3, 0x6cee, "Adrian Mole I, pt. 4 (MSX *reconstructed*)"},
574
575 {0x7931, 0xb9, 0xc51b, "Adrian Mole II, pt. 1 (Commodore 64/Amstrad CPC/MSX)"},
576 {0x7cdf, 0xa5, 0x43e3, "Adrian Mole II, pt. 2 (Commodore 64/Amstrad CPC/MSX)"},
577 {0x7a0c, 0x97, 0x4bea, "Adrian Mole II, pt. 3 (Commodore 64/Amstrad CPC/MSX)"},
578 {0x7883, 0xe2, 0xee0e, "Adrian Mole II, pt. 4 (Commodore 64/Amstrad CPC/MSX)"},
579
580 {0x6841, 0x4a, 0x94e7, "Adrian Mole II, pt. 1 (Spectrum)"},
581 {0x6bc0, 0x62, 0xab3d, "Adrian Mole II, pt. 2 (Spectrum)"},
582 {0x692c, 0x21, 0x2015, "Adrian Mole II, pt. 3 (Spectrum)"},
583 {0x670a, 0x94, 0xa2a6, "Adrian Mole II, pt. 4 (Spectrum)"},
584
585 {0x593a, 0xaf, 0x30e9, "Adrian Mole II, pt. 1 (BBC)"},
586 {0x57e6, 0x8a, 0xc41a, "Adrian Mole II, pt. 2 (BBC)"},
587 {0x5819, 0xcd, 0x1ba0, "Adrian Mole II, pt. 3 (BBC)"},
588 {0x579b, 0xad, 0xa723, "Adrian Mole II, pt. 4 (BBC)"},
589
590 {0x765d, 0xcd, 0xfc02, "The Archers, pt. 1 (Commodore 64/MSX)"},
591 {0x6e58, 0x07, 0xbffc, "The Archers, pt. 2 (Commodore 64)"},
592 {0x6e56, 0x17, 0x477d, "The Archers, pt. 2 (MSX)"},
593 {0x7e98, 0x6a, 0x95e5, "The Archers, pt. 3 (Commodore 64/MSX)"},
594 {0x81e2, 0xd5, 0xb278, "The Archers, pt. 4 (Commodore 64/MSX)"},
595
596 {0x6ce5, 0x58, 0x46de, "The Archers, pt. 1 (Spectrum)"},
597 {0x68da, 0xc1, 0x3b8e, "The Archers, pt. 2 (Spectrum)"},
598 {0x6c67, 0x9a, 0x9a6a, "The Archers, pt. 3 (Spectrum)"},
599 {0x6d91, 0xb9, 0x12a7, "The Archers, pt. 4 (Spectrum)"},
600
601 {0x5834, 0x42, 0xcc9d, "The Archers, pt. 1 (BBC)"},
602 {0x56dd, 0x51, 0xe582, "The Archers, pt. 2 (BBC)"},
603 {0x5801, 0x53, 0xf2ef, "The Archers, pt. 3 (BBC)"},
604 {0x54a4, 0x01, 0xc0ab, "The Archers, pt. 4 (BBC)"},
605
606 {0x579e, 0x97, 0x9faa, "Lords of Time /T&M GD (BBC)"},
607 {0x5500, 0x50, 0xca75, "Red Moon /T&M GD (BBC)"},
608 {0x579a, 0x2a, 0x9373, "Price of Magik /T&M GD (BBC)"},
609
610 {0x4fd2, 0x9d, 0x799a, "Lancelot, pt. 1 GD (BBC)"},
611 {0x4dac, 0xa8, 0x86ed, "Lancelot, pt. 2 GD (BBC)"},
612 {0x4f96, 0x22, 0x30f8, "Lancelot, pt. 3 GD (BBC)"},
613
614 {0x55ce, 0xa1, 0xba12, "Scapeghost, pt. 1 GD (BBC)"},
615 {0x54a6, 0xa9, 0xc9f3, "Scapeghost, pt. 2 GD (BBC)"},
616 {0x51bc, 0xe3, 0x89c3, "Scapeghost, pt. 3 GD (BBC)"},
617
618 {0x46ec, 0x64, 0x2300, "Knight Orc, pt. 1 GD (Amstrad CPC/Spectrum +3)"},
619 {0x6140, 0x18, 0x4f66, "Knight Orc, pt. 2 GD (Amstrad CPC/Spectrum +3)"},
620 {0x640e, 0xc1, 0xfc69, "Knight Orc, pt. 3 GD (Amstrad CPC/Spectrum +3)"},
621
622 {0x5ff0, 0xf8, 0x3a13, "Gnome Ranger, pt. 1 GD (Amstrad CPC/Spectrum +3)"},
623 {0x6024, 0x01, 0xaaa9, "Gnome Ranger, pt. 2 GD (Amstrad CPC/Spectrum +3)"},
624 {0x6036, 0x3d, 0x6c6c, "Gnome Ranger, pt. 3 GD (Amstrad CPC/Spectrum +3)"},
625
626 {0x69fe, 0x56, 0xecfb, "Lords of Time /T&M GD (Amstrad CPC/Spectrum +3)"},
627 {0x6888, 0x8d, 0x7f6a, "Red Moon /T&M GD (Amstrad CPC/Spectrum +3)"},
628 {0x5a50, 0xa9, 0xa5fa, "Price of Magik /T&M GD (Amstrad CPC/Spectrum +3)"},
629
630 {0x5c7a, 0x44, 0x460e, "Lancelot, pt. 1 GD (Amstrad CPC/Spectrum +3)"},
631 {0x53a2, 0x1e, 0x2fae, "Lancelot, pt. 2 GD (Amstrad CPC/Spectrum +3)"},
632 {0x5914, 0x22, 0x4a31, "Lancelot, pt. 3 GD (Amstrad CPC/Spectrum +3)"},
633
634 {0x5a38, 0xf7, 0x876e, "Ingrid's Back, pt. 1 GD (Amstrad CPC/Spectrum +3)"},
635 {0x531a, 0xed, 0xcf3f, "Ingrid's Back, pt. 2 GD (Amstrad CPC/Spectrum +3)"},
636 {0x57e4, 0x19, 0xb354, "Ingrid's Back, pt. 3 GD (Amstrad CPC/Spectrum +3)"},
637
638 {0x5cbc, 0xa5, 0x0dbe, "Scapeghost, pt. 1 GD (Amstrad CPC/Spectrum +3)"},
639 {0x5932, 0x4e, 0xb2f5, "Scapeghost, pt. 2 GD (Amstrad CPC/Spectrum +3)"},
640 {0x5860, 0x95, 0x3227, "Scapeghost, pt. 3 GD (Amstrad CPC/Spectrum +3)"},
641
642 {0x74e0, 0x92, 0x885e, "Knight Orc, pt. 1 GD (Spectrum 128)"},
643 {0x6dbc, 0x97, 0x6f55, "Knight Orc, pt. 2 GD (Spectrum 128)"},
644 {0x7402, 0x07, 0x385f, "Knight Orc, pt. 3 GD (Spectrum 128)"},
645
646 {0x52aa, 0xdf, 0x7b5b, "Gnome Ranger, pt. 1 GD (Spectrum 128)"},
647 {0x6ffa, 0xdb, 0xdde2, "Gnome Ranger, pt. 2 GD (Spectrum 128)"},
648 {0x723a, 0x69, 0x039b, "Gnome Ranger, pt. 3 GD (Spectrum 128)"},
649
650 {0x6f1e, 0xda, 0x2ce0, "Lords of Time /T&M GD (Spectrum 128)"},
651 {0x6da0, 0xb8, 0x3802, "Red Moon /T&M GD (Spectrum 128)"},
652 {0x6108, 0xdd, 0xefe7, "Price of Magik /T&M GD (Spectrum 128)"},
653
654 {0x768c, 0xe8, 0x8fc6, "Lancelot, pt. 1 GD (Spectrum 128)"},
655 {0x76b0, 0x1d, 0x0fcd, "Lancelot, pt. 2 GD (Spectrum 128)"},
656 {0x765e, 0x4f, 0x3b73, "Lancelot, pt. 3 GD (Spectrum 128)"},
657
658 {0x76a0, 0x3a, 0xb803, "Ingrid's Back, pt. 1 GD (Spectrum 128)"},
659 {0x7674, 0x0b, 0xe92f, "Ingrid's Back, pt. 2 GD (Spectrum 128)"},
660 {0x765e, 0xba, 0x086d, "Ingrid's Back, pt. 3 GD (Spectrum 128)"},
661
662 {0x762e, 0x82, 0x8848, "Scapeghost, pt. 1 GD (Spectrum 128)"},
663 {0x5bd6, 0x35, 0x79ef, "Scapeghost, pt. 2 GD (Spectrum 128)"},
664 {0x6fa8, 0xa4, 0x62c2, "Scapeghost, pt. 3 GD (Spectrum 128)"},
665
666 {0xbb93, 0x36, 0x6a05, "Knight Orc, pt. 1 (Amiga)"},
667 {0xbb6e, 0xad, 0x4d40, "Knight Orc, pt. 1 (ST)"},
668 {0xc58e, 0x4a, 0x4e9d, "Knight Orc, pt. 2 (Amiga/ST)"},
669 {0xcb9a, 0x0f, 0x0804, "Knight Orc, pt. 3 (Amiga/ST)"},
670
671 {0xbb6e, 0xa6, 0x9753, "Knight Orc, pt. 1 (PC)"},
672 {0xc58e, 0x43, 0xe9ce, "Knight Orc, pt. 2 (PC)"},
673 {0xcb9a, 0x08, 0x6c36, "Knight Orc, pt. 3 (PC)"},
674
675 {0x898a, 0x43, 0xfc8b, "Knight Orc, pt. 1 (Apple ][)"},
676 {0x8b9f, 0x61, 0x7288, "Knight Orc, pt. 2 (Apple ][)"},
677 {0x8af9, 0x61, 0x7542, "Knight Orc, pt. 3 (Apple ][)"},
678
679 {0x8970, 0x6b, 0x3c7b, "Knight Orc, pt. 1 (Commodore 64 Gfx)"},
680 {0x8b90, 0x4e, 0x098c, "Knight Orc, pt. 2 (Commodore 64 Gfx)"},
681 {0x8aea, 0x4e, 0xca54, "Knight Orc, pt. 3 (Commodore 64 Gfx)"},
682
683 {0x86d0, 0xb7, 0xadbd, "Knight Orc, pt. 1 (Spectrum 48)"},
684 {0x8885, 0x22, 0xe293, "Knight Orc, pt. 2 (Spectrum 48)"},
685 {0x87e5, 0x0e, 0xdc33, "Knight Orc, pt. 3 (Spectrum 48)"},
686
687 {0xb92d, 0x00, 0x46cc, "Knight Orc, pt. 1 (MSX *corrupt*)"},
688 {0xb92d, 0x25, 0xd86d, "Knight Orc, pt. 1 (MSX)"},
689 {0xb734, 0xbc, 0x6729, "Knight Orc, pt. 2 (MSX)"},
690 {0xba02, 0x5f, 0x2078, "Knight Orc, pt. 3 (MSX)"},
691
692 {0xb1a9, 0x80, 0x5fb7, "Gnome Ranger, pt. 1 (Amiga/ST)"},
693 {0xab9d, 0x31, 0xbe6d, "Gnome Ranger, pt. 2 (Amiga/ST)"},
694 {0xae28, 0x87, 0xb6b6, "Gnome Ranger, pt. 3 (Amiga/ST)"},
695
696 {0xb0ec, 0xc2, 0x0053, "Gnome Ranger, pt. 1 (ST[v1])"},
697 {0xaf82, 0x83, 0x19f7, "Gnome Ranger, pt. 2 (ST[v1])"},
698
699 {0xb1aa, 0xad, 0xaf47, "Gnome Ranger, pt. 1 (PC)"},
700 {0xb19e, 0x92, 0x8f96, "Gnome Ranger, pt. 1 (ST[v2])"},
701 {0xab8b, 0xbf, 0x31e6, "Gnome Ranger, pt. 2 (PC/ST[v2])"},
702 {0xae16, 0x81, 0x8741, "Gnome Ranger, pt. 3 (PC/ST[v2])"},
703
704 {0xad41, 0xa8, 0x42c5, "Gnome Ranger, pt. 1 (Commodore 64 TO/MSX)"},
705 {0xa735, 0xf7, 0x2e08, "Gnome Ranger, pt. 2 (Commodore 64 TO/MSX)"},
706 {0xa9c0, 0x9e, 0x0d70, "Gnome Ranger, pt. 3 (Commodore 64 TO/MSX)"},
707
708 {0x908e, 0x0d, 0x58a7, "Gnome Ranger, pt. 1 (Commodore 64 Gfx)"},
709 {0x8f6f, 0x0a, 0x411a, "Gnome Ranger, pt. 2 (Commodore 64 Gfx)"},
710 {0x9060, 0xbb, 0xe75d, "Gnome Ranger, pt. 3 (Commodore 64 Gfx)"},
711
712 {0x8aab, 0xc0, 0xde5f, "Gnome Ranger, pt. 1 (Spectrum 48)"},
713 {0x8ac8, 0x9a, 0xc89b, "Gnome Ranger, pt. 2 (Spectrum 48)"},
714 {0x8a93, 0x4f, 0x10cc, "Gnome Ranger, pt. 3 (Spectrum 48)"},
715
716 {0xb57c, 0x44, 0x7779, "Lords of Time /T&M (PC)"},
717 {0xa69e, 0x6c, 0xb268, "Red Moon /T&M (PC)"},
718 {0xbac7, 0x7f, 0xddb2, "Price of Magik /T&M (PC)"},
719
720 {0xb579, 0x89, 0x3e89, "Lords of Time /T&M (ST)"},
721 {0xa698, 0x41, 0xcaca, "Red Moon /T&M (ST)"},
722 {0xbac4, 0x80, 0xa750, "Price of Magik /T&M (ST)"},
723
724 {0xb576, 0x2a, 0x7239, "Lords of Time /T&M (Amiga)"},
725 {0xa692, 0xd1, 0x6a99, "Red Moon /T&M (Amiga)"},
726 {0xbaca, 0x3a, 0x221b, "Price of Magik /T&M (Amiga)"},
727
728 {0xb563, 0x6a, 0x0c5c, "Lords of Time /T&M (Mac)"},
729 {0xa67c, 0xb8, 0xff41, "Red Moon /T&M (Mac)"},
730 {0xbab2, 0x87, 0x09f5, "Price of Magik /T&M (Mac)"},
731
732 {0xb393, 0x11, 0x25e7, "Lords of Time /T&M (MSX)"},
733 {0xa4d8, 0xd9, 0xb1eb, "Red Moon /T&M (MSX)"},
734 {0xb8b5, 0x27, 0x461a, "Price of Magik /T&M (MSX)"},
735
736 {0xb38c, 0x37, 0x9f8e, "Lords of Time /T&M (Commodore 64 TO)"},
737 {0xa4e2, 0xa6, 0x016d, "Red Moon /T&M (Commodore 64 TO)"},
738 {0xb451, 0xa8, 0x2682, "Price of Magik /T&M (Commodore 64 TO)"},
739
740 {0x9070, 0x43, 0x45d4, "Lords of Time /T&M (Commodore 64 Gfx)"},
741 {0x903f, 0x6b, 0x603e, "Red Moon /T&M (Commodore 64 Gfx)"},
742 {0x8f51, 0xb2, 0x6c9a, "Price of Magik /T&M (Commodore 64 Gfx)"},
743
744 {0x8950, 0xa1, 0xbb16, "Lords of Time /T&M (Spectrum 48)"},
745 {0x8813, 0x11, 0x22de, "Red Moon /T&M (Spectrum 48)"},
746 {0x8a60, 0x2a, 0x29ed, "Price of Magik /T&M (Spectrum 48)"},
747
748 {0xb260, 0xe5, 0xc5b2, "Lords of Time /T&M (PC/ST *USA*)"},
749 {0xa3a4, 0xdf, 0x6732, "Red Moon /T&M (PC/ST *USA*)"},
750 {0xb7a0, 0x7e, 0x2226, "Price of Magik /T&M (PC/ST *USA*)"},
751
752 {0xb257, 0xf8, 0xfbd5, "Lords of Time /T&M (Amiga *USA*)"},
753 {0xa398, 0x82, 0xd031, "Red Moon /T&M (Amiga *USA*)"},
754 {0xb797, 0x1f, 0x84a9, "Price of Magik /T&M (Amiga *USA*)"},
755
756 {0x8d78, 0x3a, 0xba6e, "Lords of Time /T&M (Commodore 64 Gfx *USA*)"},
757 {0x8d56, 0xd3, 0x146a, "Red Moon /T&M (Commodore 64 Gfx *USA*)"},
758 {0x8c46, 0xf0, 0xcaf6, "Price of Magik /T&M (Commodore 64 Gfx *USA*)"},
759
760 {0xc0cf, 0x4e, 0xb7fa, "Lancelot, pt. 1 (Amiga/PC/ST)"},
761 {0xd5e9, 0x6a, 0x4192, "Lancelot, pt. 2 (Amiga/PC/ST)"},
762 {0xbb8f, 0x1a, 0x7487, "Lancelot, pt. 3 (Amiga/PC/ST)"},
763
764 {0xc0bd, 0x57, 0x6ef1, "Lancelot, pt. 1 (Mac)"},
765 {0xd5d7, 0x99, 0x770b, "Lancelot, pt. 2 (Mac)"},
766 {0xbb7d, 0x17, 0xbc42, "Lancelot, pt. 3 (Mac)"},
767
768 {0xb4c9, 0x94, 0xd784, "Lancelot, pt. 1 (Commodore 64 TO/MSX)"},
769 {0xb729, 0x51, 0x8ee5, "Lancelot, pt. 2 (Commodore 64 TO/MSX)"},
770 {0xb702, 0xe4, 0x1809, "Lancelot, pt. 3 (Commodore 64 TO/MSX)"},
771
772 {0x8feb, 0xba, 0xa800, "Lancelot, pt. 1 (Commodore 64 Gfx)"},
773 {0x8f6b, 0xfa, 0x0f7e, "Lancelot, pt. 2 (Commodore 64 Gfx)"},
774 {0x8f71, 0x2f, 0x0ddc, "Lancelot, pt. 3 (Commodore 64 Gfx)"},
775
776 {0x8ade, 0xf2, 0xfffb, "Lancelot, pt. 1 (Spectrum 48)"},
777 {0x8b0e, 0xfb, 0x0bab, "Lancelot, pt. 2 (Spectrum 48)"},
778 {0x8ab3, 0xc1, 0xcb62, "Lancelot, pt. 3 (Spectrum 48)"},
779
780 {0xbba4, 0x94, 0x0871, "Lancelot, pt. 1 (Amiga/PC *USA*)"},
781 {0xd0c0, 0x56, 0x8c48, "Lancelot, pt. 2 (Amiga/PC *USA*)"},
782 {0xb6ac, 0xc6, 0xaea0, "Lancelot, pt. 3 (Amiga/PC *USA*)"},
783
784 {0x8afc, 0x07, 0x8321, "Lancelot, pt. 1 (Commodore 64 Gfx *USA*)"},
785 {0x8aec, 0x13, 0x6791, "Lancelot, pt. 2 (Commodore 64 Gfx *USA*)"},
786 {0x8aba, 0x0d, 0x5602, "Lancelot, pt. 3 (Commodore 64 Gfx *USA*)"},
787
788 {0xd19b, 0xad, 0x306d, "Ingrid's Back, pt. 1 (PC)"},
789 {0xc5a5, 0xfe, 0x3c98, "Ingrid's Back, pt. 2 (PC)"},
790 {0xd7ae, 0x9e, 0x1878, "Ingrid's Back, pt. 3 (PC)"},
791
792 {0xd188, 0x13, 0xdc60, "Ingrid's Back, pt. 1 (Amiga)"},
793 {0xc594, 0x03, 0xea95, "Ingrid's Back, pt. 2 (Amiga)"},
794 {0xd79f, 0xb5, 0x1661, "Ingrid's Back, pt. 3 (Amiga)"},
795
796 {0xd183, 0x83, 0xef72, "Ingrid's Back, pt. 1 (ST)"},
797 {0xc58f, 0x65, 0xf337, "Ingrid's Back, pt. 2 (ST)"},
798 {0xd79a, 0x57, 0x49c5, "Ingrid's Back, pt. 3 (ST)"},
799
800 {0xb770, 0x03, 0x9a03, "Ingrid's Back, pt. 1 (Commodore 64 TO)"},
801 {0xb741, 0xb6, 0x2aa5, "Ingrid's Back, pt. 2 (Commodore 64 TO)"},
802 {0xb791, 0xa1, 0xd065, "Ingrid's Back, pt. 3 (Commodore 64 TO)"},
803
804 {0x9089, 0xce, 0xc5e2, "Ingrid's Back, pt. 1 (Commodore 64 Gfx)"},
805 {0x908d, 0x80, 0x30c7, "Ingrid's Back, pt. 2 (Commodore 64 Gfx)"},
806 {0x909e, 0x9f, 0xdecc, "Ingrid's Back, pt. 3 (Commodore 64 Gfx)"},
807
808 {0x8ab7, 0x68, 0xee57, "Ingrid's Back, pt. 1 (Spectrum 48)"},
809 {0x8b1e, 0x84, 0x2538, "Ingrid's Back, pt. 2 (Spectrum 48)"},
810 {0x8b1c, 0xa8, 0x9262, "Ingrid's Back, pt. 3 (Spectrum 48)"},
811
812 {0xbefa, 0x1e, 0x2cdd, "Ingrid's Back, pt. 1 (MSX)"},
813 {0xbd57, 0x14, 0x7fe7, "Ingrid's Back, pt. 2 (MSX)"},
814 {0xbf4b, 0x9f, 0xad8c, "Ingrid's Back, pt. 3 (MSX)"},
815
816 {0xbeab, 0x2d, 0x94d9, "Scapeghost, pt. 1 (Amiga)"},
817 {0xc132, 0x14, 0x7adc, "Scapeghost, pt. 1 (Amiga *bak*)"},
818 {0xbe94, 0xcc, 0x04b8, "Scapeghost, pt. 1 (PC/ST)"},
819 {0x99bd, 0x65, 0x032e, "Scapeghost, pt. 2 (Amiga/PC/ST)"},
820 {0xbcb6, 0x7a, 0x7d4f, "Scapeghost, pt. 3 (Amiga/PC/ST)"},
821
822 {0xb613, 0x4c, 0x6311, "Scapeghost, pt. 1 (Commodore 64 TO/MSX *converted*)"},
823 {0x97c0, 0x48, 0xbf7f, "Scapeghost, pt. 2 (Commodore 64 TO/MSX *converted*)"},
824 {0xb60e, 0x6a, 0x7eac, "Scapeghost, pt. 3 (Commodore 64 TO/MSX *converted*)"},
825
826 {0x9058, 0xcf, 0x9748, "Scapeghost, pt. 1 (Commodore 64 Gfx)"},
827 {0x8f43, 0xc9, 0xeefd, "Scapeghost, pt. 2 (Commodore 64 Gfx)"},
828 {0x90ac, 0x68, 0xb4a8, "Scapeghost, pt. 3 (Commodore 64 Gfx)"},
829
830 {0x8a21, 0xf4, 0xd9e4, "Scapeghost, pt. 1 (Spectrum 48)"},
831 {0x8a12, 0xe3, 0xc2ff, "Scapeghost, pt. 2 (Spectrum 48)"},
832 {0x8a16, 0xcc, 0x4f3b, "Scapeghost, pt. 3 (Spectrum 48)"},
833
834 {0x3ebb, 0x00, 0xf6dc, "Champion of the Raj (English) 1/2 GD (Amiga)"},
835 {0x0fd8, 0x00, 0xf250, "Champion of the Raj (English) 2/2 GD (Amiga)"},
836
837 {0x3e8f, 0x00, 0x5599, "Champion of the Raj (English) 1/2 GD (ST)"},
838
839 {0x3e4f, 0x00, 0xb202, "Champion of the Raj (English) 1/2 GD (PC)"},
840 {0x14a3, 0x00, 0xa288, "Champion of the Raj (English) 2/2 GD (PC)"},
841
842 {0x1929, 0x00, 0xd4b2, "Champion of the Raj (demo), 1/2 GD (ST)"},
843 {0x40e0, 0x02, 0x080d, "Champion of the Raj (demo), 2/2 GD (ST)"},
844
845 {0x4872, 0x00, 0x9515, "Champion of the Raj (German) 1/2 GD (Amiga)"},
846 {0x11f5, 0x00, 0xbf39, "Champion of the Raj (German) 2/2 GD (Amiga)"},
847
848 {0x4846, 0x00, 0xd9c1, "Champion of the Raj (German) 1/2 GD (ST)"},
849 {0x11f5, 0x00, 0x7aa4, "Champion of the Raj (German) 2/2 GD (ST)"},
850
851 {0x110f, 0x00, 0x4b57, "Champion of the Raj (French) 2/2 GD (ST)"},
852
853 {0x0000, 0x00, 0x0000, NULL}
854 };
855
856
857 /*
858 * The following patch database is obtained from L9cut's l9data_p.h, and
859 * allows CRCs from patched games to be translated into original CRCs for
860 * lookup in the game database above. Some file commentary has been removed
861 * for brevity, and unused patch fields deleted.
862 *
863 * The version of l9data_p.h used is 012 (22 May 2001).
864 */
865 typedef const struct
866 {
867 const gln_uint16 length; /* Datafile length in bytes */
868 const gln_byte orig_checksum; /* 8-bit checksum, last datafile byte */
869 const gln_uint16 orig_crc; /* 16-bit CRC, L9cut-internal */
870 const gln_byte patch_checksum; /* 8-bit checksum, last datafile byte */
871 const gln_uint16 patch_crc; /* 16-bit CRC, L9cut-internal */
872 } gln_patch_table_t;
873 typedef gln_patch_table_t *gln_patch_tableref_t;
874
875 static gln_patch_table_t GLN_PATCH_TABLE[] = {
876 /* Price of Magik (Spectrum128) */
877 {0x7410, 0x5e, 0x60be, 0x70, 0x6cef},
878
879 /* Price of Magik (Commodore 64) */
880 {0x6fc6, 0x14, 0xf9b6, 0x26, 0x3326},
881
882 /* Price of Magik (MSX) */
883 {0x7334, 0x87, 0x8b5d, 0x99, 0x880c},
884
885 /* Price of Magik (Spectrum48) */
886 {0x5aa4, 0xc1, 0xeda4, 0xd3, 0xed35},
887 {0x5aa4, 0xc1, 0xeda4, 0xc1, 0x8a65},
888
889 /* Colossal Adventure /JoD (Amiga/PC) */
890 {0x76f4, 0x5e, 0x1fe5, 0xea, 0x1305},
891 {0x76f4, 0x5e, 0x1fe5, 0xb5, 0x901f},
892 {0x76f4, 0x5e, 0x1fe5, 0x5e, 0x6ea1},
893
894 /* Colossal Adventure /JoD (ST) */
895 {0x76f4, 0x5a, 0xcf4b, 0xe6, 0x012a},
896 {0x76f4, 0x5a, 0xcf4b, 0xb1, 0x40b1},
897
898 /* Adventure Quest /JoD (Amiga/PC) */
899 {0x6e60, 0x83, 0x18e0, 0x4c, 0xcfb0},
900 {0x6e60, 0x83, 0x18e0, 0xfa, 0x9b3b},
901 {0x6e60, 0x83, 0x18e0, 0x83, 0x303d},
902
903 /* Adventure Quest /JoD (ST) */
904 {0x6e5c, 0xf6, 0xd356, 0xbf, 0xede7},
905 {0x6e5c, 0xf6, 0xd356, 0x6d, 0x662d},
906
907 /* Dungeon Adventure /JoD (Amiga/PC/ST) */
908 {0x6f0c, 0x95, 0x1f64, 0x6d, 0x2443},
909 {0x6f0c, 0x95, 0x1f64, 0x0c, 0x6066},
910 {0x6f0c, 0x95, 0x1f64, 0x96, 0xdaca},
911 {0x6f0c, 0x95, 0x1f64, 0x95, 0x848d},
912
913 /* Colossal Adventure /JoD (Spectrum128) */
914 {0x6f6e, 0x78, 0x28cd, 0xf8, 0xda5f},
915 {0x6f6e, 0x78, 0x28cd, 0x77, 0x5b4e},
916
917 /* Adventure Quest /JoD (Spectrum128) */
918 {0x6970, 0xd6, 0xa820, 0x3b, 0x1870},
919 {0x6970, 0xd6, 0xa820, 0xd5, 0x13c4},
920
921 /* Dungeon Adventure /JoD (Spectrum128) */
922 {0x6de8, 0x4c, 0xd795, 0xa2, 0x3eea},
923 {0x6de8, 0x4c, 0xd795, 0x4b, 0xad30},
924
925 /* Colossal Adventure /JoD (Amstrad CPC) */
926 {0x6f4d, 0xcb, 0xe8f2, 0x4b, 0xb384},
927 {0x6f4d, 0xcb, 0xe8f2, 0xca, 0x96e7},
928
929 /* Adventure Quest /JoD (Amstrad CPC) */
930 {0x6968, 0x32, 0x0c01, 0x97, 0xdded},
931 {0x6968, 0x32, 0x0c01, 0x31, 0xe8c2},
932
933 /* Dungeon Adventure /JoD (Amstrad CPC) */
934 {0x6dc0, 0x63, 0x5d95, 0xb9, 0xc963},
935 {0x6dc0, 0x63, 0x5d95, 0x62, 0x79f7},
936
937 /* Colossal Adventure /JoD (Commodore 64) */
938 {0x6c8e, 0xb6, 0x9be3, 0x36, 0x6971},
939 {0x6c8e, 0xb6, 0x9be3, 0xb5, 0xeba0},
940
941 /* Adventure Quest /JoD (Commodore 64) */
942 {0x63b6, 0x2e, 0xef38, 0x93, 0x4e68},
943 {0x63b6, 0x2e, 0xef38, 0x2d, 0x54dc},
944
945 /* Dungeon Adventure /JoD (Commodore 64) */
946 {0x6bd2, 0x65, 0xa41f, 0xbb, 0x4260},
947 {0x6bd2, 0x65, 0xa41f, 0x64, 0xdf5a},
948
949 /* Colossal Adventure /JoD (Spectrum48) */
950 {0x5a8e, 0xf2, 0x7cca, 0x72, 0x8e58},
951 {0x5a8e, 0xf2, 0x7cca, 0xf1, 0x0c89},
952 {0x5a8e, 0xf2, 0x7cca, 0xf2, 0x2c96},
953
954 /* Adventure Quest /JoD (Spectrum48) */
955 {0x5ace, 0x11, 0xdc12, 0x76, 0x8663},
956 {0x5ace, 0x11, 0xdc12, 0x10, 0xa757},
957 {0x5ace, 0x11, 0xdc12, 0x11, 0xf118},
958
959 /* Dungeon Adventure /JoD (Spectrum48) */
960 {0x58a3, 0x38, 0x8ce4, 0x8e, 0xb61a},
961 {0x58a3, 0x38, 0x8ce4, 0x37, 0x34c0},
962 {0x58a3, 0x38, 0x8ce4, 0x38, 0xa1ee},
963
964 /* Colossal Adventure /JoD (MSX) */
965 {0x6f70, 0x40, 0xbd91, 0xc0, 0xcaba},
966 {0x6f70, 0x40, 0xbd91, 0x40, 0x7f59},
967
968 /* Adventure Quest /JoD (MSX) */
969 {0x6972, 0x55, 0x042e, 0xba, 0x74df},
970 {0x6972, 0x55, 0x042e, 0x55, 0x0933},
971
972 /* Dungeon Adventure /JoD (MSX) */
973 {0x6dea, 0x50, 0xe4f7, 0xa6, 0x0a08},
974 {0x6dea, 0x50, 0xe4f7, 0x50, 0xc951},
975
976 /* Snowball /SD (Amiga/ST) */
977 {0x7b31, 0x6e, 0x2e2b, 0xe5, 0x6017},
978
979 /* Return to Eden /SD (Amiga/ST) */
980 {0x7d16, 0xe6, 0x5438, 0x5d, 0xc770},
981
982 /* Worm in Paradise /SD (Amiga/ST) */
983 {0x7cd9, 0x0c, 0x4df1, 0x83, 0xe997},
984
985 /* Snowball /SD (PC/Spectrum128) */
986 {0x7b2f, 0x70, 0x6955, 0xe7, 0x0af4},
987 {0x7b2f, 0x70, 0x6955, 0x70, 0x1179},
988
989 /* Return to Eden /SD (PC) */
990 {0x7d14, 0xe8, 0xfbab, 0x5f, 0xeab9},
991 {0x7d14, 0xe8, 0xfbab, 0xe8, 0xe216},
992
993 /* Return to Eden /SD (Amstrad CPC) */
994 {0x7cff, 0xf8, 0x6044, 0x6f, 0xbb57},
995
996 /* Return to Eden /SD (Spectrum128) */
997 {0x7c55, 0x18, 0xdaee, 0x8f, 0x01fd},
998
999 /* Worm in Paradise /SD (Amstrad CPC/PC/Spectrum128) */
1000 {0x7cd7, 0x0e, 0x4feb, 0x85, 0x4eae},
1001 {0x7cd7, 0x0e, 0x4feb, 0x0e, 0xb02c},
1002
1003 /* Snowball /SD (Commodore 64/MSX) */
1004 {0x7363, 0x65, 0xa0ab, 0xdc, 0xca6a},
1005 {0x7363, 0x65, 0xa0ab, 0x65, 0xc017},
1006
1007 /* Return to Eden /SD (Commodore 64/MSX) */
1008 {0x772f, 0xca, 0x8602, 0x41, 0x9bd0},
1009 {0x772f, 0xca, 0x8602, 0xca, 0x150c},
1010
1011 /* Worm in Paradise /SD (Commodore 64/MSX) */
1012 {0x788d, 0x72, 0x888a, 0xe9, 0x4cce},
1013 {0x788d, 0x72, 0x888a, 0x72, 0xc3bd},
1014
1015 /* Snowball /SD (Atari) */
1016 {0x6bf8, 0x3f, 0xc9f7, 0x96, 0x1908},
1017
1018 /* Return to Eden /SD (Atari) */
1019 {0x60f7, 0x68, 0xc2bc, 0xdf, 0xd3ae},
1020
1021 /* Worm in Paradise /SD (Atari) */
1022 {0x6161, 0xf3, 0xe6d7, 0x6a, 0xe232},
1023
1024 /* Snowball /SD (Spectrum48) */
1025 {0x6541, 0x02, 0x2e6c, 0x79, 0xb80c},
1026 {0x6541, 0x02, 0x2e6c, 0x02, 0x028a},
1027
1028 /* Return to Eden /SD (Spectrum48) */
1029 {0x5f43, 0xca, 0x828c, 0x41, 0x9f5e},
1030 {0x5f43, 0xca, 0x828c, 0xca, 0x6e1b},
1031
1032 /* Worm in Paradise /SD (Spectrum48) */
1033 {0x5ebb, 0xf1, 0x4dec, 0x68, 0x4909},
1034 {0x5ebb, 0xf1, 0x4dec, 0xf1, 0xcc1a},
1035
1036 /* Knight Orc, pt. 1 (Amiga) */
1037 {0xbb93, 0x36, 0x6a05, 0xad, 0xe52d},
1038
1039 /* Knight Orc, pt. 1 (ST) */
1040 {0xbb6e, 0xad, 0x4d40, 0x24, 0x3bcd},
1041
1042 /* Knight Orc, pt. 2 (Amiga/ST) */
1043 {0xc58e, 0x4a, 0x4e9d, 0xc1, 0xe2bf},
1044
1045 /* Knight Orc, pt. 3 (Amiga/ST) */
1046 {0xcb9a, 0x0f, 0x0804, 0x86, 0x6487},
1047
1048 /* Knight Orc, pt. 1 (PC) */
1049 {0xbb6e, 0xa6, 0x9753, 0x1d, 0x2e7f},
1050 {0xbb6e, 0xa6, 0x9753, 0xa6, 0x001d},
1051
1052 /* Knight Orc, pt. 2 (PC) */
1053 {0xc58e, 0x43, 0xe9ce, 0xba, 0x5e4c},
1054 {0xc58e, 0x43, 0xe9ce, 0x43, 0xa8f0},
1055
1056 /* Knight Orc, pt. 3 (PC) */
1057 {0xcb9a, 0x08, 0x6c36, 0x7f, 0xf0d4},
1058 {0xcb9a, 0x08, 0x6c36, 0x08, 0x2d08},
1059
1060 /* Knight Orc, pt. 1 (Commodore 64 Gfx) */
1061 {0x8970, 0x6b, 0x3c7b, 0xe2, 0xb6f3},
1062
1063 /* Knight Orc, pt. 1 (Spectrum48) */
1064 {0x86d0, 0xb7, 0xadbd, 0x2e, 0x43e1},
1065
1066 /* Knight Orc, pt. 1 (MSX) */
1067 {0xb92d, 0x25, 0xd86d, 0x25, 0xc5d9},
1068 {0xb92d, 0x25, 0xd86d, 0x9c, 0xa1e0},
1069
1070 /* Knight Orc, pt. 2 (MSX) */
1071 {0xb734, 0xbc, 0x6729, 0xbc, 0xdacb},
1072 {0xb734, 0xbc, 0x6729, 0x33, 0xb851},
1073
1074 /* Knight Orc, pt. 3 (MSX) */
1075 {0xba02, 0x5f, 0x2078, 0x5f, 0x9d9a},
1076 {0xba02, 0x5f, 0x2078, 0xd6, 0xfee0},
1077
1078 /* Gnome Ranger, pt. 1 (Amiga/ST) */
1079 {0xb1a9, 0x80, 0x5fb7, 0xf7, 0x5c6c},
1080
1081 /* Gnome Ranger, pt. 2 (Amiga/ST) */
1082 {0xab9d, 0x31, 0xbe6d, 0xa8, 0xcb96},
1083
1084 /* Gnome Ranger, pt. 3 (Amiga/ST) */
1085 {0xae28, 0x87, 0xb6b6, 0xfe, 0x760c},
1086
1087 /* Gnome Ranger, pt. 1 (PC) */
1088 {0xb1aa, 0xad, 0xaf47, 0x24, 0x5cfd},
1089 {0xb1aa, 0xad, 0xaf47, 0xad, 0xe0ed},
1090
1091 /* Gnome Ranger, pt. 1 (ST-var) */
1092 {0xb19e, 0x92, 0x8f96, 0x09, 0x798c},
1093
1094 /* Gnome Ranger, pt. 2 (PC/ST-var) */
1095 {0xab8b, 0xbf, 0x31e6, 0x36, 0x811c},
1096 {0xab8b, 0xbf, 0x31e6, 0xbf, 0x8ff3},
1097
1098 /* Gnome Ranger, pt. 3 (PC/ST-var) */
1099 {0xae16, 0x81, 0x8741, 0xf8, 0x47fb},
1100 {0xae16, 0x81, 0x8741, 0x81, 0xc8eb},
1101
1102 /* Gnome Ranger, pt. 1 (Commodore 64 TO/MSX) */
1103 {0xad41, 0xa8, 0x42c5, 0x1f, 0x7d1e},
1104
1105 /* Gnome Ranger, pt. 2 (Commodore 64 TO/MSX) */
1106 {0xa735, 0xf7, 0x2e08, 0x6e, 0x780e},
1107
1108 /* Gnome Ranger, pt. 3 (Commodore 64 TO/MSX) */
1109 {0xa9c0, 0x9e, 0x0d70, 0x15, 0x3e6b},
1110
1111 /* Gnome Ranger, pt. 1 (Commodore 64 Gfx) */
1112 {0x908e, 0x0d, 0x58a7, 0x84, 0xab1d},
1113
1114 /* Gnome Ranger, pt. 2 (Commodore 64 Gfx) */
1115 {0x8f6f, 0x0a, 0x411a, 0x81, 0x12bc},
1116
1117 /* Gnome Ranger, pt. 3 (Commodore 64 Gfx) */
1118 {0x9060, 0xbb, 0xe75d, 0x32, 0x14e7},
1119
1120 /* Lords of Time /T&M (PC) */
1121 {0xb57c, 0x44, 0x7779, 0xbb, 0x31a6},
1122 {0xb57c, 0x44, 0x7779, 0x44, 0xea72},
1123
1124 /* Red Moon /T&M (PC) */
1125 {0xa69e, 0x6c, 0xb268, 0xe3, 0x4cef},
1126 {0xa69e, 0x6c, 0xb268, 0x6c, 0x3799},
1127
1128 /* Price of Magik /T&M (PC) */
1129 {0xbac7, 0x7f, 0xddb2, 0xf6, 0x6ab3},
1130 {0xbac7, 0x7f, 0xddb2, 0x7f, 0x905c},
1131
1132 /* Lords of Time /T&M (ST) */
1133 {0xb579, 0x89, 0x3e89, 0x00, 0xa2b7},
1134
1135 /* Red Moon /T&M (ST) */
1136 {0xa698, 0x41, 0xcaca, 0xb8, 0xeeac},
1137
1138 /* Price of Magik /T&M (ST) */
1139 {0xbac4, 0x80, 0xa750, 0xf7, 0xe030},
1140
1141 /* Lords of Time /T&M (Amiga) */
1142 {0xb576, 0x2a, 0x7239, 0xa1, 0x2ea6},
1143
1144 /* Red Moon /T&M (Amiga) */
1145 {0xa692, 0xd1, 0x6a99, 0x48, 0x50ff},
1146
1147 /* Price of Magik /T&M (Amiga) */
1148 {0xbaca, 0x3a, 0x221b, 0xb1, 0x55bb},
1149
1150 /* Lords of Time /T&M (MSX) */
1151 {0xb393, 0x11, 0x25e7, 0xea, 0xf09e},
1152
1153 /* Red Moon /T&M (MSX) */
1154 {0xa4d8, 0xd9, 0xb1eb, 0xb1, 0x5eed},
1155
1156 /* Price of Magik /T&M (MSX) */
1157 {0xb8b5, 0x27, 0x461a, 0xde, 0x1f6d},
1158
1159 /* Lords of Time /T&M (Commodore 64 TO) */
1160 {0xb38c, 0x37, 0x9f8e, 0xae, 0xc6b1},
1161
1162 /* Red Moon /T&M (Commodore 64 TO) */
1163 {0xa4e2, 0xa6, 0x016d, 0x1d, 0x31ab},
1164
1165 /* Price of Magik /T&M (Commodore 64 TO) */
1166 {0xb451, 0xa8, 0x2682, 0x1f, 0x5de2},
1167
1168 /* Lords of Time /T&M (Commodore 64 Gfx) */
1169 {0x9070, 0x43, 0x45d4, 0xba, 0x02eb},
1170
1171 /* Red Moon /T&M (Commodore 64 Gfx) */
1172 {0x903f, 0x6b, 0x603e, 0xe2, 0x9f59},
1173
1174 /* Price of Magik /T&M (Commodore 64 Gfx) */
1175 {0x8f51, 0xb2, 0x6c9a, 0x29, 0xde3b},
1176
1177 /* Lords of Time /T&M (Spectrum48) */
1178 {0x8950, 0xa1, 0xbb16, 0x18, 0x2828},
1179 {0x8950, 0xa1, 0xbb16, 0xa1, 0x1ea2},
1180
1181 /* Red Moon /T&M (Spectrum48) */
1182 {0x8813, 0x11, 0x22de, 0x88, 0x18b8},
1183 {0x8813, 0x11, 0x22de, 0x11, 0xd0cd},
1184
1185 /* Price of Magik /T&M (Spectrum48) */
1186 {0x8a60, 0x2a, 0x29ed, 0xa1, 0x5e4d},
1187
1188 /* Lancelot, pt. 1 (Amiga/PC/ST) */
1189 {0xc0cf, 0x4e, 0xb7fa, 0xc5, 0x4400},
1190
1191 /* Lancelot, pt. 2 (Amiga/PC/ST) */
1192 {0xd5e9, 0x6a, 0x4192, 0xe1, 0x3b1e},
1193
1194 /* Lancelot, pt. 3 (Amiga/PC/ST) */
1195 {0xbb8f, 0x1a, 0x7487, 0x91, 0x877d},
1196
1197 /* Lancelot, pt. 1 (Commodore 64 TO/MSX) */
1198 {0xb4c9, 0x94, 0xd784, 0x0b, 0x203e},
1199
1200 /* Lancelot, pt. 2 (Commodore 64 TO/MSX) */
1201 {0xb729, 0x51, 0x8ee5, 0x6d, 0xba10},
1202 {0xb729, 0x51, 0x8ee5, 0xc8, 0xf1c9},
1203
1204 /* Lancelot, pt. 3 (Commodore 64 TO/MSX) */
1205 {0xb702, 0xe4, 0x1809, 0x5b, 0x25b2},
1206
1207 /* Lancelot, pt. 1 (Commodore 64 Gfx) */
1208 {0x8feb, 0xba, 0xa800, 0x31, 0x5bfa},
1209
1210 /* Lancelot, pt. 2 (Commodore 64 Gfx) */
1211 {0x8f6b, 0xfa, 0x0f7e, 0x71, 0x75f2},
1212
1213 /* Lancelot, pt. 3 (Commodore 64 Gfx) */
1214 {0x8f71, 0x2f, 0x0ddc, 0xa6, 0x3e87},
1215
1216 /* Ingrid's Back, pt. 1 (PC) */
1217 {0xd19b, 0xad, 0x306d, 0x24, 0x4504},
1218 {0xd19b, 0xad, 0x306d, 0xad, 0x878e},
1219
1220 /* Ingrid's Back, pt. 2 (PC) */
1221 {0xc5a5, 0xfe, 0x3c98, 0x75, 0x8950},
1222 {0xc5a5, 0xfe, 0x3c98, 0xfe, 0x8b7b},
1223
1224 /* Ingrid's Back, pt. 3 (PC) */
1225 {0xd7ae, 0x9e, 0x1878, 0x15, 0xadb0},
1226 {0xd7ae, 0x9e, 0x1878, 0x9e, 0xaf9b},
1227
1228 /* Ingrid's Back, pt. 1 (Amiga) */
1229 {0xd188, 0x13, 0xdc60, 0x8a, 0x755c},
1230
1231 /* Ingrid's Back, pt. 2 (Amiga) */
1232 {0xc594, 0x03, 0xea95, 0x7a, 0xb5a8},
1233
1234 /* Ingrid's Back, pt. 3 (Amiga) */
1235 {0xd79f, 0xb5, 0x1661, 0x2c, 0xbf5d},
1236
1237 /* Ingrid's Back, pt. 1 (ST) */
1238 {0xd183, 0x83, 0xef72, 0xfa, 0xb04f},
1239
1240 /* Ingrid's Back, pt. 2 (ST) */
1241 {0xc58f, 0x65, 0xf337, 0xdc, 0x900a},
1242
1243 /* Ingrid's Back, pt. 3 (ST) */
1244 {0xd79a, 0x57, 0x49c5, 0xce, 0xe0f9},
1245
1246 /* Ingrid's Back, pt. 1 (Commodore 64 TO) */
1247 {0xb770, 0x03, 0x9a03, 0x7a, 0xdc6a},
1248
1249 /* Ingrid's Back, pt. 2 (Commodore 64 TO) */
1250 {0xb741, 0xb6, 0x2aa5, 0x2d, 0x5a6c},
1251
1252 /* Ingrid's Back, pt. 3 (Commodore 64 TO) */
1253 {0xb791, 0xa1, 0xd065, 0x18, 0xaa0c},
1254
1255 /* Ingrid's Back, pt. 1 (Commodore 64 Gfx) */
1256 {0x9089, 0xce, 0xc5e2, 0x44, 0xeff4},
1257
1258 /* Ingrid's Back, pt. 2 (Commodore 64 Gfx) */
1259 {0x908d, 0x80, 0x30c7, 0xf6, 0x2a11},
1260
1261 /* Ingrid's Back, pt. 3 (Commodore 64 Gfx) */
1262 {0x909e, 0x9f, 0xdecc, 0x15, 0xf4da},
1263
1264 /* Ingrid's Back, pt. 1 (MSX) */
1265 {0xbefa, 0x1e, 0x2cdd, 0x95, 0x9915},
1266
1267 /* Ingrid's Back, pt. 2 (MSX) */
1268 {0xbd57, 0x14, 0x7fe7, 0x8b, 0xce6f},
1269
1270 /* Ingrid's Back, pt. 3 (MSX) */
1271 {0xbf4b, 0x9f, 0xad8c, 0x16, 0xd8e5},
1272
1273 {0x0000, 0x00, 0x0000, 0x00, 0x0000},
1274 };
1275
1276
1277 /*
1278 * gln_gameid_lookup_game()
1279 * gln_gameid_lookup_patch()
1280 *
1281 * Look up and return game table and patch table entries given a game's
1282 * length, checksum, and CRC. Returns the entry, or NULL if not found.
1283 */
1284 static gln_game_tableref_t
1285 gln_gameid_lookup_game (gln_uint16 length, gln_byte checksum,
1286 gln_uint16 crc, int ignore_crc)
1287 {
1288 gln_game_tableref_t game;
1289
1290 for (game = GLN_GAME_TABLE; game->length; game++)
1291 {
1292 if (game->length == length && game->checksum == checksum
1293 && (ignore_crc || game->crc == crc))
1294 break;
1295 }
1296
1297 return game->length ? game : NULL;
1298 }
1299
1300 static gln_patch_tableref_t
1301 gln_gameid_lookup_patch (gln_uint16 length, gln_byte checksum,
1302 gln_uint16 crc)
1303 {
1304 gln_patch_tableref_t patch;
1305
1306 for (patch = GLN_PATCH_TABLE; patch->length; patch++)
1307 {
1308 if (patch->length == length && patch->patch_checksum == checksum
1309 && patch->patch_crc == crc)
1310 break;
1311 }
1312
1313 return patch->length ? patch : NULL;
1314 }
1315
1316
1317 /*
1318 * gln_gameid_identify_game()
1319 *
1320 * Identify a game from its data length, checksum, and CRC. Returns the
1321 * entry of the game in the game table, or NULL if not found.
1322 *
1323 * This function uses startdata and FileSize from the core interpreter.
1324 * These aren't advertised symbols, so be warned.
1325 */
1326 static gln_game_tableref_t
1327 gln_gameid_identify_game (void)
1328 {
1329 gln_uint16 length, crc;
1330 gln_byte checksum;
1331 int is_version2;
1332 gln_game_tableref_t game;
1333 gln_patch_tableref_t patch;
1334
1335 /* Handle v1 games */
1336 if (L9V1Game >= 0) {
1337 assert((unsigned)L9V1Game < sizeof (GLN_V1GAME_TABLE) / sizeof (GLN_V1GAME_TABLE[0]));
1338 return &GLN_V1GAME_TABLE[L9V1Game];
1339 }
1340
1341 /* If the data file appears too short for a header, give up now. */
1342 if (FileSize < 30)
1343 return NULL;
1344
1345 /*
1346 * Find the version of the game, and the length of game data. This logic
1347 * is taken from L9cut, with calcword() replaced by simple byte comparisons.
1348 * If the length exceeds the available data, fail.
1349 * The alternative conditions are exceptional with Colossal Adventure v2 for MSX.
1350 */
1351 assert (startdata);
1352 is_version2 = ((startdata[4] == 0x20 && startdata[5] == 0x00)
1353 || (startdata[6] == 0x20 && startdata[7] == 0x00))
1354 && ((startdata[10] == 0x00 && startdata[11] == 0x80)
1355 || (startdata[8] == 0x00 && startdata[9] == 0x80))
1356 && startdata[20] == startdata[22]
1357 && startdata[21] == startdata[23];
1358
1359 length = is_version2
1360 ? startdata[28] | startdata[29] << CHAR_BIT
1361 : startdata[0] | startdata[1] << CHAR_BIT;
1362 if (length >= FileSize)
1363 return NULL;
1364
1365 /* Calculate or retrieve the checksum, in a version specific way. */
1366 if (is_version2)
1367 {
1368 int index;
1369
1370 checksum = 0;
1371 for (index = 0; index < length + 1; index++)
1372 checksum += startdata[index];
1373 }
1374 else
1375 checksum = startdata[length];
1376
1377 /*
1378 * Generate a CRC for this data. When L9cut calculates a CRC, it's using a
1379 * copy taken up to length + 1 and then padded with two NUL bytes, so we
1380 * mimic that here.
1381 */
1382 crc = gln_get_buffer_crc (startdata, length + 1, 2);
1383
1384 /*
1385 * See if this is a patched file. If it is, look up the game based on the
1386 * original CRC and checksum. If not, use the current CRC and checksum.
1387 */
1388 patch = gln_gameid_lookup_patch (length, checksum, crc);
1389 game = gln_gameid_lookup_game (length,
1390 patch ? patch->orig_checksum : checksum,
1391 patch ? patch->orig_crc : crc,
1392 FALSE);
1393
1394 /* If no game identified, retry without the CRC. This is guesswork. */
1395 if (!game)
1396 game = gln_gameid_lookup_game (length, checksum, crc, TRUE);
1397
1398 return game;
1399 }
1400
1401
1402 /*
1403 * gln_gameid_get_game_name()
1404 *
1405 * Return the name of the game, or NULL if not identifiable.
1406 *
1407 * This function uses startdata from the core interpreter. This isn't an
1408 * advertised symbol, so be warned.
1409 */
1410 static const char *
1411 gln_gameid_get_game_name (void)
1412 {
1413 /*
1414 * If no game name yet known, attempt to identify the game. If it can't
1415 * be identified, set the cached game name to "" -- this special value
1416 * indicates that the game is an unknown one, but suppresses repeated
1417 * attempts to identify it on successive calls.
1418 */
1419 if (!gln_gameid_game_name)
1420 {
1421 gln_game_tableref_t game;
1422
1423 /*
1424 * If the interpreter hasn't yet loaded a game, startdata is NULL
1425 * (uninitialized, global). In this case, we return NULL, allowing
1426 * for retries until a game is loaded.
1427 */
1428 if (!startdata)
1429 return NULL;
1430
1431 game = gln_gameid_identify_game ();
1432 gln_gameid_game_name = game ? game->name : "";
1433 }
1434
1435 /* Return the game's name, or NULL if it was unidentifiable. */
1436 assert (gln_gameid_game_name);
1437 return strlen (gln_gameid_game_name) > 0 ? gln_gameid_game_name : NULL;
1438 }
1439
1440
1441 /*
1442 * gln_gameid_game_name_reset()
1443 *
1444 * Clear the saved game name, forcing a new lookup when next queried. This
1445 * function should be called by actions that may cause the interpreter to
1446 * change game file, for example os_set_filenumber().
1447 */
1448 static void
1449 gln_gameid_game_name_reset (void)
1450 {
1451 gln_gameid_game_name = NULL;
1452 }
1453
1454
1455 /*---------------------------------------------------------------------*/
1456 /* Glk port bitmap picture functions */
1457 /*---------------------------------------------------------------------*/
1458
1459 /* R,G,B color triple definition. */
1460 typedef struct
1461 {
1462 int red, green, blue;
1463 } gln_rgb_t;
1464 typedef gln_rgb_t *gln_rgbref_t;
1465
1466 /*
1467 * Maximum number of regions to consider in a single repaint pass. A
1468 * couple of hundred seems to strike the right balance between not too
1469 * sluggardly picture updates, and responsiveness to input during graphics
1470 * rendering, when combined with short timeouts.
1471 */
1472 static const int GLN_REPAINT_LIMIT = 256;
1473
1474 /*
1475 * Graphics timeout; we like an update call after this period (ms). In
1476 * practice, this timeout may actually be shorter than the time taken
1477 * to reach the limit on repaint regions, but because Glk guarantees that
1478 * user interactions (in this case, line events) take precedence over
1479 * timeouts, this should be okay; we'll still see a game that responds to
1480 * input each time the background repaint function yields.
1481 *
1482 * Setting this value is tricky. We'd like it to be the shortest possible
1483 * consistent with getting other stuff done, say 10ms. However, Xglk has
1484 * a granularity of 50ms on checking for timeouts, as it uses a 1/20s
1485 * timeout on X select. This means that the shortest timeout we'll ever
1486 * get from Xglk will be 50ms, so there's no point in setting this shorter
1487 * than that. With luck, other Glk libraries will be more efficient than
1488 * this, and can give us higher timer resolution; we'll set 50ms here, and
1489 * hope that no other Glk library is worse.
1490 */
1491 static const glui32 GLN_GRAPHICS_TIMEOUT = 50;
1492
1493 /*
1494 * Count of timeouts to wait on. Waiting after a repaint smooths the
1495 * display where the frame is being resized, by helping to avoid graphics
1496 * output while more resize events are received; around 1/2 second seems
1497 * okay.
1498 */
1499 static const int GLN_GRAPHICS_REPAINT_WAIT = 10;
1500
1501 /* Pixel size multiplier for image size scaling. */
1502 static const int GLN_GRAPHICS_PIXEL = 1;
1503
1504 /* Proportion of the display to use for graphics. */
1505 static const glui32 GLN_GRAPHICS_PROPORTION = 30;
1506
1507 /*
1508 * Special title picture number, requiring its own handling, and count of
1509 * timeouts to wait on after fully rendering the title picture (~2 seconds).
1510 */
1511 static const int GLN_GRAPHICS_TITLE_PICTURE = 0,
1512 GLN_GRAPHICS_TITLE_WAIT = 40;
1513
1514 /*
1515 * Border and shading control. For cases where we can't detect the back-
1516 * ground color of the main window, there's a default, white, background.
1517 * Bordering is black, with a 1 pixel border, 2 pixel shading, and 8 steps
1518 * of shading fade.
1519 */
1520 static const glui32 GLN_GRAPHICS_DEFAULT_BACKGROUND = 0x00ffffff,
1521 GLN_GRAPHICS_BORDER_COLOR = 0x00000000;
1522 static const int GLN_GRAPHICS_BORDER = 1,
1523 GLN_GRAPHICS_SHADING = 2,
1524 GLN_GRAPHICS_SHADE_STEPS = 8;
1525
1526 /*
1527 * Guaranteed unused pixel value. This value is used to fill the on-screen
1528 * buffer on new pictures or repaints, resulting in a full paint of all
1529 * pixels since no off-screen, real picture, pixel will match it.
1530 */
1531 static const int GLN_GRAPHICS_UNUSED_PIXEL = 0xff;
1532
1533 /* Graphics file directory, and type of graphics found in it. */
1534 static char *gln_graphics_bitmap_directory = NULL;
1535 static BitmapType gln_graphics_bitmap_type = NO_BITMAPS;
1536
1537 /* The current picture id being displayed. */
1538 enum { GLN_PALETTE_SIZE = 32 };
1539 static gln_byte *gln_graphics_bitmap = NULL;
1540 static gln_uint16 gln_graphics_width = 0,
1541 gln_graphics_height = 0;
1542 static Colour gln_graphics_palette[GLN_PALETTE_SIZE]; /* = { 0, ... }; */
1543 static int gln_graphics_picture = -1;
1544
1545 /*
1546 * Flags set on new picture, and on resize or arrange events, and a flag
1547 * to indicate whether background repaint is stopped or active.
1548 */
1549 static int gln_graphics_new_picture = FALSE,
1550 gln_graphics_repaint = FALSE,
1551 gln_graphics_active = FALSE;
1552
1553 /*
1554 * State to monitor the state of interpreter graphics. The values of the
1555 * enumerations match the modes supplied by os_graphics().
1556 */
1557 static enum {
1558 GLN_GRAPHICS_OFF = 0,
1559 GLN_GRAPHICS_LINE_MODE = 1,
1560 GLN_GRAPHICS_BITMAP_MODE = 2
1561 }
1562 gln_graphics_interpreter_state = GLN_GRAPHICS_OFF;
1563
1564
1565 /*
1566 * Pointer to the two graphics buffers, one the off-screen representation
1567 * of pixels, and the other tracking on-screen data. These are temporary
1568 * graphics malloc'ed memory, and should be free'd on exit.
1569 */
1570 static gln_byte *gln_graphics_off_screen = NULL,
1571 *gln_graphics_on_screen = NULL;
1572
1573 /*
1574 * The number of colors used in the palette by the current picture. Because
1575 * of the way it's queried, we risk a race, with admittedly a very low
1576 * probability, with the updater. So, it's initialized instead to the
1577 * largest possible value. The real value in use is inserted on the first
1578 * picture update timeout call for a new picture.
1579 */
1580 static int gln_graphics_color_count = GLN_PALETTE_SIZE;
1581
1582
1583 /*
1584 * gln_graphics_open()
1585 *
1586 * If it's not open, open the graphics window. Returns TRUE if graphics
1587 * was successfully started, or already on.
1588 */
1589 static int
1590 gln_graphics_open (void)
1591 {
1592 if (!gln_graphics_window)
1593 {
1594 gln_graphics_window = glk_window_open (gln_main_window,
1595 winmethod_Above
1596 | winmethod_Proportional,
1597 GLN_GRAPHICS_PROPORTION,
1598 wintype_Graphics, 0);
1599 }
1600
1601 return gln_graphics_window != NULL;
1602 }
1603
1604
1605 /*
1606 * gln_graphics_close()
1607 *
1608 * If open, close the graphics window and set back to NULL.
1609 */
1610 static void
1611 gln_graphics_close (void)
1612 {
1613 if (gln_graphics_window)
1614 {
1615 glk_window_close (gln_graphics_window, NULL);
1616 gln_graphics_window = NULL;
1617 }
1618 }
1619
1620
1621 /*
1622 * gln_graphics_start()
1623 *
1624 * If graphics enabled, start any background picture update processing.
1625 */
1626 static void
1627 gln_graphics_start (void)
1628 {
1629 if (gln_graphics_enabled)
1630 {
1631 /* If not running, start the updating "thread". */
1632 if (!gln_graphics_active)
1633 {
1634 glk_request_timer_events (GLN_GRAPHICS_TIMEOUT);
1635 gln_graphics_active = TRUE;
1636 }
1637 }
1638 }
1639
1640
1641 /*
1642 * gln_graphics_stop()
1643 *
1644 * Stop any background picture update processing.
1645 */
1646 static void
1647 gln_graphics_stop (void)
1648 {
1649 /* If running, stop the updating "thread". */
1650 if (gln_graphics_active)
1651 {
1652 glk_request_timer_events (0);
1653 gln_graphics_active = FALSE;
1654 }
1655 }
1656
1657
1658 /*
1659 * gln_graphics_are_displayed()
1660 *
1661 * Return TRUE if graphics are currently being displayed, FALSE otherwise.
1662 */
1663 static int
1664 gln_graphics_are_displayed (void)
1665 {
1666 return gln_graphics_window != NULL;
1667 }
1668
1669
1670 /*
1671 * gln_graphics_paint()
1672 *
1673 * Set up a complete repaint of the current picture in the graphics window.
1674 * This function should be called on the appropriate Glk window resize and
1675 * arrange events.
1676 */
1677 static void
1678 gln_graphics_paint (void)
1679 {
1680 if (gln_graphics_enabled && gln_graphics_are_displayed ())
1681 {
1682 /* Set the repaint flag, and start graphics. */
1683 gln_graphics_repaint = TRUE;
1684 gln_graphics_start ();
1685 }
1686 }
1687
1688
1689 /*
1690 * gln_graphics_restart()
1691 *
1692 * Restart graphics as if the current picture is a new picture. This
1693 * function should be called whenever graphics is re-enabled after being
1694 * disabled.
1695 */
1696 static void
1697 gln_graphics_restart (void)
1698 {
1699 if (gln_graphics_enabled && gln_graphics_are_displayed ())
1700 {
1701 /* Set the new picture flag, and start graphics. */
1702 gln_graphics_new_picture = TRUE;
1703 gln_graphics_start ();
1704 }
1705 }
1706
1707
1708 /*
1709 * gln_graphics_count_colors()
1710 *
1711 * Analyze an image, and return an overall count of how many colors out of
1712 * the palette are used.
1713 */
1714 static int
1715 gln_graphics_count_colors (gln_byte bitmap[],
1716 gln_uint16 width, gln_uint16 height)
1717 {
1718 int x, y, count;
1719 long usage[GLN_PALETTE_SIZE], index_row;
1720 assert (bitmap);
1721
1722 /*
1723 * Traverse the image, counting each pixel usage. For the y iterator,
1724 * maintain an index row as an optimization to avoid multiplications in
1725 * the loop.
1726 */
1727 count = 0;
1728 memset (usage, 0, sizeof (usage));
1729 for (y = 0, index_row = 0; y < height; y++, index_row += width)
1730 {
1731 for (x = 0; x < width; x++)
1732 {
1733 long index;
1734
1735 /* Get the pixel index, and update the count for this color. */
1736 index = index_row + x;
1737 usage[bitmap[index]]++;
1738
1739 /* If color usage is now 1, note new color encountered. */
1740 if (usage[bitmap[index]] == 1)
1741 count++;
1742 }
1743 }
1744
1745 return count;
1746 }
1747
1748
1749 /*
1750 * gln_graphics_split_color()
1751 * gln_graphics_combine_color()
1752 *
1753 * General graphics helper functions, to convert between RGB and Glk glui32
1754 * color representations.
1755 */
1756 static void
1757 gln_graphics_split_color (glui32 color, gln_rgbref_t rgb_color)
1758 {
1759 assert (rgb_color);
1760
1761 rgb_color->red = (color >> 16) & 0xff;
1762 rgb_color->green = (color >> 8) & 0xff;
1763 rgb_color->blue = color & 0xff;
1764 }
1765
1766 static glui32
1767 gln_graphics_combine_color (gln_rgbref_t rgb_color)
1768 {
1769 glui32 color;
1770 assert (rgb_color);
1771
1772 color = (rgb_color->red << 16) | (rgb_color->green << 8) | rgb_color->blue;
1773 return color;
1774 }
1775
1776
1777 /*
1778 * gln_graphics_clear_and_border()
1779 *
1780 * Clear the graphics window, and border and shade the area where the
1781 * picture is going to be rendered. This attempts a small raised effect
1782 * for the picture, in keeping with modern trends.
1783 */
1784 static void
1785 gln_graphics_clear_and_border (winid_t glk_window,
1786 int x_offset, int y_offset,
1787 int pixel_size, gln_uint16 width,
1788 gln_uint16 height)
1789 {
1790 glui32 background, fade_color, shading_color;
1791 gln_rgb_t rgb_background, rgb_border, rgb_fade;
1792 int index;
1793 assert (glk_window);
1794
1795 /*
1796 * Try to detect the background color of the main window, by getting the
1797 * background for Normal style (Glk offers no way to directly get a window's
1798 * background color). If we can get it, we'll match the graphics window
1799 * background to it. If we can't, we'll default the color to white.
1800 */
1801 if (!glk_style_measure (gln_main_window,
1802 style_Normal, stylehint_BackColor, &background))
1803 {
1804 /*
1805 * Unable to get the main window background, so assume, and default
1806 * graphics to white.
1807 */
1808 background = GLN_GRAPHICS_DEFAULT_BACKGROUND;
1809 }
1810
1811 /*
1812 * Set the graphics window background to match the main window background,
1813 * as best as we can tell, and clear the window.
1814 */
1815 glk_window_set_background_color (glk_window, background);
1816 glk_window_clear (glk_window);
1817 #ifndef GARGLK
1818 /*
1819 * For very small pictures, just border them, but don't try and
1820 * do any shading. Failing this check is probably highly unlikely.
1821 */
1822 if (width < 2 * GLN_GRAPHICS_SHADE_STEPS
1823 || height < 2 * GLN_GRAPHICS_SHADE_STEPS)
1824 {
1825 /* Paint a rectangle bigger than the picture by border pixels. */
1826 glk_window_fill_rect (glk_window,
1827 GLN_GRAPHICS_BORDER_COLOR,
1828 x_offset - GLN_GRAPHICS_BORDER,
1829 y_offset - GLN_GRAPHICS_BORDER,
1830 width * pixel_size + GLN_GRAPHICS_BORDER * 2,
1831 height * pixel_size + GLN_GRAPHICS_BORDER * 2);
1832 return;
1833 }
1834 #endif
1835 /*
1836 * Paint a rectangle bigger than the picture by border pixels all round,
1837 * and with additional shading pixels right and below. Some of these
1838 * shading pixels are later overwritten by the fading loop below. The
1839 * picture will sit over this rectangle.
1840 */
1841 glk_window_fill_rect (glk_window,
1842 GLN_GRAPHICS_BORDER_COLOR,
1843 x_offset - GLN_GRAPHICS_BORDER,
1844 y_offset - GLN_GRAPHICS_BORDER,
1845 width * pixel_size + GLN_GRAPHICS_BORDER * 2
1846 + GLN_GRAPHICS_SHADING,
1847 height * pixel_size + GLN_GRAPHICS_BORDER * 2
1848 + GLN_GRAPHICS_SHADING);
1849
1850 /*
1851 * Split the main window background color and the border color into
1852 * components.
1853 */
1854 gln_graphics_split_color (background, &rgb_background);
1855 gln_graphics_split_color (GLN_GRAPHICS_BORDER_COLOR, &rgb_border);
1856
1857 /*
1858 * Generate the incremental color to use in fade steps. Here we're
1859 * assuming that the border is always darker than the main window
1860 * background (currently valid, as we're using black).
1861 */
1862 rgb_fade.red = (rgb_background.red - rgb_border.red)
1863 / GLN_GRAPHICS_SHADE_STEPS;
1864 rgb_fade.green = (rgb_background.green - rgb_border.green)
1865 / GLN_GRAPHICS_SHADE_STEPS;
1866 rgb_fade.blue = (rgb_background.blue - rgb_border.blue)
1867 / GLN_GRAPHICS_SHADE_STEPS;
1868
1869 /* Combine RGB fade into a single incremental Glk color. */
1870 fade_color = gln_graphics_combine_color (&rgb_fade);
1871
1872 /* Fade in edge, from background to border, shading in stages. */
1873 shading_color = background;
1874 for (index = 0; index < GLN_GRAPHICS_SHADE_STEPS; index++)
1875 {
1876 /* Shade the two border areas with this color. */
1877 glk_window_fill_rect (glk_window, shading_color,
1878 x_offset + width * pixel_size
1879 + GLN_GRAPHICS_BORDER,
1880 y_offset + index - GLN_GRAPHICS_BORDER,
1881 GLN_GRAPHICS_SHADING, 1);
1882 glk_window_fill_rect (glk_window, shading_color,
1883 x_offset + index - GLN_GRAPHICS_BORDER,
1884 y_offset + height * pixel_size
1885 + GLN_GRAPHICS_BORDER,
1886 1, GLN_GRAPHICS_SHADING);
1887
1888 /* Update the shading color for the fade next iteration. */
1889 shading_color -= fade_color;
1890 }
1891 }
1892
1893
1894 /*
1895 * gln_graphics_convert_palette()
1896 *
1897 * Convert a Level 9 bitmap color palette to a Glk one.
1898 */
1899 static void
1900 gln_graphics_convert_palette (Colour ln_palette[], glui32 glk_palette[])
1901 {
1902 int index;
1903 assert (ln_palette && glk_palette);
1904
1905 for (index = 0; index < GLN_PALETTE_SIZE; index++)
1906 {
1907 Colour colour;
1908 gln_rgb_t gln_color;
1909
1910 /* Convert color from Level 9 to internal RGB, then to Glk color. */
1911 colour = ln_palette[index];
1912 gln_color.red = colour.red;
1913 gln_color.green = colour.green;
1914 gln_color.blue = colour.blue;
1915 glk_palette[index] = gln_graphics_combine_color (&gln_color);
1916 }
1917 }
1918
1919
1920 /*
1921 * gln_graphics_position_picture()
1922 *
1923 * Given a picture width and height, return the x and y offsets to center
1924 * this picture in the current graphics window.
1925 */
1926 static void
1927 gln_graphics_position_picture (winid_t glk_window, int pixel_size,
1928 gln_uint16 width, gln_uint16 height,
1929 int *x_offset, int *y_offset)
1930 {
1931 glui32 window_width, window_height;
1932 assert (glk_window && x_offset && y_offset);
1933
1934 /* Measure the current graphics window dimensions. */
1935 glk_window_get_size (glk_window, &window_width, &window_height);
1936
1937 /*
1938 * Calculate and return an x and y offset to use on point plotting, so that
1939 * the image centers inside the graphical window.
1940 */
1941 *x_offset = ((int) window_width - width * pixel_size) / 2;
1942 *y_offset = ((int) window_height - height * pixel_size) / 2;
1943 }
1944
1945
1946 /*
1947 * gln_graphics_is_vertex()
1948 *
1949 * Given a point, return TRUE if that point is the vertex of a fillable
1950 * region. This is a helper function for layering pictures. When assign-
1951 * ing layers, we want to weight the colors that have the most complex
1952 * shapes, or the largest count of isolated areas, heavier than simpler
1953 * areas.
1954 *
1955 * By painting the colors with the largest number of isolated areas or
1956 * the most complex shapes first, we help to minimize the number of fill
1957 * regions needed to render the complete picture.
1958 */
1959 static int
1960 gln_graphics_is_vertex (gln_byte off_screen[],
1961 gln_uint16 width, gln_uint16 height, int x, int y)
1962 {
1963 gln_byte pixel;
1964 int above, below, left, right;
1965 long index_row;
1966 assert (off_screen);
1967
1968 /* Use an index row to cut down on multiplications. */
1969 index_row = y * width;
1970
1971 /* Find the color of the reference pixel. */
1972 pixel = off_screen[index_row + x];
1973 assert (pixel < GLN_PALETTE_SIZE);
1974
1975 /*
1976 * Detect differences between the reference pixel and its upper, lower, left
1977 * and right neighbors. Mark as different if the neighbor doesn't exist,
1978 * that is, at the edge of the picture.
1979 */
1980 above = (y == 0 || off_screen[index_row - width + x] != pixel);
1981 below = (y == height - 1 || off_screen[index_row + width + x] != pixel);
1982 left = (x == 0 || off_screen[index_row + x - 1] != pixel);
1983 right = (x == width - 1 || off_screen[index_row + x + 1] != pixel);
1984
1985 /*
1986 * Return TRUE if this pixel lies at the vertex of a rectangular, fillable,
1987 * area. That is, if two adjacent neighbors aren't the same color (or if
1988 * absent -- at the edge of the picture).
1989 */
1990 return ((above || below) && (left || right));
1991 }
1992
1993
1994 /*
1995 * gms_graphics_compare_layering_inverted()
1996 * gln_graphics_assign_layers()
1997 *
1998 * Given two sets of image bitmaps, and a palette, this function will
1999 * assign layers palette colors.
2000 *
2001 * Layers are assigned by first counting the number of vertices in the
2002 * color plane, to get a measure of the complexity of shapes displayed in
2003 * this color, and also the raw number of times each palette color is
2004 * used. This is then sorted, so that layers are assigned to colors, with
2005 * the lowest layer being the color with the most complex shapes, and
2006 * within this (or where the count of vertices is zero) the most used color.
2007 *
2008 * The function compares pixels in the two image bitmaps given, these
2009 * being the off-screen and on-screen buffers, and generates counts only
2010 * where these bitmaps differ. This ensures that only pixels not yet
2011 * painted are included in layering.
2012 *
2013 * As well as assigning layers, this function returns a set of layer usage
2014 * flags, to help the rendering loop to terminate as early as possible.
2015 *
2016 * By painting lower layers first, the paint can take in larger areas if
2017 * it's permitted to include not-yet-validated higher levels. This helps
2018 * minimize the amount of Glk areas fills needed to render a picture.
2019 */
2020 typedef struct {
2021 long complexity; /* Count of vertices for this color. */
2022 long usage; /* Color usage count. */
2023 int color; /* Color index into palette. */
2024 } gln_layering_t;
2025
2026 static int
2027 gln_graphics_compare_layering_inverted (const void *void_first,
2028 const void *void_second)
2029 {
2030 gln_layering_t * first = (gln_layering_t *) void_first;
2031 gln_layering_t * second = (gln_layering_t *) void_second;
2032
2033 /*
2034 * Order by complexity first, then by usage, putting largest first. Some
2035 * colors may have no vertices at all when doing animation frames, but
2036 * rendering optimization relies on the first layer that contains no areas
2037 * to fill halting the rendering loop. So it's important here that we order
2038 * indexes so that colors that render complex shapes come first, non-empty,
2039 * but simpler shaped colors next, and finally all genuinely empty layers.
2040 */
2041 return second->complexity > first->complexity ? 1 :
2042 first->complexity > second->complexity ? -1 :
2043 second->usage > first->usage ? 1 :
2044 first->usage > second->usage ? -1 : 0;
2045 }
2046
2047 static void
2048 gln_graphics_assign_layers (gln_byte off_screen[], gln_byte on_screen[],
2049 gln_uint16 width, gln_uint16 height,
2050 int layers[], long layer_usage[])
2051 {
2052 int index, x, y;
2053 long index_row;
2054 gln_layering_t layering[GLN_PALETTE_SIZE];
2055 assert (off_screen && on_screen && layers && layer_usage);
2056
2057 /* Clear initial complexity and usage counts, and set initial colors. */
2058 for (index = 0; index < GLN_PALETTE_SIZE; index++)
2059 {
2060 layering[index].complexity = 0;
2061 layering[index].usage = 0;
2062 layering[index].color = index;
2063 }
2064
2065 /*
2066 * Traverse the image, counting vertices and pixel usage where the pixels
2067 * differ between the off-screen and on-screen buffers. Optimize by
2068 * maintaining an index row to avoid multiplications.
2069 */
2070 for (y = 0, index_row = 0; y < height; y++, index_row += width)
2071 {
2072 for (x = 0; x < width; x++)
2073 {
2074 long index;
2075
2076 /*
2077 * Get the index for this pixel, and update complexity and usage
2078 * if off-screen and on-screen pixels differ.
2079 */
2080 index = index_row + x;
2081 if (on_screen[index] != off_screen[index])
2082 {
2083 if (gln_graphics_is_vertex (off_screen, width, height, x, y))
2084 layering[off_screen[index]].complexity++;
2085
2086 layering[off_screen[index]].usage++;
2087 }
2088 }
2089 }
2090
2091 /*
2092 * Sort counts to form color indexes. The primary sort is on the shape
2093 * complexity, and within this, on color usage.
2094 */
2095 qsort (layering, GLN_PALETTE_SIZE,
2096 sizeof (*layering), gln_graphics_compare_layering_inverted);
2097
2098 /*
2099 * Assign a layer to each palette color, and also return the layer usage
2100 * for each layer.
2101 */
2102 for (index = 0; index < GLN_PALETTE_SIZE; index++)
2103 {
2104 layers[layering[index].color] = index;
2105 layer_usage[index] = layering[index].usage;
2106 }
2107 }
2108
2109
2110 /*
2111 * gln_graphics_paint_region()
2112 *
2113 * This is a partially optimized point plot. Given a point in the graphics
2114 * bitmap, it tries to extend the point to a color region, and fill a number
2115 * of pixels in a single Glk rectangle fill. The goal here is to reduce the
2116 * number of Glk rectangle fills, which tend to be extremely inefficient
2117 * operations for generalized point plotting.
2118 *
2119 * The extension works in image layers; each palette color is assigned* a
2120 * layer, and we paint each layer individually, starting at the lowest. So,
2121 * the region is free to fill any invalidated pixel in a higher layer, and
2122 * all pixels, invalidated or already validated, in the same layer. In
2123 * practice, it is good enough to look for either invalidated pixels or pixels
2124 * in the same layer, and construct a region as large as possible from these,
2125 * then on marking points as validated, mark only those in the same layer as
2126 * the initial point.
2127 *
2128 * The optimization here is not the best possible, but is reasonable. What
2129 * we do is to try and stretch the region horizontally first, then vertically.
2130 * In practice, we might find larger areas by stretching vertically and then
2131 * horizontally, or by stretching both dimensions at the same time. In
2132 * mitigation, the number of colors in a picture is small (16), and the
2133 * aspect ratio of pictures makes them generally wider than they are tall.
2134 *
2135 * Once we've found the region, we render it with a single Glk rectangle fill,
2136 * and mark all the pixels in this region that match the layer of the initial
2137 * given point as validated.
2138 */
2139 static void
2140 gln_graphics_paint_region (winid_t glk_window, glui32 palette[], int layers[],
2141 gln_byte off_screen[], gln_byte on_screen[],
2142 int x, int y, int x_offset, int y_offset,
2143 int pixel_size, gln_uint16 width, gln_uint16 height)
2144 {
2145 gln_byte pixel;
2146 int layer, x_min, x_max, y_min, y_max, x_index, y_index;
2147 long index_row;
2148 assert (glk_window && palette && layers && off_screen && on_screen);
2149
2150 /* Find the color and layer for the initial pixel. */
2151 pixel = off_screen[y * width + x];
2152 layer = layers[pixel];
2153 assert (pixel < GLN_PALETTE_SIZE);
2154
2155 /*
2156 * Start by finding the extent to which we can pull the x coordinate and
2157 * still find either invalidated pixels, or pixels in this layer.
2158 *
2159 * Use an index row to remove multiplications from the loops.
2160 */
2161 index_row = y * width;
2162 for (x_min = x; x_min - 1 >= 0; x_min--)
2163 {
2164 long index = index_row + x_min - 1;
2165
2166 if (on_screen[index] == off_screen[index]
2167 && layers[off_screen[index]] != layer)
2168 break;
2169 }
2170 for (x_max = x; x_max + 1 < width; x_max++)
2171 {
2172 long index = index_row + x_max + 1;
2173
2174 if (on_screen[index] == off_screen[index]
2175 && layers[off_screen[index]] != layer)
2176 break;
2177 }
2178
2179 /*
2180 * Now try to stretch the height of the region, by extending the y
2181 * coordinate as much as possible too. Again, we're looking for pixels
2182 * that are invalidated or ones in the same layer. We need to check
2183 * across the full width of the current region.
2184 *
2185 * As above, an index row removes multiplications from the loops.
2186 */
2187 for (y_min = y, index_row = (y - 1) * width;
2188 y_min - 1 >= 0; y_min--, index_row -= width)
2189 {
2190 for (x_index = x_min; x_index <= x_max; x_index++)
2191 {
2192 long index = index_row + x_index;
2193
2194 if (on_screen[index] == off_screen[index]
2195 && layers[off_screen[index]] != layer)
2196 goto break_y_min;
2197 }
2198 }
2199 break_y_min:
2200
2201 for (y_max = y, index_row = (y + 1) * width;
2202 y_max + 1 < height; y_max++, index_row += width)
2203 {
2204 for (x_index = x_min; x_index <= x_max; x_index++)
2205 {
2206 long index = index_row + x_index;
2207
2208 if (on_screen[index] == off_screen[index]
2209 && layers[off_screen[index]] != layer)
2210 goto break_y_max;
2211 }
2212 }
2213 break_y_max:
2214
2215 /* Fill the region using Glk's rectangle fill. */
2216 glk_window_fill_rect (glk_window, palette[pixel],
2217 x_min * pixel_size + x_offset,
2218 y_min * pixel_size + y_offset,
2219 (x_max - x_min + 1) * pixel_size,
2220 (y_max - y_min + 1) * pixel_size);
2221
2222 /*
2223 * Validate each pixel in the reference layer that was rendered by the
2224 * rectangle fill. We don't validate pixels that are not in this layer
2225 * (and are by definition in higher layers, as we've validated all lower
2226 * layers), since although we colored them, we did it for optimization
2227 * reasons, and they're not yet colored correctly.
2228 *
2229 * Maintain an index row as an optimization to avoid multiplication.
2230 */
2231 index_row = y_min * width;
2232 for (y_index = y_min; y_index <= y_max; y_index++)
2233 {
2234 for (x_index = x_min; x_index <= x_max; x_index++)
2235 {
2236 long index;
2237
2238 /*
2239 * Get the index for x_index,y_index. If the layers match, update
2240 * the on-screen buffer.
2241 */
2242 index = index_row + x_index;
2243 if (layers[off_screen[index]] == layer)
2244 {
2245 assert (off_screen[index] == pixel);
2246 on_screen[index] = off_screen[index];
2247 }
2248 }
2249
2250 /* Update row index component on change of y. */
2251 index_row += width;
2252 }
2253 }
2254
2255 static void
2256 gln_graphics_paint_everything (winid_t glk_window,
2257 glui32 palette[],
2258 gln_byte off_screen[],
2259 int x_offset, int y_offset,
2260 gln_uint16 width, gln_uint16 height)
2261 {
2262 gln_byte pixel; /* Reference pixel color */
2263 int x, y;
2264
2265 for (y = 0; y < height; y++)
2266 {
2267 for (x = 0; x < width; x ++)
2268 {
2269 pixel = off_screen[ y * width + x ];
2270 glk_window_fill_rect (glk_window,
2271 palette[ pixel ],
2272 x * GLN_GRAPHICS_PIXEL + x_offset,
2273 y * GLN_GRAPHICS_PIXEL + y_offset,
2274 GLN_GRAPHICS_PIXEL, GLN_GRAPHICS_PIXEL);
2275 }
2276 }
2277 }
2278
2279 /*
2280 * gln_graphics_timeout()
2281 *
2282 * This is a background function, called on Glk timeouts. Its job is to
2283 * repaint some of the current graphics image. On successive calls, it
2284 * does a part of the repaint, then yields to other processing. This is
2285 * useful since the Glk primitive to plot points in graphical windows is
2286 * extremely slow; this way, the repaint doesn't block game play.
2287 *
2288 * The function should be called on Glk timeout events. When the repaint
2289 * is complete, the function will turn off Glk timers.
2290 *
2291 * The function uses double-buffering to track how much of the graphics
2292 * buffer has been rendered. This helps to minimize the amount of point
2293 * plots required, as only the differences between the two buffers need
2294 * to be rendered.
2295 */
2296 static void
2297 gln_graphics_timeout (void)
2298 {
2299 static glui32 palette[GLN_PALETTE_SIZE]; /* Precomputed Glk palette */
2300 static int layers[GLN_PALETTE_SIZE]; /* Assigned image layers */
2301 static long layer_usage[GLN_PALETTE_SIZE]; /* Image layer occupancies */
2302
2303 static int deferred_repaint = FALSE; /* Local delayed repaint flag */
2304 static int ignore_counter; /* Count of calls ignored */
2305
2306 static int x_offset, y_offset; /* Point plot offsets */
2307 static int yield_counter; /* Yields in rendering */
2308 static int saved_layer; /* Saved current layer */
2309 static int saved_x, saved_y; /* Saved x,y coord */
2310
2311 static int total_regions; /* Debug statistic */
2312
2313 gln_byte *on_screen; /* On-screen image buffer */
2314 gln_byte *off_screen; /* Off-screen image buffer */
2315 long picture_size; /* Picture size in pixels */
2316 int layer; /* Image layer iterator */
2317 int x, y; /* Image iterators */
2318 int regions; /* Count of regions painted */
2319
2320 /* Ignore the call if the current graphics state is inactive. */
2321 if (!gln_graphics_active)
2322 return;
2323 assert (gln_graphics_window);
2324
2325 /*
2326 * On detecting a repaint request, note the flag in a local static variable,
2327 * then set up a graphics delay to wait until, hopefully, the resize, if
2328 * that's what caused it, is complete, and return. This makes resizing the
2329 * window a lot smoother, since it prevents unnecessary region paints where
2330 * we are receiving consecutive Glk arrange or redraw events.
2331 */
2332 if (gln_graphics_repaint)
2333 {
2334 deferred_repaint = TRUE;
2335 gln_graphics_repaint = FALSE;
2336 ignore_counter = GLN_GRAPHICS_REPAINT_WAIT - 1;
2337 return;
2338 }
2339
2340 /*
2341 * If asked to ignore a given number of calls, decrement the ignore counter
2342 * and return having done nothing more. This lets us delay graphics
2343 * operations by a number of timeouts, providing partial protection from
2344 * resize event "storms".
2345 *
2346 * Note -- to wait for N timeouts, set the count of timeouts to be ignored
2347 * to N-1.
2348 */
2349 assert (ignore_counter >= 0);
2350 if (ignore_counter > 0)
2351 {
2352 ignore_counter--;
2353 return;
2354 }
2355
2356 /* Calculate the picture size, and synchronize screen buffer pointers. */
2357 picture_size = gln_graphics_width * gln_graphics_height;
2358 off_screen = gln_graphics_off_screen;
2359 on_screen = gln_graphics_on_screen;
2360
2361 /*
2362 * If we received a new picture, set up the local static variables for that
2363 * picture -- convert the color palette, and initialize the off_screen
2364 * buffer to be the base picture.
2365 */
2366 if (gln_graphics_new_picture)
2367 {
2368 /* Initialize the off_screen buffer to be a copy of the base picture. */
2369 free (off_screen);
2370 off_screen = gln_malloc (picture_size * sizeof (*off_screen));
2371 memcpy (off_screen, gln_graphics_bitmap,
2372 picture_size * sizeof (*off_screen));
2373
2374 /* Note the buffer for freeing on cleanup. */
2375 gln_graphics_off_screen = off_screen;
2376
2377 /*
2378 * Pre-convert all the picture palette colors into their corresponding
2379 * Glk colors.
2380 */
2381 gln_graphics_convert_palette (gln_graphics_palette, palette);
2382
2383 /* Save the color count for possible queries later. */
2384 gln_graphics_color_count =
2385 gln_graphics_count_colors (off_screen,
2386 gln_graphics_width, gln_graphics_height);
2387 }
2388
2389 /*
2390 * For a new picture, or a repaint of a prior one, calculate new values for
2391 * the x and y offsets used to draw image points, and set the on-screen
2392 * buffer to an unused pixel value, in effect invalidating all on-screen
2393 * data. Also, reset the saved image scan coordinates so that we scan for
2394 * unpainted pixels from top left starting at layer zero, and clear the
2395 * graphics window.
2396 */
2397 if (gln_graphics_new_picture || deferred_repaint)
2398 {
2399 /*
2400 * Calculate the x and y offset to center the picture in the graphics
2401 * window.
2402 */
2403 gln_graphics_position_picture (gln_graphics_window,
2404 GLN_GRAPHICS_PIXEL,
2405 gln_graphics_width, gln_graphics_height,
2406 &x_offset, &y_offset);
2407
2408 /*
2409 * Reset all on-screen pixels to an unused value, guaranteed not to
2410 * match any in a real picture. This forces all pixels to be repainted
2411 * on a buffer/on-screen comparison.
2412 */
2413 free (on_screen);
2414 on_screen = gln_malloc (picture_size * sizeof (*on_screen));
2415 memset (on_screen, GLN_GRAPHICS_UNUSED_PIXEL,
2416 picture_size * sizeof (*on_screen));
2417
2418 /* Note the buffer for freeing on cleanup. */
2419 gln_graphics_on_screen = on_screen;
2420
2421 /*
2422 * Assign new layers to the current image. This sorts colors by usage
2423 * and puts the most used colors in the lower layers. It also hands us
2424 * a count of pixels in each layer, useful for knowing when to stop
2425 * scanning for layers in the rendering loop.
2426 */
2427 #ifndef GARGLK
2428 gln_graphics_assign_layers (off_screen, on_screen,
2429 gln_graphics_width, gln_graphics_height,
2430 layers, layer_usage);
2431 #endif
2432
2433 /* Clear the graphics window. */
2434 gln_graphics_clear_and_border (gln_graphics_window,
2435 x_offset, y_offset,
2436 GLN_GRAPHICS_PIXEL,
2437 gln_graphics_width, gln_graphics_height);
2438
2439 /* Start a fresh picture rendering pass. */
2440 yield_counter = 0;
2441 saved_layer = 0;
2442 saved_x = 0;
2443 saved_y = 0;
2444 total_regions = 0;
2445
2446 /* Clear the new picture and deferred repaint flags. */
2447 gln_graphics_new_picture = FALSE;
2448 deferred_repaint = FALSE;
2449 }
2450
2451 #ifndef GARGLK
2452 /*
2453 * Make a portion of an image pass, from lower to higher image layers,
2454 * scanning for invalidated pixels that are in the current image layer we
2455 * are painting. Each invalidated pixel gives rise to a region paint,
2456 * which equates to one Glk rectangle fill.
2457 *
2458 * When the limit on regions is reached, save the current image pass layer
2459 * and coordinates, and yield control to the main game playing code by
2460 * returning. On the next call, pick up where we left off.
2461 *
2462 * As an optimization, we can leave the loop on the first empty layer we
2463 * encounter. Since layers are ordered by complexity and color usage, all
2464 * layers higher than the first unused one will also be empty, so we don't
2465 * need to scan them.
2466 */
2467 regions = 0;
2468 for (layer = saved_layer;
2469 layer < GLN_PALETTE_SIZE && layer_usage[layer] > 0; layer++)
2470 {
2471 long index_row;
2472
2473 /*
2474 * As an optimization to avoid multiplications in the loop, maintain a
2475 * separate index row.
2476 */
2477 index_row = saved_y * gln_graphics_width;
2478 for (y = saved_y; y < gln_graphics_height; y++)
2479 {
2480 for (x = saved_x; x < gln_graphics_width; x++)
2481 {
2482 long index;
2483
2484 /* Get the index for this pixel. */
2485 index = index_row + x;
2486 assert (index < picture_size * sizeof (*off_screen));
2487
2488 /*
2489 * Ignore pixels not in the current layer, and pixels not
2490 * currently invalid (that is, ones whose on-screen represen-
2491 * tation matches the off-screen buffer).
2492 */
2493 if (layers[off_screen[index]] == layer
2494 && on_screen[index] != off_screen[index])
2495 {
2496 /*
2497 * Rather than painting just one pixel, here we try to
2498 * paint the maximal region we can for the layer of the
2499 * given pixel.
2500 */
2501 gln_graphics_paint_region (gln_graphics_window,
2502 palette, layers,
2503 off_screen, on_screen,
2504 x, y, x_offset, y_offset,
2505 GLN_GRAPHICS_PIXEL,
2506 gln_graphics_width,
2507 gln_graphics_height);
2508
2509 /*
2510 * Increment count of regions handled, and yield, by
2511 * returning, if the limit on paint regions is reached.
2512 * Before returning, save the current layer and scan
2513 * coordinates, so we can pick up here on the next call.
2514 */
2515 regions++;
2516 if (regions >= GLN_REPAINT_LIMIT)
2517 {
2518 yield_counter++;
2519 saved_layer = layer;
2520 saved_x = x;
2521 saved_y = y;
2522 total_regions += regions;
2523 return;
2524 }
2525 }
2526 }
2527
2528 /* Reset the saved x coordinate on y increment. */
2529 saved_x = 0;
2530
2531 /* Update the index row on change of y. */
2532 index_row += gln_graphics_width;
2533 }
2534
2535 /* Reset the saved y coordinate on layer change. */
2536 saved_y = 0;
2537 }
2538
2539 /*
2540 * If we reach this point, then we didn't get to the limit on regions
2541 * painted on this pass. In that case, we've finished rendering the
2542 * image.
2543 */
2544 assert (regions < GLN_REPAINT_LIMIT);
2545 total_regions += regions;
2546
2547 #else
2548 gln_graphics_paint_everything
2549 (gln_graphics_window,
2550 palette, off_screen,
2551 x_offset, y_offset,
2552 gln_graphics_width,
2553 gln_graphics_height);
2554 #endif
2555
2556 /* Stop graphics; there's no more to be done until something restarts us. */
2557 gln_graphics_stop ();
2558 }
2559
2560
2561 /*
2562 * gln_graphics_locate_bitmaps()
2563 *
2564 * Given the name of the game file being run, try to set up the graphics
2565 * directory and bitmap type for that game. If none available, set the
2566 * directory to NULL, and bitmap type to NO_BITMAPS.
2567 */
2568 static void
2569 gln_graphics_locate_bitmaps (const char *gamefile)
2570 {
2571 const char *basename;
2572 char *dirname;
2573 BitmapType bitmap_type;
2574
2575 /* Find the start of the last element of the filename passed in. */
2576 basename = strrchr (gamefile, GLN_FILE_DELIM);
2577 basename = basename ? basename + 1 : gamefile;
2578
2579 /* Take a copy of the directory part of the filename. */
2580 dirname = gln_malloc (basename - gamefile + 1);
2581 strncpy (dirname, gamefile, basename - gamefile);
2582 dirname[basename - gamefile] = '\0';
2583
2584 /*
2585 * Use the core interpreter to search for suitable bitmaps. If none found,
2586 * free allocated memory and return noting none available.
2587 */
2588 bitmap_type = DetectBitmaps (dirname);
2589 if (bitmap_type == NO_BITMAPS)
2590 {
2591 free (dirname);
2592 gln_graphics_bitmap_directory = NULL;
2593 gln_graphics_bitmap_type = NO_BITMAPS;
2594 return;
2595 }
2596
2597 /* Record the bitmap details for later use. */
2598 gln_graphics_bitmap_directory = dirname;
2599 gln_graphics_bitmap_type = bitmap_type;
2600 }
2601
2602
2603 /*
2604 * gln_graphics_handle_title_picture()
2605 *
2606 * Picture 0 is special, normally the title picture. Unless we handle it
2607 * specially, the next picture comes along and instantly overwrites it.
2608 * Here, then, we try to delay until the picture has rendered, allowing the
2609 * delay to be broken with a keypress.
2610 */
2611 static void
2612 gln_graphics_handle_title_picture (void)
2613 {
2614 event_t event;
2615 int count;
2616
2617 gln_standout_string ("\n[ Press any key to skip the title picture... ]\n\n");
2618
2619 /* Wait until a keypress or graphics rendering is complete. */
2620 glk_request_char_event (gln_main_window);
2621 do
2622 {
2623 gln_event_wait_2 (evtype_CharInput, evtype_Timer, &event);
2624
2625 /*
2626 * If a character was pressed, return. This will let the game
2627 * progress, probably into showing the next bitmap.
2628 */
2629 if (event.type == evtype_CharInput)
2630 {
2631 gln_watchdog_tick ();
2632 return;
2633 }
2634 }
2635 while (gln_graphics_active);
2636
2637 /*
2638 * Now wait another couple of seconds, or until a keypress. We'll do this
2639 * in graphics timeout chunks, so that if graphics restarts while we're
2640 * delaying, and it requests timer events and overwrites ours, we wind up
2641 * with the identical timer event period to the one we're expecting anyway.
2642 */
2643 glk_request_timer_events (GLN_GRAPHICS_TIMEOUT);
2644 for (count = 0; count < GLN_GRAPHICS_TITLE_WAIT; count++)
2645 {
2646 gln_event_wait_2 (evtype_CharInput, evtype_Timer, &event);
2647
2648 if (event.type == evtype_CharInput)
2649 break;
2650 }
2651
2652 /*
2653 * While we waited, a Glk arrange or redraw event could have triggered
2654 * graphics into repainting, and using timers. To handle this, stop timers
2655 * only if graphics is inactive. If active, graphics will stop timers
2656 * itself when it finishes rendering. We can't stop timers here while
2657 * graphics is active; that will hang the graphics "thread".
2658 */
2659 if (!gln_graphics_active)
2660 glk_request_timer_events (0);
2661
2662 /* Cancel possible pending character event, and continue on. */
2663 glk_cancel_char_event (gln_main_window);
2664 gln_watchdog_tick ();
2665 }
2666
2667
2668 /*
2669 * os_show_bitmap()
2670 *
2671 * Called by the main interpreter when it wants us to display a picture.
2672 *
2673 * The function gets the picture bitmap, palette, and dimensions, and saves
2674 * them, and the picture id, in module variables for the background rendering
2675 * function.
2676 */
2677 void
2678 os_show_bitmap (int picture, int x, int y)
2679 {
2680 Bitmap *bitmap;
2681 long picture_bytes;
2682
2683 /*
2684 * If interpreter graphics are disabled, the only way we can get into here
2685 * is using #picture. It seems that the interpreter won't always deliver
2686 * correct bitmaps with #picture when in text mode, so it's simplest here
2687 * if we just ignore those calls.
2688 */
2689 if (gln_graphics_interpreter_state != GLN_GRAPHICS_BITMAP_MODE)
2690 return;
2691
2692 /* Ignore repeat calls for the currently displayed picture. */
2693 if (picture == gln_graphics_picture)
2694 return;
2695
2696 /*
2697 * Get the core interpreter's bitmap for the requested picture. If this
2698 * returns NULL, the picture doesn't exist, so ignore the call silently.
2699 */
2700 bitmap = DecodeBitmap (gln_graphics_bitmap_directory,
2701 gln_graphics_bitmap_type, picture, x, y);
2702 if (!bitmap)
2703 return;
2704
2705 /*
2706 * Note the last thing passed to os_show_bitmap, to avoid possible repaints
2707 * of the current picture.
2708 */
2709 gln_graphics_picture = picture;
2710
2711 /* Calculate the picture size in bytes. */
2712 picture_bytes = bitmap->width * bitmap->height * sizeof (*bitmap->bitmap);
2713
2714 /*
2715 * Save the picture details for the update code. Here we take a complete
2716 * local copy of the bitmap, dimensions, and palette. The core interpreter
2717 * may return a palette with fewer colors than our maximum, so unused local
2718 * palette entries are set to zero.
2719 */
2720 free (gln_graphics_bitmap);
2721 gln_graphics_bitmap = gln_malloc (picture_bytes);
2722 memcpy (gln_graphics_bitmap, bitmap->bitmap, picture_bytes);
2723 gln_graphics_width = bitmap->width;
2724 gln_graphics_height = bitmap->height;
2725 memset (gln_graphics_palette, 0, sizeof (gln_graphics_palette));
2726 memcpy (gln_graphics_palette, bitmap->palette,
2727 bitmap->npalette * sizeof (bitmap->palette[0]));
2728
2729 /*
2730 * If graphics are enabled, both at the Glk level and in the core
2731 * interpreter, ensure the window is displayed, set the appropriate flags,
2732 * and start graphics update. If they're not enabled, the picture details
2733 * will simply stick around in module variables until they are required.
2734 */
2735 if (gln_graphics_enabled
2736 && gln_graphics_interpreter_state == GLN_GRAPHICS_BITMAP_MODE)
2737 {
2738 /*
2739 * Ensure graphics on, then set the new picture flag and start the
2740 * updating "thread". If this is the title picture, start special
2741 * handling.
2742 */
2743 if (gln_graphics_open ())
2744 {
2745 gln_graphics_new_picture = TRUE;
2746 gln_graphics_start ();
2747
2748 if (picture == GLN_GRAPHICS_TITLE_PICTURE)
2749 gln_graphics_handle_title_picture ();
2750 }
2751 }
2752 }
2753
2754
2755 /*
2756 * gln_graphics_picture_is_available()
2757 *
2758 * Return TRUE if the graphics module data is loaded with a usable picture,
2759 * FALSE if there is no picture available to display.
2760 */
2761 static int
2762 gln_graphics_picture_is_available (void)
2763 {
2764 return gln_graphics_bitmap != NULL;
2765 }
2766
2767
2768 /*
2769 * gln_graphics_get_picture_details()
2770 *
2771 * Return the width and height of the currently loaded picture. The function
2772 * returns FALSE if no picture is loaded, otherwise TRUE, with picture details
2773 * in the return arguments.
2774 */
2775 static int
2776 gln_graphics_get_picture_details (int *width, int *height)
2777 {
2778 if (gln_graphics_picture_is_available ())
2779 {
2780 if (width)
2781 *width = gln_graphics_width;
2782 if (height)
2783 *height = gln_graphics_height;
2784
2785 return TRUE;
2786 }
2787
2788 return FALSE;
2789 }
2790
2791
2792 /*
2793 * gln_graphics_get_rendering_details()
2794 *
2795 * Returns the type of bitmap in use (if any), as a string, the count of
2796 * colors in the picture, and a flag indicating if graphics is active (busy).
2797 * The function return FALSE if graphics is not enabled or if not being
2798 * displayed, otherwise TRUE with the bitmap type, color count, and active
2799 * flag in the return arguments.
2800 *
2801 * This function races with the graphics timeout, as it returns information
2802 * set up by the first timeout following a new picture. There's a very
2803 * very small chance that it might win the race, in which case out-of-date
2804 * values are returned.
2805 */
2806 static int
2807 gln_graphics_get_rendering_details (const char **bitmap_type,
2808 int *color_count, int *is_active)
2809 {
2810 if (gln_graphics_enabled && gln_graphics_are_displayed ())
2811 {
2812 /*
2813 * Convert the detected bitmap type into a string and return it.
2814 * A NULL bitmap string implies no bitmaps.
2815 */
2816 if (bitmap_type)
2817 {
2818 const char *return_type;
2819
2820 switch (gln_graphics_bitmap_type)
2821 {
2822 case AMIGA_BITMAPS:
2823 return_type = "Amiga";
2824 break;
2825 case PC1_BITMAPS:
2826 return_type = "IBM PC(1)";
2827 break;
2828 case PC2_BITMAPS:
2829 return_type = "IBM PC(2)";
2830 break;
2831 case C64_BITMAPS:
2832 return_type = "Commodore 64";
2833 break;
2834 case BBC_BITMAPS:
2835 return_type = "BBC B";
2836 break;
2837 case CPC_BITMAPS:
2838 return_type = "Amstrad CPC/Spectrum";
2839 break;
2840 case MAC_BITMAPS:
2841 return_type = "Macintosh";
2842 break;
2843 case ST1_BITMAPS:
2844 return_type = "Atari ST(1)";
2845 break;
2846 case ST2_BITMAPS:
2847 return_type = "Atari ST(2)";
2848 break;
2849 case NO_BITMAPS:
2850 default:
2851 return_type = NULL;
2852 break;
2853 }
2854
2855 *bitmap_type = return_type;
2856 }
2857
2858 /*
2859 * Return the color count noted by timeouts on the first timeout
2860 * following a new picture. We might return the one for the prior
2861 * picture.
2862 */
2863 if (color_count)
2864 *color_count = gln_graphics_color_count;
2865
2866 /* Return graphics active flag. */
2867 if (is_active)
2868 *is_active = gln_graphics_active;
2869
2870 return TRUE;
2871 }
2872
2873 return FALSE;
2874 }
2875
2876
2877 /*
2878 * gln_graphics_interpreter_enabled()
2879 *
2880 * Return TRUE if it looks like interpreter graphics are turned on, FALSE
2881 * otherwise.
2882 */
2883 static int
2884 gln_graphics_interpreter_enabled (void)
2885 {
2886 return gln_graphics_interpreter_state != GLN_GRAPHICS_OFF;
2887 }
2888
2889
2890 /*
2891 * gln_graphics_cleanup()
2892 *
2893 * Free memory resources allocated by graphics functions. Called on game
2894 * end.
2895 */
2896 static void
2897 gln_graphics_cleanup (void)
2898 {
2899 free (gln_graphics_bitmap);
2900 gln_graphics_bitmap = NULL;
2901 free (gln_graphics_off_screen);
2902 gln_graphics_off_screen = NULL;
2903 free (gln_graphics_on_screen);
2904 gln_graphics_on_screen = NULL;
2905 free (gln_graphics_bitmap_directory);
2906 gln_graphics_bitmap_directory = NULL;
2907
2908 gln_graphics_bitmap_type = NO_BITMAPS;
2909 gln_graphics_picture = -1;
2910 }
2911
2912
2913 /*---------------------------------------------------------------------*/
2914 /* Glk port line drawing picture adapter functions */
2915 /*---------------------------------------------------------------------*/
2916
2917 /*
2918 * Graphics color table. These eight colors are selected into the four-
2919 * color palette by os_setcolour(). The standard Amiga palette is rather
2920 * over-vibrant, so to soften it a bit this table uses non-primary colors.
2921 */
2922 static const gln_rgb_t GLN_LINEGRAPHICS_COLOR_TABLE[] = {
2923 { 47, 79, 79}, /* DarkSlateGray [Black] */
2924 {238, 44, 44}, /* Firebrick2 [Red] */
2925 { 67, 205, 128}, /* SeaGreen3 [Green] */
2926 {238, 201, 0}, /* Gold2 [Yellow] */
2927 { 92, 172, 238}, /* SteelBlue2 [Blue] */
2928 {139, 87, 66}, /* LightSalmon4 [Brown] */
2929 {175, 238, 238}, /* PaleTurquoise [Cyan] */
2930 {245, 245, 245}, /* WhiteSmoke [White] */
2931 };
2932
2933 /*
2934 * Structure of a Seed Fill segment entry, and a growable stack-based array
2935 * of segments pending fill. When length exceeds size, size is increased
2936 * and the array grown.
2937 */
2938 typedef struct
2939 {
2940 int y; /* Segment y coordinate */
2941 int xl; /* Segment x left hand side coordinate */
2942 int xr; /* Segment x right hand side coordinate */
2943 int dy; /* Segment y delta */
2944 } gln_linegraphics_segment_t;
2945
2946 static gln_linegraphics_segment_t * gln_linegraphics_fill_segments = NULL;
2947 static int gln_linegraphics_fill_segments_allocation = 0,
2948 gln_linegraphics_fill_segments_length = 0;
2949
2950
2951 /*
2952 * gln_linegraphics_create_context()
2953 *
2954 * Initialize a new constructed bitmap graphics context for line drawn
2955 * graphics.
2956 */
2957 static void
2958 gln_linegraphics_create_context (void)
2959 {
2960 int width, height;
2961 long picture_bytes;
2962
2963 /* Get the picture size, and calculate the bytes in the bitmap. */
2964 GetPictureSize (&width, &height);
2965 picture_bytes = width * height * sizeof (*gln_graphics_bitmap);
2966
2967 /*
2968 * Destroy any current bitmap, and begin a fresh one. Here we set the
2969 * bitmap and the palette to all zeroes; this equates to all black.
2970 */
2971 free (gln_graphics_bitmap);
2972 gln_graphics_bitmap = gln_malloc (picture_bytes);
2973 memset (gln_graphics_bitmap, 0, picture_bytes);
2974 gln_graphics_width = width;
2975 gln_graphics_height = height;
2976 memset (gln_graphics_palette, 0, sizeof (gln_graphics_palette));
2977
2978 /* Set graphics picture number to -1; this is not a real game bitmap. */
2979 gln_graphics_picture = -1;
2980 }
2981
2982
2983 /*
2984 * gln_linegraphics_clear_context()
2985 *
2986 * Clear the complete graphical drawing area, setting all pixels to zero,
2987 * and resetting the palette to all black as well.
2988 */
2989 static void
2990 gln_linegraphics_clear_context (void)
2991 {
2992 long picture_bytes;
2993
2994 /* Get the picture size, and zero all bytes in the bitmap. */
2995 picture_bytes = gln_graphics_width
2996 * gln_graphics_height * sizeof (*gln_graphics_bitmap);
2997 memset (gln_graphics_bitmap, 0, picture_bytes);
2998
2999 /* Clear palette colors to all black. */
3000 memset (gln_graphics_palette, 0, sizeof (gln_graphics_palette));
3001 }
3002
3003
3004 /*
3005 * gln_linegraphics_set_palette_color()
3006 *
3007 * Copy the indicated main color table entry into the palette.
3008 */
3009 static void
3010 gln_linegraphics_set_palette_color (int colour, int index)
3011 {
3012 const gln_rgb_t *entry;
3013 assert (colour < GLN_PALETTE_SIZE);
3014 assert (index < sizeof (GLN_LINEGRAPHICS_COLOR_TABLE)
3015 / sizeof (GLN_LINEGRAPHICS_COLOR_TABLE[0]));
3016
3017 /* Copy the color table entry to the constructed game palette. */
3018 entry = GLN_LINEGRAPHICS_COLOR_TABLE + index;
3019 gln_graphics_palette[colour].red = entry->red;
3020 gln_graphics_palette[colour].green = entry->green;
3021 gln_graphics_palette[colour].blue = entry->blue;
3022 }
3023
3024
3025 /*
3026 * gln_linegraphics_get_pixel()
3027 * gln_linegraphics_set_pixel()
3028 *
3029 * Return and set the bitmap pixel at x,y.
3030 */
3031 static gln_byte
3032 gln_linegraphics_get_pixel (int x, int y)
3033 {
3034 assert (x >= 0 && x < gln_graphics_width
3035 && y >= 0 && y < gln_graphics_height);
3036
3037 return gln_graphics_bitmap[y * gln_graphics_width + x];
3038 }
3039
3040 static void
3041 gln_linegraphics_set_pixel (int x, int y, gln_byte color)
3042 {
3043 assert (x >= 0 && x < gln_graphics_width
3044 && y >= 0 && y < gln_graphics_height);
3045
3046 gln_graphics_bitmap[y * gln_graphics_width + x] = color;
3047 }
3048
3049
3050 /*
3051 * gln_linegraphics_plot_clip()
3052 * gln_linegraphics_draw_line_if()
3053 *
3054 * Draw a line from x1,y1 to x2,y2 in colour1, where the existing pixel
3055 * colour is colour2. The function uses Bresenham's algorithm. The second
3056 * function, gln_graphics_plot_clip, is a line drawing helper; it handles
3057 * clipping, and the requirement to plot a point only if it matches colour2.
3058 */
3059 static void
3060 gln_linegraphics_plot_clip (int x, int y, int colour1, int colour2)
3061 {
3062 /*
3063 * Clip the plot if the value is outside the context. Otherwise, plot the
3064 * pixel as colour1 if it is currently colour2.
3065 */
3066 if (x >= 0 && x < gln_graphics_width && y >= 0 && y < gln_graphics_height)
3067 {
3068 if (gln_linegraphics_get_pixel (x, y) == colour2)
3069 gln_linegraphics_set_pixel (x, y, colour1);
3070 }
3071 }
3072
3073 static void
3074 gln_linegraphics_draw_line_if (int x1, int y1, int x2, int y2,
3075 int colour1, int colour2)
3076 {
3077 int x, y, dx, dy, incx, incy, balance;
3078
3079 /* Ignore any odd request where there will be no colour changes. */
3080 if (colour1 == colour2)
3081 return;
3082
3083 /* Normalize the line into deltas and increments. */
3084 if (x2 >= x1)
3085 {
3086 dx = x2 - x1;
3087 incx = 1;
3088 }
3089 else
3090 {
3091 dx = x1 - x2;
3092 incx = -1;
3093 }
3094
3095 if (y2 >= y1)
3096 {
3097 dy = y2 - y1;
3098 incy = 1;
3099 }
3100 else
3101 {
3102 dy = y1 - y2;
3103 incy = -1;
3104 }
3105
3106 /* Start at x1,y1. */
3107 x = x1;
3108 y = y1;
3109
3110 /* Decide on a direction to progress in. */
3111 if (dx >= dy)
3112 {
3113 dy <<= 1;
3114 balance = dy - dx;
3115 dx <<= 1;
3116
3117 /* Loop until we reach the end point of the line. */
3118 while (x != x2)
3119 {
3120 gln_linegraphics_plot_clip (x, y, colour1, colour2);
3121 if (balance >= 0)
3122 {
3123 y += incy;
3124 balance -= dx;
3125 }
3126 balance += dy;
3127 x += incx;
3128 }
3129 gln_linegraphics_plot_clip (x, y, colour1, colour2);
3130 }
3131 else
3132 {
3133 dx <<= 1;
3134 balance = dx - dy;
3135 dy <<= 1;
3136
3137 /* Loop until we reach the end point of the line. */
3138 while (y != y2)
3139 {
3140 gln_linegraphics_plot_clip (x, y, colour1, colour2);
3141 if (balance >= 0)
3142 {
3143 x += incx;
3144 balance -= dy;
3145 }
3146 balance += dx;
3147 y += incy;
3148 }
3149 gln_linegraphics_plot_clip (x, y, colour1, colour2);
3150 }
3151 }
3152
3153
3154 /*
3155 * gln_linegraphics_push_fill_segment()
3156 * gln_linegraphics_pop_fill_segment()
3157 * gln_linegraphics_fill_4way_if()
3158 *
3159 * Area fill algorithm, set a region to colour1 if it is currently set to
3160 * colour2. This function is a derivation of Paul Heckbert's Seed Fill,
3161 * from "Graphics Gems", Academic Press, 1990, which fills 4-connected
3162 * neighbors.
3163 *
3164 * The main modification is to make segment stacks growable, through the
3165 * helper push and pop functions. There is also a small adaptation to
3166 * check explicitly for color2, to meet the Level 9 API.
3167 */
3168 static void
3169 gln_linegraphics_push_fill_segment (int y, int xl, int xr, int dy)
3170 {
3171 /* Clip points outside the graphics context. */
3172 if (!(y + dy < 0 || y + dy >= gln_graphics_height))
3173 {
3174 int length, allocation;
3175
3176 length = ++gln_linegraphics_fill_segments_length;
3177 allocation = gln_linegraphics_fill_segments_allocation;
3178
3179 /* Grow the segments stack if required, successively doubling. */
3180 if (length > allocation)
3181 {
3182 size_t bytes;
3183
3184 allocation = allocation == 0 ? 1 : allocation << 1;
3185
3186 bytes = allocation * sizeof (*gln_linegraphics_fill_segments);
3187 gln_linegraphics_fill_segments =
3188 gln_realloc (gln_linegraphics_fill_segments, bytes);
3189 }
3190
3191 /* Push top of segments stack. */
3192 gln_linegraphics_fill_segments[length - 1].y = y;
3193 gln_linegraphics_fill_segments[length - 1].xl = xl;
3194 gln_linegraphics_fill_segments[length - 1].xr = xr;
3195 gln_linegraphics_fill_segments[length - 1].dy = dy;
3196
3197 /* Write back local dimensions copies. */
3198 gln_linegraphics_fill_segments_length = length;
3199 gln_linegraphics_fill_segments_allocation = allocation;
3200 }
3201 }
3202
3203 static void
3204 gln_linegraphics_pop_fill_segment (int *y, int *xl, int *xr, int *dy)
3205 {
3206 int length;
3207 assert (gln_linegraphics_fill_segments_length > 0);
3208
3209 length = --gln_linegraphics_fill_segments_length;
3210
3211 /* Pop top of segments stack. */
3212 *y = gln_linegraphics_fill_segments[length].y;
3213 *xl = gln_linegraphics_fill_segments[length].xl;
3214 *xr = gln_linegraphics_fill_segments[length].xr;
3215 *dy = gln_linegraphics_fill_segments[length].dy;
3216 }
3217
3218 static void
3219 gln_linegraphics_fill_4way_if (int x, int y, int colour1, int colour2)
3220 {
3221 /* Ignore any odd request where there will be no colour changes. */
3222 if (colour1 == colour2)
3223 return;
3224
3225 /* Clip fill requests to visible graphics region. */
3226 if (x >= 0 && x < gln_graphics_width && y >= 0 && y < gln_graphics_height)
3227 {
3228 int left, x1, x2, dy, x_lo, x_hi;
3229
3230 /*
3231 * Level 9 API; explicit check for a match against colour2. This also
3232 * covers the standard Seed Fill check that old pixel value should not
3233 * equal colour1, because of the color1 == colour2 comparison above.
3234 */
3235 if (gln_linegraphics_get_pixel (x, y) != colour2)
3236 return;
3237
3238 /*
3239 * Set up inclusive window dimension to ease algorithm translation.
3240 * The original worked with inclusive rectangle limits.
3241 */
3242 x_lo = 0;
3243 x_hi = gln_graphics_width - 1;
3244
3245 /*
3246 * The first of these is "needed in some cases", the second is the seed
3247 * segment, popped first.
3248 */
3249 gln_linegraphics_push_fill_segment (y, x, x, 1);
3250 gln_linegraphics_push_fill_segment (y + 1, x, x, -1);
3251
3252 while (gln_linegraphics_fill_segments_length > 0)
3253 {
3254 /* Pop segment off stack and add delta to y coord. */
3255 gln_linegraphics_pop_fill_segment (&y, &x1, &x2, &dy);
3256 y += dy;
3257
3258 /*
3259 * Segment of scan line y-dy for x1<=x<=x2 was previously filled,
3260 * now explore adjacent pixels in scan line y.
3261 */
3262 for (x = x1;
3263 x >= x_lo && gln_linegraphics_get_pixel (x, y) == colour2;
3264 x--)
3265 {
3266 gln_linegraphics_set_pixel (x, y, colour1);
3267 }
3268
3269 if (x >= x1)
3270 goto skip;
3271
3272 left = x + 1;
3273 if (left < x1)
3274 {
3275 /* Leak on left? */
3276 gln_linegraphics_push_fill_segment (y, left, x1 - 1, -dy);
3277 }
3278
3279 x = x1 + 1;
3280 do
3281 {
3282 for (;
3283 x <= x_hi && gln_linegraphics_get_pixel (x, y) == colour2;
3284 x++)
3285 {
3286 gln_linegraphics_set_pixel (x, y, colour1);
3287 }
3288
3289 gln_linegraphics_push_fill_segment (y, left, x - 1, dy);
3290
3291 if (x > x2 + 1)
3292 {
3293 /* Leak on right? */
3294 gln_linegraphics_push_fill_segment (y, x2 + 1, x - 1, -dy);
3295 }
3296
3297 skip: for (x++;
3298 x <= x2 && gln_linegraphics_get_pixel (x, y) != colour2;
3299 x++)
3300 ;
3301
3302 left = x;
3303 }
3304 while (x <= x2);
3305 }
3306 }
3307 }
3308
3309
3310 /*
3311 * os_cleargraphics()
3312 * os_setcolour()
3313 * os_drawline()
3314 * os_fill()
3315 *
3316 * Interpreter entry points for line drawing graphics. All calls to these
3317 * are ignored if line drawing mode is not set.
3318 */
3319 void
3320 os_cleargraphics (void)
3321 {
3322 if (gln_graphics_interpreter_state == GLN_GRAPHICS_LINE_MODE)
3323 gln_linegraphics_clear_context ();
3324 }
3325
3326 void
3327 os_setcolour (int colour, int index)
3328 {
3329 if (gln_graphics_interpreter_state == GLN_GRAPHICS_LINE_MODE)
3330 gln_linegraphics_set_palette_color (colour, index);
3331 }
3332
3333 void
3334 os_drawline (int x1, int y1, int x2, int y2, int colour1, int colour2)
3335 {
3336 if (gln_graphics_interpreter_state == GLN_GRAPHICS_LINE_MODE)
3337 gln_linegraphics_draw_line_if (x1, y1, x2, y2, colour1, colour2);
3338 }
3339
3340 void
3341 os_fill (int x, int y, int colour1, int colour2)
3342 {
3343 if (gln_graphics_interpreter_state == GLN_GRAPHICS_LINE_MODE)
3344 gln_linegraphics_fill_4way_if (x, y, colour1, colour2);
3345 }
3346
3347
3348 /*
3349 * gln_linegraphics_process()
3350 *
3351 * Process as many graphics opcodes as are available, constructing the
3352 * resulting image as a bitmap. When complete, treat as normal bitmaps.
3353 */
3354 static void
3355 gln_linegraphics_process (void)
3356 {
3357 /*
3358 * If interpreter graphics are not set to line mode, ignore any call that
3359 * arrives here.
3360 */
3361 if (gln_graphics_interpreter_state == GLN_GRAPHICS_LINE_MODE)
3362 {
3363 int opcodes_count;
3364
3365 /* Run all the available graphics opcodes. */
3366 for (opcodes_count = 0; RunGraphics (); )
3367 {
3368 opcodes_count++;
3369 glk_tick ();
3370 }
3371
3372 /*
3373 * If graphics is enabled and we created an image with graphics
3374 * opcodes above, open a graphics window and start bitmap display.
3375 */
3376 if (gln_graphics_enabled && opcodes_count > 0)
3377 {
3378 if (gln_graphics_open ())
3379 {
3380 /* Set the new picture flag, and start the updating "thread". */
3381 gln_graphics_new_picture = TRUE;
3382 gln_graphics_start ();
3383 }
3384 }
3385 }
3386 }
3387
3388
3389 /*
3390 * gln_linegraphics_cleanup()
3391 *
3392 * Free memory resources allocated by line graphics functions. Called on
3393 * game end.
3394 */
3395 static void
3396 gln_linegraphics_cleanup (void)
3397 {
3398 free (gln_linegraphics_fill_segments);
3399 gln_linegraphics_fill_segments = NULL;
3400
3401 gln_linegraphics_fill_segments_allocation = 0;
3402 gln_linegraphics_fill_segments_length = 0;
3403 }
3404
3405
3406 /*---------------------------------------------------------------------*/
3407 /* Glk picture dispatch (bitmap or line), and timer arbitration */
3408 /*---------------------------------------------------------------------*/
3409
3410 /*
3411 * Note of the current set graphics mode, to detect changes in mode from
3412 * the core interpreter.
3413 */
3414 static int gln_graphics_current_mode = -1;
3415
3416 /* Note indicating if the graphics "thread" is temporarily suspended. */
3417 static int gln_graphics_suspended = FALSE;
3418
3419
3420 /*
3421 * os_graphics()
3422 *
3423 * Called by the main interpreter to turn graphics on and off. Mode 0
3424 * turns graphics off, mode 1 is line drawing graphics, and mode 2 is
3425 * bitmap graphics.
3426 *
3427 * This function tracks the current state of interpreter graphics setting
3428 * using gln_graphics_interpreter_state.
3429 */
3430 void
3431 os_graphics (int mode)
3432 {
3433 /* Ignore the call unless it changes the graphics mode. */
3434 if (mode != gln_graphics_current_mode)
3435 {
3436 /* Set tracked interpreter state given the input mode. */
3437 switch (mode)
3438 {
3439 case 0:
3440 gln_graphics_interpreter_state = GLN_GRAPHICS_OFF;
3441 break;
3442
3443 case 1:
3444 gln_graphics_interpreter_state = GLN_GRAPHICS_LINE_MODE;
3445 break;
3446
3447 case 2:
3448 /* If no graphics bitmaps were detected, ignore this call. */
3449 if (!gln_graphics_bitmap_directory
3450 || gln_graphics_bitmap_type == NO_BITMAPS)
3451 return;
3452
3453 gln_graphics_interpreter_state = GLN_GRAPHICS_BITMAP_MODE;
3454 break;
3455 }
3456
3457 /* Given the interpreter state, update graphics activities. */
3458 switch (gln_graphics_interpreter_state)
3459 {
3460 case GLN_GRAPHICS_OFF:
3461
3462 /* If currently displaying graphics, stop and close window. */
3463 if (gln_graphics_enabled && gln_graphics_are_displayed ())
3464 {
3465 gln_graphics_stop ();
3466 gln_graphics_close ();
3467 }
3468 break;
3469
3470 case GLN_GRAPHICS_LINE_MODE:
3471 case GLN_GRAPHICS_BITMAP_MODE:
3472
3473 /* Create a new graphics context on switch to line mode. */
3474 if (gln_graphics_interpreter_state == GLN_GRAPHICS_LINE_MODE)
3475 gln_linegraphics_create_context ();
3476
3477 /*
3478 * If we have a picture loaded already, restart graphics. If not,
3479 * we'll delay this until one is supplied by a call to
3480 * os_show_bitmap().
3481 */
3482 if (gln_graphics_enabled && gln_graphics_bitmap)
3483 {
3484 if (gln_graphics_open ())
3485 gln_graphics_restart ();
3486 }
3487 break;
3488 }
3489
3490 /* Note the current mode so changes can be detected. */
3491 gln_graphics_current_mode = mode;
3492 }
3493 }
3494
3495
3496 /*
3497 * gln_arbitrate_request_timer_events()
3498 *
3499 * Shim function for glk_request_timer_events(), this function should be
3500 * called by other functional areas in place of the main timer event setting
3501 * function. It suspends graphics if busy when setting timer events, and
3502 * resumes graphics if necessary when clearing timer events.
3503 *
3504 * On resuming, it calls the graphics timeout function to simulate the
3505 * timeout that has (probably) been missed. This also ensures that tight
3506 * loops that enable then disable timers using this function don't lock out
3507 * the graphics completely.
3508 *
3509 * Use only in paired calls, the first non-zero, the second zero, and use
3510 * no graphics functions between calls.
3511 */
3512 static void
3513 gln_arbitrate_request_timer_events (glui32 millisecs)
3514 {
3515 if (millisecs > 0)
3516 {
3517 /* Setting timer events; suspend graphics if currently active. */
3518 if (gln_graphics_active)
3519 {
3520 gln_graphics_suspended = TRUE;
3521 gln_graphics_stop ();
3522 }
3523
3524 /* Set timer events as requested. */
3525 glk_request_timer_events (millisecs);
3526 }
3527 else
3528 {
3529 /*
3530 * Resume graphics if currently suspended, otherwise cancel timer
3531 * events as requested by the caller.
3532 */
3533 if (gln_graphics_suspended)
3534 {
3535 gln_graphics_suspended = FALSE;
3536 gln_graphics_start ();
3537
3538 /* Simulate the "missed" graphics timeout. */
3539 gln_graphics_timeout ();
3540 }
3541 else
3542 glk_request_timer_events (0);
3543 }
3544 }
3545
3546
3547 /*---------------------------------------------------------------------*/
3548 /* Glk port infinite loop detection functions */
3549 /*---------------------------------------------------------------------*/
3550
3551 /* Short timeout to wait purely in order to get the display updated. */
3552 static const glui32 GLN_WATCHDOG_FIXUP = 50;
3553
3554 /*
3555 * Timestamp of the last watchdog tick call, and timeout. This is used to
3556 * monitor the elapsed time since the interpreter made an I/O call. If it
3557 * remains silent for long enough, set by the timeout, we'll offer the
3558 * option to end the game. A timeout of zero disables the watchdog.
3559 */
3560 static time_t gln_watchdog_monitor = 0;
3561 static double gln_watchdog_timeout_secs = 0.0;
3562
3563 /*
3564 * To save thrashing in time(), we want to check for timeouts less frequently
3565 * than we're polled. Here's the control for that.
3566 */
3567 static int gln_watchdog_check_period = 0,
3568 gln_watchdog_check_counter = 0;
3569
3570
3571 /*
3572 * gln_watchdog_start()
3573 * gln_watchdog_stop()
3574 *
3575 * Start and stop watchdog monitoring.
3576 */
3577 static void
3578 gln_watchdog_start (int timeout, int period)
3579 {
3580 assert (timeout > 0 && period > 0);
3581
3582 gln_watchdog_timeout_secs = (double) timeout;
3583 gln_watchdog_check_period = period;
3584 gln_watchdog_check_counter = period;
3585 gln_watchdog_monitor = time (NULL);
3586 }
3587
3588 static void
3589 gln_watchdog_stop (void)
3590 {
3591 gln_watchdog_timeout_secs = 0;
3592 }
3593
3594
3595 /*
3596 * gln_watchdog_tick()
3597 *
3598 * Set the watchdog timestamp to the current system time.
3599 *
3600 * This function should be called just before almost every os_* function
3601 * returns to the interpreter, as a means of timing how long the interpreter
3602 * dwells in running game code.
3603 */
3604 static void
3605 gln_watchdog_tick (void)
3606 {
3607 gln_watchdog_monitor = time (NULL);
3608 }
3609
3610
3611 /*
3612 * gln_watchdog_has_timed_out()
3613 *
3614 * Check to see if too much time has elapsed since the last tick. If it has,
3615 * offer the option to stop the game, and if accepted, return TRUE. Otherwise,
3616 * if no timeout, or if the watchdog is disabled, return FALSE.
3617 *
3618 * This function only checks every N calls; it's called extremely frequently
3619 * from opcode handling, and will thrash in time() if it checks on each call.
3620 */
3621 static int
3622 gln_watchdog_has_timed_out (void)
3623 {
3624 /* If loop detection is off or the timeout is set to zero, do nothing. */
3625 if (gln_loopcheck_enabled && gln_watchdog_timeout_secs > 0)
3626 {
3627 time_t now;
3628 double delta_time;
3629
3630 /*
3631 * Wait until we've seen enough calls to make a timeout check. If we
3632 * haven't, return FALSE, otherwise reset the counter and continue.
3633 */
3634 if (--gln_watchdog_check_counter > 0)
3635 return FALSE;
3636 else
3637 gln_watchdog_check_counter = gln_watchdog_check_period;
3638
3639 /*
3640 * Determine how much time has passed, and offer to end the game if it
3641 * exceeds the allowable timeout.
3642 */
3643 now = time (NULL);
3644 delta_time = difftime (now, gln_watchdog_monitor);
3645
3646 if (delta_time >= gln_watchdog_timeout_secs)
3647 {
3648 if (gln_confirm ("\nThe game may be in an infinite loop. Do you"
3649 " want to stop it? [Y or N] "))
3650 {
3651 gln_watchdog_tick ();
3652 return TRUE;
3653 }
3654
3655 /*
3656 * If we have timers, set a really short timeout and let it expire.
3657 * This is to force a display update with the response of the
3658 * confirm -- without this, we may not get a screen update for a
3659 * while since at this point the game isn't, by definition, doing
3660 * any input or output. If we don't have timers, no biggie.
3661 */
3662 if (glk_gestalt (gestalt_Timer, 0))
3663 {
3664 event_t event;
3665
3666 gln_arbitrate_request_timer_events (GLN_WATCHDOG_FIXUP);
3667 gln_event_wait (evtype_Timer, &event);
3668 gln_arbitrate_request_timer_events (0);
3669 }
3670
3671 /* Reset the monitor and drop into FALSE return -- stop rejected. */
3672 gln_watchdog_tick ();
3673 }
3674 }
3675
3676 /* No timeout indicated, or offer rejected by the user. */
3677 return FALSE;
3678 }
3679
3680
3681 /*---------------------------------------------------------------------*/
3682 /* Glk port status line functions */
3683 /*---------------------------------------------------------------------*/
3684
3685 /* Default width used for non-windowing Glk status lines. */
3686 static const int GLN_DEFAULT_STATUS_WIDTH = 74;
3687
3688
3689 /*
3690 * gln_status_update()
3691 *
3692 * Update the information in the status window with the current contents of
3693 * the current game identity string, or a default string if no game identity
3694 * could be established.
3695 */
3696 static void
3697 gln_status_update (void)
3698 {
3699 glui32 width, height;
3700 assert (gln_status_window);
3701
3702 glk_window_get_size (gln_status_window, &width, &height);
3703 if (height > 0)
3704 {
3705 const char *game_name;
3706
3707 glk_window_clear (gln_status_window);
3708 glk_window_move_cursor (gln_status_window, 0, 0);
3709 glk_set_window (gln_status_window);
3710
3711 /*
3712 * Try to establish a game identity to display; if none, use a standard
3713 * message instead.
3714 */
3715 game_name = gln_gameid_get_game_name ();
3716 glk_put_string (game_name ? (char *) game_name
3717 : "Glk Level 9 version 5.2");
3718
3719 glk_set_window (gln_main_window);
3720 }
3721 }
3722
3723
3724 /*
3725 * gln_status_print()
3726 *
3727 * Print the current contents of the game identity out in the main window,
3728 * if it has changed since the last call. This is for non-windowing Glk
3729 * libraries.
3730 *
3731 * To save memory management hassles, this function uses the CRC functions
3732 * to detect changes of game identity string, and gambles a little on the
3733 * belief that two games' strings won't have the same CRC.
3734 */
3735 static void
3736 gln_status_print (void)
3737 {
3738 static int is_initialized = FALSE;
3739 static gln_uint16 crc = 0;
3740
3741 const char *game_name;
3742
3743 /* Get the current game name, and do nothing if none available. */
3744 game_name = gln_gameid_get_game_name ();
3745 if (game_name)
3746 {
3747 gln_uint16 new_crc;
3748
3749 /*
3750 * If not the first call and the game identity string has not changed,
3751 * again, do nothing.
3752 */
3753 new_crc = gln_get_buffer_crc (game_name, strlen (game_name), 0);
3754 if (!is_initialized || new_crc != crc)
3755 {
3756 int index;
3757
3758 #ifndef GARGLK
3759 /* Set fixed width font to try to preserve status line formatting. */
3760 glk_set_style (style_Preformatted);
3761 #endif
3762
3763 /* Bracket, and output the extracted game name. */
3764 glk_put_string ("[ ");
3765 glk_put_string ((char *) game_name);
3766
3767 for (index = strlen (game_name);
3768 index <= GLN_DEFAULT_STATUS_WIDTH; index++)
3769 glk_put_char (' ');
3770 glk_put_string (" ]\n");
3771
3772 crc = new_crc;
3773 is_initialized = TRUE;
3774 }
3775 }
3776 }
3777
3778
3779 /*
3780 * gln_status_notify()
3781 *
3782 * Front end function for updating status. Either updates the status window
3783 * or prints the status line to the main window.
3784 */
3785 static void
3786 gln_status_notify (void)
3787 {
3788 if (gln_status_window)
3789 gln_status_update ();
3790 else
3791 gln_status_print ();
3792 }
3793
3794
3795 /*
3796 * gln_status_redraw()
3797 *
3798 * Redraw the contents of any status window with the buffered status string.
3799 * This function should be called on the appropriate Glk window resize and
3800 * arrange events.
3801 */
3802 static void
3803 gln_status_redraw (void)
3804 {
3805 if (gln_status_window)
3806 {
3807 winid_t parent;
3808
3809 /*
3810 * Rearrange the status window, without changing its actual arrangement
3811 * in any way. This is a hack to work round incorrect window repainting
3812 * in Xglk; it forces a complete repaint of affected windows on Glk
3813 * window resize and arrange events, and works in part because Xglk
3814 * doesn't check for actual arrangement changes in any way before
3815 * invalidating its windows. The hack should be harmless to Glk
3816 * libraries other than Xglk, moreover, we're careful to activate it
3817 * only on resize and arrange events.
3818 */
3819 parent = glk_window_get_parent (gln_status_window);
3820 glk_window_set_arrangement (parent,
3821 winmethod_Above | winmethod_Fixed, 1, NULL);
3822
3823 gln_status_update ();
3824 }
3825 }
3826
3827
3828 /*---------------------------------------------------------------------*/
3829 /* Glk port output functions */
3830 /*---------------------------------------------------------------------*/
3831
3832 /*
3833 * Flag for if the user entered "help" as their last input, or if hints have
3834 * been silenced as a result of already using a Glk command.
3835 */
3836 static int gln_help_requested = FALSE,
3837 gln_help_hints_silenced = FALSE;
3838
3839 /*
3840 * Output buffer. We receive characters one at a time, and it's a bit
3841 * more efficient for everyone if we buffer them, and output a complete
3842 * string on a flush call.
3843 */
3844 static char *gln_output_buffer = NULL;
3845 static int gln_output_allocation = 0,
3846 gln_output_length = 0;
3847
3848 /*
3849 * Output activity flag. Set when os_printchar() is called, and queried
3850 * periodically by os_readchar(). Helps os_readchar() judge whether it must
3851 * request input, or when it's being used as a crude scroll control.
3852 */
3853 static int gln_output_activity = FALSE;
3854
3855 /*
3856 * Flag to indicate if the last buffer flushed looked like it ended in a
3857 * "> " prompt. Some later games switch to this mode after a while, and
3858 * it's nice not to duplicate this prompt with our own.
3859 */
3860 static int gln_output_prompt = FALSE;
3861
3862
3863 /*
3864 * gln_output_notify()
3865 *
3866 * Register recent text output from the interpreter. This function is
3867 * called by os_printchar().
3868 */
3869 static void
3870 gln_output_notify (void)
3871 {
3872 gln_output_activity = TRUE;
3873 }
3874
3875
3876 /*
3877 * gln_recent_output()
3878 *
3879 * Return TRUE if the interpreter has recently output text, FALSE otherwise.
3880 * Clears the flag, so that more output text is required before the next
3881 * call returns TRUE.
3882 */
3883 static int
3884 gln_recent_output (void)
3885 {
3886 int result;
3887
3888 result = gln_output_activity;
3889 gln_output_activity = FALSE;
3890
3891 return result;
3892 }
3893
3894
3895 /*
3896 * gln_output_register_help_request()
3897 * gln_output_silence_help_hints()
3898 * gln_output_provide_help_hint()
3899 *
3900 * Register a request for help, and print a note of how to get Glk command
3901 * help from the interpreter unless silenced.
3902 */
3903 static void
3904 gln_output_register_help_request (void)
3905 {
3906 gln_help_requested = TRUE;
3907 }
3908
3909 static void
3910 gln_output_silence_help_hints (void)
3911 {
3912 gln_help_hints_silenced = TRUE;
3913 }
3914
3915 static void
3916 gln_output_provide_help_hint (void)
3917 {
3918 if (gln_help_requested && !gln_help_hints_silenced)
3919 {
3920 glk_set_style (style_Emphasized);
3921 glk_put_string ("[Try 'glk help' for help on special interpreter"
3922 " commands]\n");
3923
3924 gln_help_requested = FALSE;
3925 glk_set_style (style_Normal);
3926 }
3927 }
3928
3929
3930 /*
3931 * gln_game_prompted()
3932 *
3933 * Return TRUE if the last game output appears to have been a "> " prompt.
3934 * Once called, the flag is reset to FALSE, and requires more game output
3935 * to set it again.
3936 */
3937 static int
3938 gln_game_prompted (void)
3939 {
3940 int result;
3941
3942 result = gln_output_prompt;
3943 gln_output_prompt = FALSE;
3944
3945 return result;
3946 }
3947
3948
3949 /*
3950 * gln_detect_game_prompt()
3951 *
3952 * See if the last non-newline-terminated line in the output buffer seems
3953 * to be a prompt, and set the game prompted flag if it does, otherwise
3954 * clear it.
3955 */
3956 static void
3957 gln_detect_game_prompt (void)
3958 {
3959 int index;
3960
3961 gln_output_prompt = FALSE;
3962
3963 /*
3964 * Search for a prompt across any last unterminated buffered line; a prompt
3965 * is any non-space character on that line.
3966 */
3967 for (index = gln_output_length - 1;
3968 index >= 0 && gln_output_buffer[index] != '\n'; index--)
3969 {
3970 if (gln_output_buffer[index] != ' ')
3971 {
3972 gln_output_prompt = TRUE;
3973 break;
3974 }
3975 }
3976 }
3977
3978
3979 /*
3980 * gln_output_delete()
3981 *
3982 * Delete all buffered output text. Free all malloc'ed buffer memory, and
3983 * return the buffer variables to their initial values.
3984 */
3985 static void
3986 gln_output_delete (void)
3987 {
3988 free (gln_output_buffer);
3989 gln_output_buffer = NULL;
3990 gln_output_allocation = gln_output_length = 0;
3991 }
3992
3993
3994 /*
3995 * gln_output_flush()
3996 *
3997 * Flush any buffered output text to the Glk main window, and clear the
3998 * buffer. Check in passing for game prompts that duplicate our's.
3999 */
4000 static void
4001 gln_output_flush (void)
4002 {
4003 assert (glk_stream_get_current ());
4004
4005 if (gln_output_length > 0)
4006 {
4007 /*
4008 * See if the game issued a standard prompt, then print the buffer to
4009 * the main window. If providing a help hint, position that before
4010 * the game's prompt (if any).
4011 */
4012 gln_detect_game_prompt ();
4013
4014 if (gln_output_prompt)
4015 {
4016 int index;
4017
4018 for (index = gln_output_length - 1;
4019 index >= 0 && gln_output_buffer[index] != '\n'; )
4020 index--;
4021
4022 glk_put_buffer (gln_output_buffer, index + 1);
4023 gln_output_provide_help_hint ();
4024 glk_put_buffer (gln_output_buffer + index + 1,
4025 gln_output_length - index - 1);
4026 }
4027 else
4028 {
4029 glk_put_buffer (gln_output_buffer, gln_output_length);
4030 gln_output_provide_help_hint ();
4031 }
4032
4033 gln_output_delete ();
4034 }
4035 }
4036
4037
4038 /*
4039 * os_printchar()
4040 *
4041 * Buffer a character for eventual printing to the main window.
4042 */
4043 void
4044 os_printchar (char c)
4045 {
4046 int bytes;
4047 assert (gln_output_length <= gln_output_allocation);
4048
4049 /* Grow the output buffer if necessary. */
4050 for (bytes = gln_output_allocation; bytes < gln_output_length + 1; )
4051 bytes = bytes == 0 ? 1 : bytes << 1;
4052
4053 if (bytes > gln_output_allocation)
4054 {
4055 gln_output_buffer = gln_realloc (gln_output_buffer, bytes);
4056 gln_output_allocation = bytes;
4057 }
4058
4059 /*
4060 * Add the character to the buffer, handling return as a newline, and
4061 * note that the game created some output.
4062 */
4063 gln_output_buffer[gln_output_length++] = (c == '\r' ? '\n' : c);
4064 gln_output_notify ();
4065 }
4066
4067
4068 /*
4069 * gln_styled_string()
4070 * gln_styled_char()
4071 * gln_standout_string()
4072 * gln_standout_char()
4073 * gln_normal_string()
4074 * gln_normal_char()
4075 * gln_header_string()
4076 * gln_banner_string()
4077 *
4078 * Convenience functions to print strings in assorted styles. A standout
4079 * string is one that hints that it's from the interpreter, not the game.
4080 */
4081 static void
4082 gln_styled_string (glui32 style, const char *message)
4083 {
4084 assert (message);
4085
4086 glk_set_style (style);
4087 glk_put_string ((char *) message);
4088 glk_set_style (style_Normal);
4089 }
4090
4091 static void
4092 gln_styled_char (glui32 style, char c)
4093 {
4094 char buffer[2];
4095
4096 buffer[0] = c;
4097 buffer[1] = '\0';
4098 gln_styled_string (style, buffer);
4099 }
4100
4101 static void
4102 gln_standout_string (const char *message)
4103 {
4104 gln_styled_string (style_Emphasized, message);
4105 }
4106
4107 static void
4108 gln_standout_char (char c)
4109 {
4110 gln_styled_char (style_Emphasized, c);
4111 }
4112
4113 static void
4114 gln_normal_string (const char *message)
4115 {
4116 gln_styled_string (style_Normal, message);
4117 }
4118
4119 static void
4120 gln_normal_char (char c)
4121 {
4122 gln_styled_char (style_Normal, c);
4123 }
4124
4125 static void
4126 gln_header_string (const char *message)
4127 {
4128 gln_styled_string (style_Header, message);
4129 }
4130
4131 static void
4132 gln_banner_string (const char *message)
4133 {
4134 gln_styled_string (style_Subheader, message);
4135 }
4136
4137
4138 /*
4139 * os_flush()
4140 *
4141 * Handle a core interpreter call to flush the output buffer. Because Glk
4142 * only flushes its buffers and displays text on glk_select(), we can ignore
4143 * these calls as long as we call glk_output_flush() when reading line or
4144 * character input.
4145 *
4146 * Taking os_flush() at face value can cause game text to appear before status
4147 * line text where we are working with a non-windowing Glk, so it's best
4148 * ignored where we can.
4149 */
4150 void
4151 os_flush (void)
4152 {
4153 }
4154
4155
4156 /*---------------------------------------------------------------------*/
4157 /* Glk command escape functions */
4158 /*---------------------------------------------------------------------*/
4159
4160 /*
4161 * gln_command_script()
4162 *
4163 * Turn game output scripting (logging) on and off.
4164 */
4165 static void
4166 gln_command_script (const char *argument)
4167 {
4168 assert (argument);
4169
4170 if (gln_strcasecmp (argument, "on") == 0)
4171 {
4172 frefid_t fileref;
4173
4174 if (gln_transcript_stream)
4175 {
4176 gln_normal_string ("Glk transcript is already on.\n");
4177 return;
4178 }
4179
4180 fileref = glk_fileref_create_by_prompt (fileusage_Transcript
4181 | fileusage_TextMode,
4182 filemode_WriteAppend, 0);
4183 if (!fileref)
4184 {
4185 gln_standout_string ("Glk transcript failed.\n");
4186 return;
4187 }
4188
4189 gln_transcript_stream = glk_stream_open_file (fileref,
4190 filemode_WriteAppend, 0);
4191 glk_fileref_destroy (fileref);
4192 if (!gln_transcript_stream)
4193 {
4194 gln_standout_string ("Glk transcript failed.\n");
4195 return;
4196 }
4197
4198 glk_window_set_echo_stream (gln_main_window, gln_transcript_stream);
4199
4200 gln_normal_string ("Glk transcript is now on.\n");
4201 }
4202
4203 else if (gln_strcasecmp (argument, "off") == 0)
4204 {
4205 if (!gln_transcript_stream)
4206 {
4207 gln_normal_string ("Glk transcript is already off.\n");
4208 return;
4209 }
4210
4211 glk_stream_close (gln_transcript_stream, NULL);
4212 gln_transcript_stream = NULL;
4213
4214 glk_window_set_echo_stream (gln_main_window, NULL);
4215
4216 gln_normal_string ("Glk transcript is now off.\n");
4217 }
4218
4219 else if (strlen (argument) == 0)
4220 {
4221 gln_normal_string ("Glk transcript is ");
4222 gln_normal_string (gln_transcript_stream ? "on" : "off");
4223 gln_normal_string (".\n");
4224 }
4225
4226 else
4227 {
4228 gln_normal_string ("Glk transcript can be ");
4229 gln_standout_string ("on");
4230 gln_normal_string (", or ");
4231 gln_standout_string ("off");
4232 gln_normal_string (".\n");
4233 }
4234 }
4235
4236
4237 /*
4238 * gln_command_inputlog()
4239 *
4240 * Turn game input logging on and off.
4241 */
4242 static void
4243 gln_command_inputlog (const char *argument)
4244 {
4245 assert (argument);
4246
4247 if (gln_strcasecmp (argument, "on") == 0)
4248 {
4249 frefid_t fileref;
4250
4251 if (gln_inputlog_stream)
4252 {
4253 gln_normal_string ("Glk input logging is already on.\n");
4254 return;
4255 }
4256
4257 fileref = glk_fileref_create_by_prompt (fileusage_InputRecord
4258 | fileusage_BinaryMode,
4259 filemode_WriteAppend, 0);
4260 if (!fileref)
4261 {
4262 gln_standout_string ("Glk input logging failed.\n");
4263 return;
4264 }
4265
4266 gln_inputlog_stream = glk_stream_open_file (fileref,
4267 filemode_WriteAppend, 0);
4268 glk_fileref_destroy (fileref);
4269 if (!gln_inputlog_stream)
4270 {
4271 gln_standout_string ("Glk input logging failed.\n");
4272 return;
4273 }
4274
4275 gln_normal_string ("Glk input logging is now on.\n");
4276 }
4277
4278 else if (gln_strcasecmp (argument, "off") == 0)
4279 {
4280 if (!gln_inputlog_stream)
4281 {
4282 gln_normal_string ("Glk input logging is already off.\n");
4283 return;
4284 }
4285
4286 glk_stream_close (gln_inputlog_stream, NULL);
4287 gln_inputlog_stream = NULL;
4288
4289 gln_normal_string ("Glk input log is now off.\n");
4290 }
4291
4292 else if (strlen (argument) == 0)
4293 {
4294 gln_normal_string ("Glk input logging is ");
4295 gln_normal_string (gln_inputlog_stream ? "on" : "off");
4296 gln_normal_string (".\n");
4297 }
4298
4299 else
4300 {
4301 gln_normal_string ("Glk input logging can be ");
4302 gln_standout_string ("on");
4303 gln_normal_string (", or ");
4304 gln_standout_string ("off");
4305 gln_normal_string (".\n");
4306 }
4307 }
4308
4309
4310 /*
4311 * gln_command_readlog()
4312 *
4313 * Set the game input log, to read input from a file.
4314 */
4315 static void
4316 gln_command_readlog (const char *argument)
4317 {
4318 assert (argument);
4319
4320 if (gln_strcasecmp (argument, "on") == 0)
4321 {
4322 frefid_t fileref;
4323
4324 if (gln_readlog_stream)
4325 {
4326 gln_normal_string ("Glk read log is already on.\n");
4327 return;
4328 }
4329
4330 fileref = glk_fileref_create_by_prompt (fileusage_InputRecord
4331 | fileusage_BinaryMode,
4332 filemode_Read, 0);
4333 if (!fileref)
4334 {
4335 gln_standout_string ("Glk read log failed.\n");
4336 return;
4337 }
4338
4339 if (!glk_fileref_does_file_exist (fileref))
4340 {
4341 glk_fileref_destroy (fileref);
4342 gln_standout_string ("Glk read log failed.\n");
4343 return;
4344 }
4345
4346 gln_readlog_stream = glk_stream_open_file (fileref, filemode_Read, 0);
4347 glk_fileref_destroy (fileref);
4348 if (!gln_readlog_stream)
4349 {
4350 gln_standout_string ("Glk read log failed.\n");
4351 return;
4352 }
4353
4354 gln_normal_string ("Glk read log is now on.\n");
4355 }
4356
4357 else if (gln_strcasecmp (argument, "off") == 0)
4358 {
4359 if (!gln_readlog_stream)
4360 {
4361 gln_normal_string ("Glk read log is already off.\n");
4362 return;
4363 }
4364
4365 glk_stream_close (gln_readlog_stream, NULL);
4366 gln_readlog_stream = NULL;
4367
4368 gln_normal_string ("Glk read log is now off.\n");
4369 }
4370
4371 else if (strlen (argument) == 0)
4372 {
4373 gln_normal_string ("Glk read log is ");
4374 gln_normal_string (gln_readlog_stream ? "on" : "off");
4375 gln_normal_string (".\n");
4376 }
4377
4378 else
4379 {
4380 gln_normal_string ("Glk read log can be ");
4381 gln_standout_string ("on");
4382 gln_normal_string (", or ");
4383 gln_standout_string ("off");
4384 gln_normal_string (".\n");
4385 }
4386 }
4387
4388
4389 /*
4390 * gln_command_abbreviations()
4391 *
4392 * Turn abbreviation expansions on and off.
4393 */
4394 static void
4395 gln_command_abbreviations (const char *argument)
4396 {
4397 assert (argument);
4398
4399 if (gln_strcasecmp (argument, "on") == 0)
4400 {
4401 if (gln_abbreviations_enabled)
4402 {
4403 gln_normal_string ("Glk abbreviation expansions are already on.\n");
4404 return;
4405 }
4406
4407 gln_abbreviations_enabled = TRUE;
4408 gln_normal_string ("Glk abbreviation expansions are now on.\n");
4409 }
4410
4411 else if (gln_strcasecmp (argument, "off") == 0)
4412 {
4413 if (!gln_abbreviations_enabled)
4414 {
4415 gln_normal_string ("Glk abbreviation expansions are already off.\n");
4416 return;
4417 }
4418
4419 gln_abbreviations_enabled = FALSE;
4420 gln_normal_string ("Glk abbreviation expansions are now off.\n");
4421 }
4422
4423 else if (strlen (argument) == 0)
4424 {
4425 gln_normal_string ("Glk abbreviation expansions are ");
4426 gln_normal_string (gln_abbreviations_enabled ? "on" : "off");
4427 gln_normal_string (".\n");
4428 }
4429
4430 else
4431 {
4432 gln_normal_string ("Glk abbreviation expansions can be ");
4433 gln_standout_string ("on");
4434 gln_normal_string (", or ");
4435 gln_standout_string ("off");
4436 gln_normal_string (".\n");
4437 }
4438 }
4439
4440
4441 /*
4442 * gln_command_graphics()
4443 *
4444 * Enable or disable graphics more permanently than is done by the main
4445 * interpreter. Also, print out a few brief details about the graphics
4446 * state of the program.
4447 */
4448 static void
4449 gln_command_graphics (const char *argument)
4450 {
4451 assert (argument);
4452
4453 if (!gln_graphics_possible)
4454 {
4455 gln_normal_string ("Glk graphics are not available.\n");
4456 return;
4457 }
4458
4459 if (gln_strcasecmp (argument, "on") == 0)
4460 {
4461 if (gln_graphics_enabled)
4462 {
4463 gln_normal_string ("Glk graphics are already on.\n");
4464 return;
4465 }
4466
4467 gln_graphics_enabled = TRUE;
4468
4469 /* If a picture is loaded, call the restart function to repaint it. */
4470 if (gln_graphics_picture_is_available ())
4471 {
4472 if (!gln_graphics_open ())
4473 {
4474 gln_normal_string ("Glk graphics error.\n");
4475 return;
4476 }
4477 gln_graphics_restart ();
4478 }
4479
4480 gln_normal_string ("Glk graphics are now on.\n");
4481 }
4482
4483 else if (gln_strcasecmp (argument, "off") == 0)
4484 {
4485 if (!gln_graphics_enabled)
4486 {
4487 gln_normal_string ("Glk graphics are already off.\n");
4488 return;
4489 }
4490
4491 /*
4492 * Set graphics to disabled, and stop any graphics processing. Close
4493 * the graphics window.
4494 */
4495 gln_graphics_enabled = FALSE;
4496 gln_graphics_stop ();
4497 gln_graphics_close ();
4498
4499 gln_normal_string ("Glk graphics are now off.\n");
4500 }
4501
4502 else if (strlen (argument) == 0)
4503 {
4504 gln_normal_string ("Glk graphics are available,");
4505 gln_normal_string (gln_graphics_enabled
4506 ? " and enabled.\n" : " but disabled.\n");
4507
4508 if (gln_graphics_picture_is_available ())
4509 {
4510 int width, height;
4511
4512 if (gln_graphics_get_picture_details (&width, &height))
4513 {
4514 char buffer[16];
4515
4516 gln_normal_string ("There is a picture loaded, ");
4517
4518 sprintf (buffer, "%d", width);
4519 gln_normal_string (buffer);
4520 gln_normal_string (" by ");
4521
4522 sprintf (buffer, "%d", height);
4523 gln_normal_string (buffer);
4524
4525 gln_normal_string (" pixels.\n");
4526 }
4527 }
4528
4529 if (!gln_graphics_interpreter_enabled ())
4530 gln_normal_string ("Interpreter graphics are disabled.\n");
4531
4532 if (gln_graphics_enabled && gln_graphics_are_displayed ())
4533 {
4534 const char *bitmap_type;
4535 int color_count, is_active;
4536
4537 if (gln_graphics_get_rendering_details (&bitmap_type,
4538 &color_count, &is_active))
4539 {
4540 char buffer[16];
4541
4542 gln_normal_string ("Graphics are ");
4543 gln_normal_string (is_active ? "active, " : "displayed, ");
4544
4545 sprintf (buffer, "%d", color_count);
4546 gln_normal_string (buffer);
4547 gln_normal_string (" colours");
4548
4549 if (bitmap_type)
4550 {
4551 gln_normal_string (", ");
4552 gln_normal_string (bitmap_type);
4553 gln_normal_string (" bitmaps");
4554 }
4555 gln_normal_string (".\n");
4556 }
4557 else
4558 gln_normal_string ("Graphics are being displayed.\n");
4559 }
4560
4561 if (gln_graphics_enabled && !gln_graphics_are_displayed ())
4562 gln_normal_string ("Graphics are not being displayed.\n");
4563 }
4564
4565 else
4566 {
4567 gln_normal_string ("Glk graphics can be ");
4568 gln_standout_string ("on");
4569 gln_normal_string (", or ");
4570 gln_standout_string ("off");
4571 gln_normal_string (".\n");
4572 }
4573 }
4574
4575
4576 /*
4577 * gln_command_loopchecks()
4578 *
4579 * Turn loop checking (for game infinite loops) on and off.
4580 */
4581 static void
4582 gln_command_loopchecks (const char *argument)
4583 {
4584 assert (argument);
4585
4586 if (gln_strcasecmp (argument, "on") == 0)
4587 {
4588 if (gln_loopcheck_enabled)
4589 {
4590 gln_normal_string ("Glk loop detection is already on.\n");
4591 return;
4592 }
4593
4594 gln_loopcheck_enabled = TRUE;
4595 gln_normal_string ("Glk loop detection is now on.\n");
4596 }
4597
4598 else if (gln_strcasecmp (argument, "off") == 0)
4599 {
4600 if (!gln_loopcheck_enabled)
4601 {
4602 gln_normal_string ("Glk loop detection is already off.\n");
4603 return;
4604 }
4605
4606 gln_loopcheck_enabled = FALSE;
4607 gln_normal_string ("Glk loop detection is now off.\n");
4608 }
4609
4610 else if (strlen (argument) == 0)
4611 {
4612 gln_normal_string ("Glk loop detection is ");
4613 gln_normal_string (gln_loopcheck_enabled ? "on" : "off");
4614 gln_normal_string (".\n");
4615 }
4616
4617 else
4618 {
4619 gln_normal_string ("Glk loop detection can be ");
4620 gln_standout_string ("on");
4621 gln_normal_string (", or ");
4622 gln_standout_string ("off");
4623 gln_normal_string (".\n");
4624 }
4625 }
4626
4627
4628 /*
4629 * gln_command_locals()
4630 *
4631 * Turn local interpretation of "quit" etc. on and off.
4632 */
4633 static void
4634 gln_command_locals (const char *argument)
4635 {
4636 assert (argument);
4637
4638 if (gln_strcasecmp (argument, "on") == 0)
4639 {
4640 if (gln_intercept_enabled)
4641 {
4642 gln_normal_string ("Glk local commands are already on.\n");
4643 return;
4644 }
4645
4646 gln_intercept_enabled = TRUE;
4647 gln_normal_string ("Glk local commands are now on.\n");
4648 }
4649
4650 else if (gln_strcasecmp (argument, "off") == 0)
4651 {
4652 if (!gln_intercept_enabled)
4653 {
4654 gln_normal_string ("Glk local commands are already off.\n");
4655 return;
4656 }
4657
4658 gln_intercept_enabled = FALSE;
4659 gln_normal_string ("Glk local commands are now off.\n");
4660 }
4661
4662 else if (strlen (argument) == 0)
4663 {
4664 gln_normal_string ("Glk local commands are ");
4665 gln_normal_string (gln_intercept_enabled ? "on" : "off");
4666 gln_normal_string (".\n");
4667 }
4668
4669 else
4670 {
4671 gln_normal_string ("Glk local commands can be ");
4672 gln_standout_string ("on");
4673 gln_normal_string (", or ");
4674 gln_standout_string ("off");
4675 gln_normal_string (".\n");
4676 }
4677 }
4678
4679
4680 /*
4681 * gln_command_prompts()
4682 *
4683 * Turn the extra "> " prompt output on and off.
4684 */
4685 static void
4686 gln_command_prompts (const char *argument)
4687 {
4688 assert (argument);
4689
4690 if (gln_strcasecmp (argument, "on") == 0)
4691 {
4692 if (gln_prompt_enabled)
4693 {
4694 gln_normal_string ("Glk extra prompts are already on.\n");
4695 return;
4696 }
4697
4698 gln_prompt_enabled = TRUE;
4699 gln_normal_string ("Glk extra prompts are now on.\n");
4700
4701 /* Check for a game prompt to clear the flag. */
4702 gln_game_prompted ();
4703 }
4704
4705 else if (gln_strcasecmp (argument, "off") == 0)
4706 {
4707 if (!gln_prompt_enabled)
4708 {
4709 gln_normal_string ("Glk extra prompts are already off.\n");
4710 return;
4711 }
4712
4713 gln_prompt_enabled = FALSE;
4714 gln_normal_string ("Glk extra prompts are now off.\n");
4715 }
4716
4717 else if (strlen (argument) == 0)
4718 {
4719 gln_normal_string ("Glk extra prompts are ");
4720 gln_normal_string (gln_prompt_enabled ? "on" : "off");
4721 gln_normal_string (".\n");
4722 }
4723
4724 else
4725 {
4726 gln_normal_string ("Glk extra prompts can be ");
4727 gln_standout_string ("on");
4728 gln_normal_string (", or ");
4729 gln_standout_string ("off");
4730 gln_normal_string (".\n");
4731 }
4732 }
4733
4734
4735 /*
4736 * gln_command_print_version_number()
4737 * gln_command_version()
4738 *
4739 * Print out the Glk library version number.
4740 */
4741 static void
4742 gln_command_print_version_number (glui32 version)
4743 {
4744 char buffer[64];
4745
4746 sprintf (buffer, "%lu.%lu.%lu",
4747 (unsigned long) version >> 16,
4748 (unsigned long) (version >> 8) & 0xff,
4749 (unsigned long) version & 0xff);
4750 gln_normal_string (buffer);
4751 }
4752
4753 static void
4754 gln_command_version (const char *argument)
4755 {
4756 glui32 version;
4757 assert (argument);
4758
4759 gln_normal_string ("This is version ");
4760 gln_command_print_version_number (GLN_PORT_VERSION);
4761 gln_normal_string (" of the Glk Level 9 port.\n");
4762
4763 version = glk_gestalt (gestalt_Version, 0);
4764 gln_normal_string ("The Glk library version is ");
4765 gln_command_print_version_number (version);
4766 gln_normal_string (".\n");
4767 }
4768
4769
4770 /*
4771 * gln_command_commands()
4772 *
4773 * Turn command escapes off. Once off, there's no way to turn them back on.
4774 * Commands must be on already to enter this function.
4775 */
4776 static void
4777 gln_command_commands (const char *argument)
4778 {
4779 assert (argument);
4780
4781 if (gln_strcasecmp (argument, "on") == 0)
4782 {
4783 gln_normal_string ("Glk commands are already on.\n");
4784 }
4785
4786 else if (gln_strcasecmp (argument, "off") == 0)
4787 {
4788 gln_commands_enabled = FALSE;
4789 gln_normal_string ("Glk commands are now off.\n");
4790 }
4791
4792 else if (strlen (argument) == 0)
4793 {
4794 gln_normal_string ("Glk commands are ");
4795 gln_normal_string (gln_commands_enabled ? "on" : "off");
4796 gln_normal_string (".\n");
4797 }
4798
4799 else
4800 {
4801 gln_normal_string ("Glk commands can be ");
4802 gln_standout_string ("on");
4803 gln_normal_string (", or ");
4804 gln_standout_string ("off");
4805 gln_normal_string (".\n");
4806 }
4807 }
4808
4809
4810 /*
4811 * gln_command_license()
4812 *
4813 * Print licensing terms.
4814 */
4815 static void
4816 gln_command_license (const char *argument)
4817 {
4818 assert (argument);
4819
4820 gln_normal_string ("This program is free software; you can redistribute it"
4821 " and/or modify it under the terms of version 2 of the"
4822 " GNU General Public License as published by the Free"
4823 " Software Foundation.\n\n");
4824
4825 gln_normal_string ("This program is distributed in the hope that it will be"
4826 " useful, but ");
4827 gln_standout_string ("WITHOUT ANY WARRANTY");
4828 gln_normal_string ("; without even the implied warranty of ");
4829 gln_standout_string ("MERCHANTABILITY");
4830 gln_normal_string (" or ");
4831 gln_standout_string ("FITNESS FOR A PARTICULAR PURPOSE");
4832 gln_normal_string (". See the GNU General Public License for more"
4833 " details.\n\n");
4834
4835 gln_normal_string ("You should have received a copy of the GNU General"
4836 " Public License along with this program; if not, write"
4837 " to the Free Software Foundation, Inc., 59 Temple"
4838 " Place, Suite 330, Boston, MA 02111-1307 USA\n\n");
4839
4840 gln_normal_string ("Please report any bugs, omissions, or misfeatures to ");
4841 gln_standout_string ("[email protected]");
4842 gln_normal_string (".\n");
4843 }
4844
4845
4846 /* Glk subcommands and handler functions. */
4847 typedef const struct
4848 {
4849 const char * const command; /* Glk subcommand. */
4850 void (* const handler) (const char *argument); /* Subcommand handler. */
4851 const int takes_argument; /* Argument flag. */
4852 } gln_command_t;
4853 typedef gln_command_t *gln_commandref_t;
4854
4855 static void gln_command_summary (const char *argument);
4856 static void gln_command_help (const char *argument);
4857
4858 static gln_command_t GLN_COMMAND_TABLE[] = {
4859 {"summary", gln_command_summary, FALSE},
4860 {"script", gln_command_script, TRUE},
4861 {"inputlog", gln_command_inputlog, TRUE},
4862 {"readlog", gln_command_readlog, TRUE},
4863 {"abbreviations", gln_command_abbreviations, TRUE},
4864 {"graphics", gln_command_graphics, TRUE},
4865 {"loopchecks", gln_command_loopchecks, TRUE},
4866 {"locals", gln_command_locals, TRUE},
4867 {"prompts", gln_command_prompts, TRUE},
4868 {"version", gln_command_version, FALSE},
4869 {"commands", gln_command_commands, TRUE},
4870 {"license", gln_command_license, FALSE},
4871 {"help", gln_command_help, TRUE},
4872 {NULL, NULL, FALSE}
4873 };
4874
4875
4876 /*
4877 * gln_command_summary()
4878 *
4879 * Report all current Glk settings.
4880 */
4881 static void
4882 gln_command_summary (const char *argument)
4883 {
4884 gln_commandref_t entry;
4885 assert (argument);
4886
4887 /*
4888 * Call handlers that have status to report with an empty argument,
4889 * prompting each to print its current setting.
4890 */
4891 for (entry = GLN_COMMAND_TABLE; entry->command; entry++)
4892 {
4893 if (entry->handler == gln_command_summary
4894 || entry->handler == gln_command_license
4895 || entry->handler == gln_command_help)
4896 continue;
4897
4898 entry->handler ("");
4899 }
4900 }
4901
4902
4903 /*
4904 * gln_command_help()
4905 *
4906 * Document the available Glk commands.
4907 */
4908 static void
4909 gln_command_help (const char *command)
4910 {
4911 gln_commandref_t entry, matched;
4912 assert (command);
4913
4914 if (strlen (command) == 0)
4915 {
4916 gln_normal_string ("Glk commands are");
4917 for (entry = GLN_COMMAND_TABLE; entry->command; entry++)
4918 {
4919 gln_commandref_t next;
4920
4921 next = entry + 1;
4922 gln_normal_string (next->command ? " " : " and ");
4923 gln_standout_string (entry->command);
4924 gln_normal_string (next->command ? "," : ".\n\n");
4925 }
4926
4927 gln_normal_string ("Glk commands may be abbreviated, as long as"
4928 " the abbreviation is unambiguous. Use ");
4929 gln_standout_string ("glk help");
4930 gln_normal_string (" followed by a Glk command name for help on that"
4931 " command.\n");
4932 return;
4933 }
4934
4935 matched = NULL;
4936 for (entry = GLN_COMMAND_TABLE; entry->command; entry++)
4937 {
4938 if (gln_strncasecmp (command, entry->command, strlen (command)) == 0)
4939 {
4940 if (matched)
4941 {
4942 gln_normal_string ("The Glk command ");
4943 gln_standout_string (command);
4944 gln_normal_string (" is ambiguous. Try ");
4945 gln_standout_string ("glk help");
4946 gln_normal_string (" for more information.\n");
4947 return;
4948 }
4949 matched = entry;
4950 }
4951 }
4952 if (!matched)
4953 {
4954 gln_normal_string ("The Glk command ");
4955 gln_standout_string (command);
4956 gln_normal_string (" is not valid. Try ");
4957 gln_standout_string ("glk help");
4958 gln_normal_string (" for more information.\n");
4959 return;
4960 }
4961
4962 if (matched->handler == gln_command_summary)
4963 {
4964 gln_normal_string ("Prints a summary of all the current Glk Level 9"
4965 " settings.\n");
4966 }
4967
4968 else if (matched->handler == gln_command_script)
4969 {
4970 gln_normal_string ("Logs the game's output to a file.\n\nUse ");
4971 gln_standout_string ("glk script on");
4972 gln_normal_string (" to begin logging game output, and ");
4973 gln_standout_string ("glk script off");
4974 gln_normal_string (" to end it. Glk Level 9 will ask you for a file"
4975 " when you turn scripts on.\n");
4976 }
4977
4978 else if (matched->handler == gln_command_inputlog)
4979 {
4980 gln_normal_string ("Records the commands you type into a game.\n\nUse ");
4981 gln_standout_string ("glk inputlog on");
4982 gln_normal_string (", to begin recording your commands, and ");
4983 gln_standout_string ("glk inputlog off");
4984 gln_normal_string (" to turn off input logs. You can play back"
4985 " recorded commands into a game with the ");
4986 gln_standout_string ("glk readlog");
4987 gln_normal_string (" command.\n");
4988 }
4989
4990 else if (matched->handler == gln_command_readlog)
4991 {
4992 gln_normal_string ("Plays back commands recorded with ");
4993 gln_standout_string ("glk inputlog on");
4994 gln_normal_string (".\n\nUse ");
4995 gln_standout_string ("glk readlog on");
4996 gln_normal_string (". Command play back stops at the end of the"
4997 " file. You can also play back commands from a"
4998 " text file created using any standard editor.\n");
4999 }
5000
5001 else if (matched->handler == gln_command_abbreviations)
5002 {
5003 gln_normal_string ("Controls abbreviation expansion.\n\nGlk Level 9"
5004 " automatically expands several standard single"
5005 " letter abbreviations for you; for example, \"x\""
5006 " becomes \"examine\". Use ");
5007 gln_standout_string ("glk abbreviations on");
5008 gln_normal_string (" to turn this feature on, and ");
5009 gln_standout_string ("glk abbreviations off");
5010 gln_normal_string (" to turn it off. While the feature is on, you"
5011 " can bypass abbreviation expansion for an"
5012 " individual game command by prefixing it with a"
5013 " single quote.\n");
5014 }
5015
5016 else if (matched->handler == gln_command_graphics)
5017 {
5018 gln_normal_string ("Turns interpreter graphics on and off.\n\nUse ");
5019 gln_standout_string ("glk graphics on");
5020 gln_normal_string (" to enable interpreter graphics, and ");
5021 gln_standout_string ("glk graphics off");
5022 gln_normal_string (" to turn graphics off and close the graphics window."
5023 " This control works slightly differently to the"
5024 " 'graphics' command in Level 9 games themselves; the"
5025 " game's 'graphics' command may disable new images,"
5026 " but leave old ones displayed. For graphics to be"
5027 " displayed, they must be turned on in both the game"
5028 " and the interpreter.\n");
5029 }
5030
5031 else if (matched->handler == gln_command_loopchecks)
5032 {
5033 gln_normal_string ("Controls game infinite loop monitoring.\n\n"
5034 "Some Level 9 games can enter an infinite loop if they"
5035 " have nothing better to do. A game might do this"
5036 " after it has ended, should you decline its offer"
5037 " to rerun. To avoid the need to kill the interpreter"
5038 " completely if a game does this, Glk Level 9 monitors"
5039 " a game's input and output, and offers the option to"
5040 " end the program gracefully if a game is silent for"
5041 " a few seconds. Use ");
5042 gln_standout_string ("glk loopchecks on");
5043 gln_normal_string (" to turn this feature on, and ");
5044 gln_standout_string ("glk loopchecks off");
5045 gln_normal_string (" to turn it off.\n");
5046 }
5047
5048 else if (matched->handler == gln_command_locals)
5049 {
5050 gln_normal_string ("Controls interception of selected game commands.\n\n"
5051 "Some Level 9 games were written for cassette tape"
5052 " based microprocessor systems, and the way in which"
5053 " they save, restore, and restart games can reflect"
5054 " this. There is also often no straightforward way"
5055 " to quit from a game.\n\nTo make playing a Level 9"
5056 " game appear similar to other systems, Glk Level 9"
5057 " will trap the commands 'quit', 'restart', 'save',"
5058 " 'restore', and 'load' (a synonym for 'restore') and"
5059 " handle them locally within the interpreter. Use ");
5060 gln_standout_string ("glk locals on");
5061 gln_normal_string (" to turn this feature on, and ");
5062 gln_standout_string ("glk locals off");
5063 gln_normal_string (" to turn it off.\n");
5064 }
5065
5066 else if (matched->handler == gln_command_prompts)
5067 {
5068 gln_normal_string ("Controls extra input prompting.\n\n"
5069 "Glk Level 9 can issue a replacement '>' input"
5070 " prompt if it detects that the game hasn't prompted"
5071 " after, say, an empty input line. Use ");
5072 gln_standout_string ("glk prompts on");
5073 gln_normal_string (" to turn this feature on, and ");
5074 gln_standout_string ("glk prompts off");
5075 gln_normal_string (" to turn it off.\n");
5076 }
5077
5078 else if (matched->handler == gln_command_version)
5079 {
5080 gln_normal_string ("Prints the version numbers of the Glk library"
5081 " and the Glk Level 9 port.\n");
5082 }
5083
5084 else if (matched->handler == gln_command_commands)
5085 {
5086 gln_normal_string ("Turn off Glk commands.\n\nUse ");
5087 gln_standout_string ("glk commands off");
5088 gln_normal_string (" to disable all Glk commands, including this one."
5089 " Once turned off, there is no way to turn Glk"
5090 " commands back on while inside the game.\n");
5091 }
5092
5093 else if (matched->handler == gln_command_license)
5094 {
5095 gln_normal_string ("Prints Glk Level 9's software license.\n");
5096 }
5097
5098 else if (matched->handler == gln_command_help)
5099 gln_command_help ("");
5100
5101 else
5102 gln_normal_string ("There is no help available on that Glk command."
5103 " Sorry.\n");
5104 }
5105
5106
5107 /*
5108 * gln_command_escape()
5109 *
5110 * This function is handed each input line. If the line contains a specific
5111 * Glk port command, handle it and return TRUE, otherwise return FALSE.
5112 */
5113 static int
5114 gln_command_escape (const char *string)
5115 {
5116 int posn;
5117 char *string_copy, *command, *argument;
5118 assert (string);
5119
5120 /*
5121 * Return FALSE if the string doesn't begin with the Glk command escape
5122 * introducer.
5123 */
5124 posn = strspn (string, "\t ");
5125 if (gln_strncasecmp (string + posn, "glk", strlen ("glk")) != 0)
5126 return FALSE;
5127
5128 /* Take a copy of the string, without any leading space or introducer. */
5129 string_copy = gln_malloc (strlen (string + posn) + 1 - strlen ("glk"));
5130 strcpy (string_copy, string + posn + strlen ("glk"));
5131
5132 /*
5133 * Find the subcommand; the first word in the string copy. Find its end,
5134 * and ensure it terminates with a NUL.
5135 */
5136 posn = strspn (string_copy, "\t ");
5137 command = string_copy + posn;
5138 posn += strcspn (string_copy + posn, "\t ");
5139 if (string_copy[posn] != '\0')
5140 string_copy[posn++] = '\0';
5141
5142 /*
5143 * Now find any argument data for the command, ensuring it too terminates
5144 * with a NUL.
5145 */
5146 posn += strspn (string_copy + posn, "\t ");
5147 argument = string_copy + posn;
5148 posn += strcspn (string_copy + posn, "\t ");
5149 string_copy[posn] = '\0';
5150
5151 /*
5152 * Try to handle the command and argument as a Glk subcommand. If it
5153 * doesn't run unambiguously, print command usage. Treat an empty command
5154 * as "help".
5155 */
5156 if (strlen (command) > 0)
5157 {
5158 gln_commandref_t entry, matched;
5159 int matches;
5160
5161 /*
5162 * Search for the first unambiguous table command string matching
5163 * the command passed in.
5164 */
5165 matches = 0;
5166 matched = NULL;
5167 for (entry = GLN_COMMAND_TABLE; entry->command; entry++)
5168 {
5169 if (gln_strncasecmp (command, entry->command, strlen (command)) == 0)
5170 {
5171 matches++;
5172 matched = entry;
5173 }
5174 }
5175
5176 /* If the match was unambiguous, call the command handler. */
5177 if (matches == 1)
5178 {
5179 gln_normal_char ('\n');
5180 matched->handler (argument);
5181
5182 if (!matched->takes_argument && strlen (argument) > 0)
5183 {
5184 gln_normal_string ("[The ");
5185 gln_standout_string (matched->command);
5186 gln_normal_string (" command ignores arguments.]\n");
5187 }
5188 }
5189
5190 /* No match, or the command was ambiguous. */
5191 else
5192 {
5193 gln_normal_string ("\nThe Glk command ");
5194 gln_standout_string (command);
5195 gln_normal_string (" is ");
5196 gln_normal_string (matches == 0 ? "not valid" : "ambiguous");
5197 gln_normal_string (". Try ");
5198 gln_standout_string ("glk help");
5199 gln_normal_string (" for more information.\n");
5200 }
5201 }
5202 else
5203 {
5204 gln_normal_char ('\n');
5205 gln_command_help ("");
5206 }
5207
5208 /* The string contained a Glk command; return TRUE. */
5209 free (string_copy);
5210 return TRUE;
5211 }
5212
5213
5214 /*
5215 * gln_command_intercept()
5216 *
5217 * The Level 9 games handle the commands "quit" and "restart" oddly, and
5218 * somewhat similarly. Both prompt "Press SPACE to play again", and then
5219 * ignore all characters except space. This makes it especially hard to exit
5220 * from a game without killing the interpreter process. They also handle
5221 * "restore" via an odd security mechanism which has no real place here (the
5222 * base Level 9 interpreter sidesteps this with its "#restore" command, and
5223 * has some bugs in "save").
5224 *
5225 * To try to improve these, here we'll catch and special case the input lines
5226 * "quit", "save", "restore", and "restart". "Load" is a synonym for
5227 * "restore".
5228 *
5229 * On "quit" or "restart", the function sets the interpreter stop reason
5230 * code, stops the current game run. On "save" or "restore" it calls the
5231 * appropriate internal interpreter function.
5232 *
5233 * The return value is TRUE if an intercepted command was found, otherwise
5234 * FALSE.
5235 */
5236 static int
5237 gln_command_intercept (char *string)
5238 {
5239 int posn, result;
5240 char *string_copy, *trailing;
5241 assert (string);
5242
5243 result = FALSE;
5244
5245 /* Take a copy of the string, excluding any leading whitespace. */
5246 posn = strspn (string, "\t ");
5247 string_copy = gln_malloc (strlen (string + posn) + 1);
5248 strcpy (string_copy, string + posn);
5249
5250 /*
5251 * Find the space or NUL after the first word, and check that anything
5252 * after it the first word is whitespace only.
5253 */
5254 posn = strcspn (string_copy, "\t ");
5255 trailing = string_copy + posn;
5256 if (trailing[strspn (trailing, "\t ")] == '\0')
5257 {
5258 /* Terminate the string copy for easy comparisons. */
5259 string_copy[posn] = '\0';
5260
5261 /* If this command was "quit", confirm, then call StopGame(). */
5262 if (gln_strcasecmp (string_copy, "quit") == 0)
5263 {
5264 if (gln_confirm ("\nDo you really want to stop? [Y or N] "))
5265 {
5266 gln_stop_reason = STOP_EXIT;
5267 StopGame ();
5268 }
5269 result = TRUE;
5270 }
5271
5272 /* If this command was "restart", confirm, then call StopGame(). */
5273 else if (gln_strcasecmp (string_copy, "restart") == 0)
5274 {
5275 if (gln_confirm ("\nDo you really want to restart? [Y or N] "))
5276 {
5277 gln_stop_reason = STOP_RESTART;
5278 StopGame ();
5279 }
5280 result = TRUE;
5281 }
5282
5283 /* If this command was "save", simply call save(). */
5284 else if (gln_strcasecmp (string_copy, "save") == 0)
5285 {
5286 gln_standout_string ("\nSaving using interpreter\n\n");
5287 save ();
5288 result = TRUE;
5289 }
5290
5291 /* If this command was "restore" or "load", call restore(). */
5292 else if (gln_strcasecmp (string_copy, "restore") == 0
5293 || gln_strcasecmp (string_copy, "load") == 0)
5294 {
5295 gln_standout_string ("\nRestoring using interpreter\n\n");
5296 restore ();
5297 result = TRUE;
5298 }
5299 }
5300
5301 free (string_copy);
5302 return result;
5303 }
5304
5305
5306 /*---------------------------------------------------------------------*/
5307 /* Glk port input functions */
5308 /*---------------------------------------------------------------------*/
5309
5310 /* Ctrl-C and Ctrl-U character constants. */
5311 static const char GLN_CONTROL_C = '\003',
5312 GLN_CONTROL_U = '\025';
5313
5314 /*
5315 * os_readchar() call count limit, after which we really read a character.
5316 * Also, call count limit on os_stoplist calls, after which we poll for a
5317 * character press to stop the listing, and a stoplist poll timeout.
5318 */
5319 static const int GLN_READCHAR_LIMIT = 1024,
5320 GLN_STOPLIST_LIMIT = 10;
5321 static const glui32 GLN_STOPLIST_TIMEOUT = 50;
5322
5323 /* Quote used to suppress abbreviation expansion and local commands. */
5324 static const char GLN_QUOTED_INPUT = '\'';
5325
5326
5327 /*
5328 * Note of when the interpreter is in list output. The last element of any
5329 * list generally lacks a terminating newline, and unless we do something
5330 * special with it, it'll look like a valid prompt to us.
5331 */
5332 static int gln_inside_list = FALSE;
5333
5334
5335 /* Table of single-character command abbreviations. */
5336 typedef const struct
5337 {
5338 const char abbreviation; /* Abbreviation character. */
5339 const char * const expansion; /* Expansion string. */
5340 } gln_abbreviation_t;
5341 typedef gln_abbreviation_t *gln_abbreviationref_t;
5342
5343 static gln_abbreviation_t GLN_ABBREVIATIONS[] = {
5344 {'c', "close"}, {'g', "again"}, {'i', "inventory"},
5345 {'k', "attack"}, {'l', "look"}, {'p', "open"},
5346 {'q', "quit"}, {'r', "drop"}, {'t', "take"},
5347 {'x', "examine"}, {'y', "yes"}, {'z', "wait"},
5348 {'\0', NULL}
5349 };
5350
5351
5352 /*
5353 * gln_expand_abbreviations()
5354 *
5355 * Expand a few common one-character abbreviations commonly found in other
5356 * game systems, but not always normal in Level 9 games.
5357 */
5358 static void
5359 gln_expand_abbreviations (char *buffer, int size)
5360 {
5361 char *command, abbreviation;
5362 const char *expansion;
5363 gln_abbreviationref_t entry;
5364 assert (buffer);
5365
5366 /* Ignore anything that isn't a single letter command. */
5367 command = buffer + strspn (buffer, "\t ");
5368 if (!(strlen (command) == 1
5369 || (strlen (command) > 1 && isspace (command[1]))))
5370 return;
5371
5372 /* Scan the abbreviations table for a match. */
5373 abbreviation = glk_char_to_lower ((unsigned char) command[0]);
5374 expansion = NULL;
5375 for (entry = GLN_ABBREVIATIONS; entry->expansion; entry++)
5376 {
5377 if (entry->abbreviation == abbreviation)
5378 {
5379 expansion = entry->expansion;
5380 break;
5381 }
5382 }
5383
5384 /*
5385 * If a match found, check for a fit, then replace the character with the
5386 * expansion string.
5387 */
5388 if (expansion)
5389 {
5390 if (strlen (buffer) + strlen (expansion) - 1 >= size)
5391 return;
5392
5393 memmove (command + strlen (expansion) - 1, command, strlen (command) + 1);
5394 memcpy (command, expansion, strlen (expansion));
5395
5396 #ifndef GARGLK
5397 gln_standout_string ("[");
5398 gln_standout_char (abbreviation);
5399 gln_standout_string (" -> ");
5400 gln_standout_string (expansion);
5401 gln_standout_string ("]\n");
5402 #endif
5403 }
5404 }
5405
5406
5407 /*
5408 * gln_output_endlist()
5409 *
5410 * The core interpreter doesn't terminate lists with a newline, so we take
5411 * care of that here; a fixup for input functions.
5412 */
5413 static void
5414 gln_output_endlist (void)
5415 {
5416 if (gln_inside_list)
5417 {
5418 /*
5419 * Supply the missing newline, using os_printchar() so that list output
5420 * doesn't look like a prompt when we come to flush it.
5421 */
5422 os_printchar ('\n');
5423
5424 gln_inside_list = FALSE;
5425 }
5426 }
5427
5428
5429 /*
5430 * os_input()
5431 *
5432 * Read a line from the keyboard. This function makes a special case of
5433 * some command strings, and will also perform abbreviation expansion.
5434 */
5435 gln_bool
5436 os_input (char *buffer, int size)
5437 {
5438 event_t event;
5439 assert (buffer);
5440
5441 /* If doing linemode graphics, run all graphic opcodes available. */
5442 gln_linegraphics_process ();
5443
5444 /*
5445 * Update the current status line display, flush any pending buffered
5446 * output, and terminate any open list.
5447 */
5448 gln_status_notify ();
5449 gln_output_endlist ();
5450 gln_output_flush ();
5451
5452 /*
5453 * Level 9 games tend not to issue a prompt after reading an empty
5454 * line of input, and the Adrian Mole games don't issue a prompt at
5455 * all when outside the 1/2/3 menuing system. This can make for a
5456 * very blank looking screen.
5457 *
5458 * To slightly improve things, if it looks like we didn't get a
5459 * prompt from the game, do our own.
5460 */
5461 if (gln_prompt_enabled && !gln_game_prompted ())
5462 {
5463 gln_normal_char ('\n');
5464 gln_normal_string (GLN_INPUT_PROMPT);
5465 }
5466
5467 /*
5468 * If we have an input log to read from, use that until it is exhausted. On
5469 * end of file, close the stream and resume input from line requests.
5470 */
5471 if (gln_readlog_stream)
5472 {
5473 glui32 chars;
5474
5475 /* Get the next line from the log stream. */
5476 chars = glk_get_line_stream (gln_readlog_stream, buffer, size);
5477 if (chars > 0)
5478 {
5479 /* Echo the line just read in input style. */
5480 glk_set_style (style_Input);
5481 glk_put_buffer (buffer, chars);
5482 glk_set_style (style_Normal);
5483
5484 /* Tick the watchdog, and return. */
5485 gln_watchdog_tick ();
5486 return TRUE;
5487 }
5488
5489 /*
5490 * We're at the end of the log stream. Close it, and then continue
5491 * on to request a line from Glk.
5492 */
5493 glk_stream_close (gln_readlog_stream, NULL);
5494 gln_readlog_stream = NULL;
5495 }
5496
5497 /*
5498 * No input log being read, or we just hit the end of file on one. Revert
5499 * to normal line input; start by getting a new line from Glk.
5500 */
5501 glk_request_line_event (gln_main_window, buffer, size - 1, 0);
5502 gln_event_wait (evtype_LineInput, &event);
5503
5504 /* Terminate the input line with a NUL. */
5505 assert (event.val1 <= size - 1);
5506 buffer[event.val1] = '\0';
5507
5508 /*
5509 * If neither abbreviations nor local commands are enabled, nor game
5510 * command interceptions, use the data read above without further massaging.
5511 */
5512 if (gln_abbreviations_enabled
5513 || gln_commands_enabled || gln_intercept_enabled)
5514 {
5515 char *command;
5516
5517 /*
5518 * If the first non-space input character is a quote, bypass all
5519 * abbreviation expansion and local command recognition, and use the
5520 * unadulterated input, less introductory quote.
5521 */
5522 command = buffer + strspn (buffer, "\t ");
5523 if (command[0] == GLN_QUOTED_INPUT)
5524 {
5525 /* Delete the quote with memmove(). */
5526 memmove (command, command + 1, strlen (command));
5527 }
5528 else
5529 {
5530 /* Check for, and expand, and abbreviated commands. */
5531 if (gln_abbreviations_enabled)
5532 gln_expand_abbreviations (buffer, size);
5533
5534 /*
5535 * Check for standalone "help", then for Glk port special commands;
5536 * suppress the interpreter's use of this input for Glk commands by
5537 * returning FALSE.
5538 */
5539 if (gln_commands_enabled)
5540 {
5541 int posn;
5542
5543 posn = strspn (buffer, "\t ");
5544 if (gln_strncasecmp (buffer + posn, "help", strlen ("help"))== 0)
5545 {
5546 if (strspn (buffer + posn + strlen ("help"), "\t ")
5547 == strlen (buffer + posn + strlen ("help")))
5548 {
5549 gln_output_register_help_request ();
5550 }
5551 }
5552
5553 if (gln_command_escape (buffer))
5554 {
5555 gln_output_silence_help_hints ();
5556 gln_watchdog_tick ();
5557 return FALSE;
5558 }
5559 }
5560
5561 /*
5562 * Check for locally intercepted commands, again returning FALSE if
5563 * one is handled.
5564 */
5565 if (gln_intercept_enabled)
5566 {
5567 if (gln_command_intercept (buffer))
5568 {
5569 gln_watchdog_tick ();
5570 return FALSE;
5571 }
5572 }
5573 }
5574 }
5575
5576 /*
5577 * If there is an input log active, log this input string to it. Note that
5578 * by logging here we get any abbreviation expansions but we won't log glk
5579 * special commands, nor any input read from a current open input log.
5580 */
5581 if (gln_inputlog_stream)
5582 {
5583 glk_put_string_stream (gln_inputlog_stream, buffer);
5584 glk_put_char_stream (gln_inputlog_stream, '\n');
5585 }
5586
5587 gln_watchdog_tick ();
5588 return TRUE;
5589 }
5590
5591
5592 /*
5593 * os_readchar()
5594 *
5595 * Poll the keyboard for characters, and return the character code of any key
5596 * pressed, or 0 if none pressed.
5597 *
5598 * Simple though this sounds, it's tough to do right in a timesharing OS, and
5599 * requires something close to an abuse of Glk.
5600 *
5601 * The initial, tempting, implementation is to wait inside this function for
5602 * a key press, then return the code. Unfortunately, this causes problems in
5603 * the Level 9 interpreter. Here's why: the interpreter is a VM emulating a
5604 * single-user microprocessor system. On such a system, it's quite okay for
5605 * code to spin in a loop waiting for a keypress; there's nothing else
5606 * happening on the system, so it can burn CPU. To wait for a keypress, game
5607 * code might first wait for no-keypress (0 from this function), then a
5608 * keypress (non-0), then no-keypress again (and it does indeed seem to do
5609 * just this). If, in os_readchar(), we simply wait for and return key codes,
5610 * we'll never return a 0, so the above wait for a keypress in the game will
5611 * hang forever.
5612 *
5613 * To make matters more complex, some Level 9 games poll for keypresses as a
5614 * way for a user to halt scrolling. For these polls, we really want to
5615 * return 0, otherwise the output grinds to a halt. Moreover, some games even
5616 * use key polling as a crude form of timeout - poll and increment a counter,
5617 * and exit when either os_readchar() returns non-0, or after some 300 or so
5618 * polls.
5619 *
5620 * So, this function MUST return 0 sometimes, and real key codes other times.
5621 * The solution adopted is best described as expedient. Depending on what Glk
5622 * provides in the way of timers, we'll do one of two things:
5623 *
5624 * o If we have timers, we'll set up a timeout, and poll for a key press
5625 * within that timeout. As a way to smooth output for games that use key
5626 * press polling for scroll control, we'll ignore calls until we get two
5627 * in a row without intervening character output.
5628 *
5629 * o If we don't have timers, then we'll return 0 most of the time, and then
5630 * really wait for a key one time out of some number. A game polling for
5631 * keypresses to halt scrolling will probably be to the point where it
5632 * cannot continue without user input at this juncture, and once we've
5633 * rejected a few hundred calls we can now really wait for Glk key press
5634 * event, and avoid a spinning loop. A game using key polling as crude
5635 * timing may, or may not, time out in the calls for which we return 0.
5636 *
5637 * Empirically, this all seems to work. The only odd behaviour is with the
5638 * DEMO mode of Adrian Mole where Glk has no timers, and this is primarily
5639 * because the DEMO mode relies on the delay of keyboard polling for part of
5640 * its effect; on a modern system, the time to call through here is nowhere
5641 * near the time consumed by the original platform. The other point of note
5642 * is that this all means that we can't return characters from any readlog
5643 * with this function; its timing stuff and its general polling nature make
5644 * it impossible to connect to readlog, so it just won't work at all with the
5645 * Adrian Mole games, Glk timers or otherwise.
5646 */
5647 char
5648 os_readchar (int millis)
5649 {
5650 static int call_count = 0;
5651
5652 event_t event;
5653 char character;
5654
5655 /* If doing linemode graphics, run all graphic opcodes available. */
5656 gln_linegraphics_process ();
5657
5658 /*
5659 * Here's the way we try to emulate keyboard polling for the case of no Glk
5660 * timers. We'll say nothing is pressed for some number of consecutive
5661 * calls, then continue after that number of calls.
5662 */
5663 if (!glk_gestalt (gestalt_Timer, 0))
5664 {
5665 if (++call_count < GLN_READCHAR_LIMIT)
5666 {
5667 /* Call tick as we may be outside an opcode loop. */
5668 glk_tick ();
5669 gln_watchdog_tick ();
5670 return 0;
5671 }
5672 else
5673 call_count = 0;
5674 }
5675
5676 /*
5677 * If we have Glk timers, we can smooth game output with games that contin-
5678 * uously use this input function by pretending that there is no keypress
5679 * if the game printed output since the last call. This helps with the
5680 * Adrian Mole games, which check for a keypress at the end of a line as a
5681 * way to temporarily halt scrolling.
5682 */
5683 if (glk_gestalt (gestalt_Timer, 0))
5684 {
5685 if (gln_recent_output ())
5686 {
5687 /* Call tick as we may be outside an opcode loop. */
5688 glk_tick ();
5689 gln_watchdog_tick ();
5690 return 0;
5691 }
5692 }
5693
5694 /*
5695 * Now flush any pending buffered output. We do it here rather than earlier
5696 * as it only needs to be done when we're going to request Glk input, and
5697 * we may have avoided this with the checks above.
5698 */
5699 gln_status_notify ();
5700 gln_output_endlist ();
5701 gln_output_flush ();
5702
5703 /*
5704 * Set up a character event request, and a timeout if the Glk library can
5705 * do them, and wait until one or the other occurs. Loop until we read an
5706 * acceptable ASCII character (if we don't time out).
5707 */
5708 do
5709 {
5710 glk_request_char_event (gln_main_window);
5711 if (glk_gestalt (gestalt_Timer, 0))
5712 {
5713 gln_arbitrate_request_timer_events (millis);
5714 gln_event_wait_2 (evtype_CharInput, evtype_Timer, &event);
5715 gln_arbitrate_request_timer_events (0);
5716
5717 /*
5718 * If the event was a timeout, cancel the unfilled character
5719 * request, and return no-keypress value.
5720 */
5721 if (event.type == evtype_Timer)
5722 {
5723 glk_cancel_char_event (gln_main_window);
5724 gln_watchdog_tick ();
5725 return 0;
5726 }
5727 }
5728 else
5729 gln_event_wait (evtype_CharInput, &event);
5730 }
5731 while (event.val1 > UCHAR_MAX && event.val1 != keycode_Return);
5732
5733 /* Extract the character from the event, converting Return, no echo. */
5734 character = event.val1 == keycode_Return ? '\n' : event.val1;
5735
5736 /*
5737 * Special case ^U as a way to press a key on a wait, yet return a code to
5738 * the interpreter as if no key was pressed. Useful if scrolling stops
5739 * where there are no Glk timers, to get scrolling started again. ^U is
5740 * always active.
5741 */
5742 if (character == GLN_CONTROL_U)
5743 {
5744 gln_watchdog_tick ();
5745 return 0;
5746 }
5747
5748 /*
5749 * Special case ^C to quit the program. Without this, there's no easy way
5750 * to exit from a game that never uses os_input(), but instead continually
5751 * uses just os_readchar(). ^C handling can be disabled with command line
5752 * options.
5753 */
5754 if (gln_intercept_enabled && character == GLN_CONTROL_C)
5755 {
5756 if (gln_confirm ("\n\nDo you really want to stop? [Y or N] "))
5757 {
5758 gln_stop_reason = STOP_EXIT;
5759 StopGame ();
5760
5761 gln_watchdog_tick ();
5762 return 0;
5763 }
5764 }
5765
5766 /*
5767 * If there is a transcript stream, send the input to it as a single line
5768 * string, otherwise it won't be visible in the transcript.
5769 */
5770 if (gln_transcript_stream)
5771 {
5772 glk_put_char_stream (gln_transcript_stream, character);
5773 glk_put_char_stream (gln_transcript_stream, '\n');
5774 }
5775
5776 /* Finally, return the single character read. */
5777 gln_watchdog_tick ();
5778 return character;
5779 }
5780
5781
5782 /*
5783 * os_stoplist()
5784 *
5785 * This is called from #dictionary listings to poll for a request to stop
5786 * the listing. A check for keypress is usual at this point. However, Glk
5787 * cannot check for keypresses without a delay, which slows listing consid-
5788 * erably, since it also adjusts and renders the display. As a compromise,
5789 * then, we'll check for keypresses on a small percentage of calls, say one
5790 * in ten, which means that listings happen with only a short delay, but
5791 * there's still an opportunity to stop them.
5792 *
5793 * This applies only where the Glk library has timers. Where it doesn't, we
5794 * can't check for keypresses without blocking, so we do no checks at all,
5795 * and let lists always run to completion.
5796 */
5797 gln_bool
5798 os_stoplist (void)
5799 {
5800 static int call_count = 0;
5801
5802 event_t event;
5803 int is_stop_confirmed;
5804
5805 /* Note that the interpreter is producing a list. */
5806 gln_inside_list = TRUE;
5807
5808 /*
5809 * If there are no Glk timers, then polling for a keypress but continuing
5810 * on if there isn't one is not an option. So flush output, return FALSE,
5811 * and just keep listing on to the end.
5812 */
5813 if (!glk_gestalt (gestalt_Timer, 0))
5814 {
5815 gln_output_flush ();
5816 gln_watchdog_tick ();
5817 return FALSE;
5818 }
5819
5820 /* Increment the call count, and return FALSE if under the limit. */
5821 if (++call_count < GLN_STOPLIST_LIMIT)
5822 {
5823 /* Call tick as we may be outside an opcode loop. */
5824 glk_tick ();
5825 gln_watchdog_tick ();
5826 return FALSE;
5827 }
5828 else
5829 call_count = 0;
5830
5831 /* Flush any pending buffered output, delayed to here in case avoidable. */
5832 gln_output_flush ();
5833
5834 /*
5835 * Look for a keypress, with a very short timeout in place, in a similar
5836 * way as done for os_readchar() above.
5837 */
5838 glk_request_char_event (gln_main_window);
5839 gln_arbitrate_request_timer_events (GLN_STOPLIST_TIMEOUT);
5840 gln_event_wait_2 (evtype_CharInput, evtype_Timer, &event);
5841 gln_arbitrate_request_timer_events (0);
5842
5843 /*
5844 * If the event was a timeout, cancel the unfilled character request, and
5845 * return FALSE to continue listing.
5846 */
5847 if (event.type == evtype_Timer)
5848 {
5849 glk_cancel_char_event (gln_main_window);
5850 gln_watchdog_tick ();
5851 return FALSE;
5852 }
5853
5854 /* Keypress detected, so offer to stop listing. */
5855 assert (event.type == evtype_CharInput);
5856 is_stop_confirmed = gln_confirm ("\n\nStop listing? [Y or N] ");
5857
5858 /*
5859 * As we've output a newline, we no longer consider that we're inside a
5860 * list. Clear the flag, and also clear prompt detection by polling it.
5861 */
5862 gln_inside_list = FALSE;
5863 gln_game_prompted ();
5864
5865 /* Return TRUE if stop was confirmed, FALSE to keep listing. */
5866 gln_watchdog_tick ();
5867 return is_stop_confirmed;
5868 }
5869
5870
5871 /*
5872 * gln_confirm()
5873 *
5874 * Print a confirmation prompt, and read a single input character, taking
5875 * only [YyNn] input. If the character is 'Y' or 'y', return TRUE.
5876 */
5877 static int
5878 gln_confirm (const char *prompt)
5879 {
5880 event_t event;
5881 unsigned char response;
5882 assert (prompt);
5883
5884 /*
5885 * Print the confirmation prompt, in a style that hints that it's from the
5886 * interpreter, not the game.
5887 */
5888 gln_standout_string (prompt);
5889
5890 /* Wait for a single 'Y' or 'N' character response. */
5891 response = ' ';
5892 do
5893 {
5894 glk_request_char_event (gln_main_window);
5895 gln_event_wait (evtype_CharInput, &event);
5896
5897 if (event.val1 <= UCHAR_MAX)
5898 response = glk_char_to_upper (event.val1);
5899 }
5900 while (!(response == 'Y' || response == 'N'));
5901
5902 /* Echo the confirmation response, and a blank line. */
5903 glk_set_style (style_Input);
5904 glk_put_string (response == 'Y' ? "Yes" : "No");
5905 glk_set_style (style_Normal);
5906 glk_put_string ("\n\n");
5907
5908 return response == 'Y';
5909 }
5910
5911
5912 /*---------------------------------------------------------------------*/
5913 /* Glk port event functions */
5914 /*---------------------------------------------------------------------*/
5915
5916 /*
5917 * gln_event_wait_2()
5918 * gln_event_wait()
5919 *
5920 * Process Glk events until one of the expected type, or types, arrives.
5921 * Return the event of that type.
5922 */
5923 static void
5924 gln_event_wait_2 (glui32 wait_type_1, glui32 wait_type_2, event_t * event)
5925 {
5926 assert (event);
5927
5928 do
5929 {
5930 glk_select (event);
5931
5932 switch (event->type)
5933 {
5934 case evtype_Arrange:
5935 case evtype_Redraw:
5936 /* Refresh any sensitive windows on size events. */
5937 gln_status_redraw ();
5938 gln_graphics_paint ();
5939 break;
5940
5941 case evtype_Timer:
5942 /* Do background graphics updates on timeout. */
5943 gln_graphics_timeout ();
5944 break;
5945 }
5946 }
5947 while (event->type != wait_type_1 && event->type != wait_type_2);
5948 }
5949
5950 static void
5951 gln_event_wait (glui32 wait_type, event_t * event)
5952 {
5953 assert (event);
5954 gln_event_wait_2 (wait_type, evtype_None, event);
5955 }
5956
5957
5958 /*---------------------------------------------------------------------*/
5959 /* Glk port file functions */
5960 /*---------------------------------------------------------------------*/
5961
5962 /*
5963 * os_save_file ()
5964 * os_load_file ()
5965 *
5966 * Save the current game state to a file, and load a game state.
5967 */
5968 gln_bool
5969 os_save_file (gln_byte * ptr, int bytes)
5970 {
5971 frefid_t fileref;
5972 strid_t stream;
5973 assert (ptr);
5974
5975 /* Flush any pending buffered output. */
5976 gln_output_flush ();
5977
5978 fileref = glk_fileref_create_by_prompt (fileusage_SavedGame,
5979 filemode_Write, 0);
5980 if (!fileref)
5981 {
5982 gln_watchdog_tick ();
5983 return FALSE;
5984 }
5985
5986 stream = glk_stream_open_file (fileref, filemode_Write, 0);
5987 if (!stream)
5988 {
5989 glk_fileref_destroy (fileref);
5990 gln_watchdog_tick ();
5991 return FALSE;
5992 }
5993
5994 /* Write game state. */
5995 glk_put_buffer_stream (stream, (char *)ptr, bytes);
5996
5997 glk_stream_close (stream, NULL);
5998 glk_fileref_destroy (fileref);
5999
6000 gln_watchdog_tick ();
6001 return TRUE;
6002 }
6003
6004 gln_bool
6005 os_load_file (gln_byte * ptr, int *bytes, int max)
6006 {
6007 frefid_t fileref;
6008 strid_t stream;
6009 assert (ptr && bytes);
6010
6011 /* Flush any pending buffered output. */
6012 gln_output_flush ();
6013
6014 fileref = glk_fileref_create_by_prompt (fileusage_SavedGame,
6015 filemode_Read, 0);
6016 if (!fileref)
6017 {
6018 gln_watchdog_tick ();
6019 return FALSE;
6020 }
6021
6022 /*
6023 * Reject the file reference if we're expecting to read from it, and the
6024 * referenced file doesn't exist.
6025 */
6026 if (!glk_fileref_does_file_exist (fileref))
6027 {
6028 glk_fileref_destroy (fileref);
6029 gln_watchdog_tick ();
6030 return FALSE;
6031 }
6032
6033 stream = glk_stream_open_file (fileref, filemode_Read, 0);
6034 if (!stream)
6035 {
6036 glk_fileref_destroy (fileref);
6037 gln_watchdog_tick ();
6038 return FALSE;
6039 }
6040
6041 /* Restore saved game data. */
6042 *bytes = glk_get_buffer_stream (stream, (char *)ptr, max);
6043
6044 glk_stream_close (stream, NULL);
6045 glk_fileref_destroy (fileref);
6046
6047 gln_watchdog_tick ();
6048 return TRUE;
6049 }
6050
6051
6052 /*---------------------------------------------------------------------*/
6053 /* Glk port multi-file game functions */
6054 /*---------------------------------------------------------------------*/
6055
6056 /*
6057 * os_get_game_file ()
6058 *
6059 * This function is a bit of a cheat. It's called when the emulator has
6060 * detected a request from the game to restart the tape, on a tape-based
6061 * game. Ordinarily, we should prompt the player for the name of the
6062 * system file containing the next game part. Unfortunately, Glk doesn't
6063 * make this at all easy. The requirement is to return a filename, but Glk
6064 * hides these inside fileref_t's, and won't let them out.
6065 *
6066 * Theoretically, according to the porting guide, this function should
6067 * prompt the user for a new game file name, that being the next part of the
6068 * game just (presumably) completed.
6069 *
6070 * However, the newname passed in is always the current game file name, as
6071 * level9.c ensures this for us. If we search for, and find, and then inc-
6072 * rement, the last digit in the filename passed in, we wind up with, in
6073 * all likelihood, the right file path. This is icky.
6074 *
6075 * This function is likely to be a source of portability problems on
6076 * platforms that don't implement a file path/name mechanism that matches
6077 * the expectations of the Level 9 base interpreter fairly closely.
6078 */
6079 gln_bool
6080 os_get_game_file (char *newname, int size)
6081 {
6082 char *basename;
6083 int index, digit, file_number;
6084 FILE *stream;
6085 assert (newname);
6086
6087 /* Find the last element of the filename passed in. */
6088 basename = strrchr (newname, GLN_FILE_DELIM);
6089 basename = basename ? basename + 1 : newname;
6090
6091 /* Search for the last numeric character in the basename. */
6092 digit = -1;
6093 for (index = strlen (basename) - 1; index >= 0; index--)
6094 {
6095 if (isdigit (basename[index]))
6096 {
6097 digit = index;
6098 break;
6099 }
6100 }
6101 if (digit == -1)
6102 {
6103 gln_watchdog_tick ();
6104 return FALSE;
6105 }
6106
6107 /*
6108 * Convert the digit to a file number and increment it. Fail if the new
6109 * file number is outside 1..9.
6110 */
6111 file_number = basename[digit] - '0' + 1;
6112 if (file_number < 1 || file_number > 9)
6113 {
6114 gln_watchdog_tick ();
6115 return FALSE;
6116 }
6117
6118 /* Write the new number back into the file. */
6119 basename[digit] = file_number + '0';
6120
6121 /* Flush pending output, then display the filename generated. */
6122 gln_output_flush ();
6123 gln_game_prompted ();
6124 gln_standout_string ("\nNext load file: ");
6125 gln_standout_string (basename);
6126 gln_standout_string ("\n\n");
6127
6128 /*
6129 * Try to confirm access to the file. Otherwise, if we return TRUE but the
6130 * interpreter can't open the file, it stops the game, and we then lose any
6131 * chance to save it before quitting.
6132 */
6133 stream = fopen (newname, "rb");
6134 if (!stream)
6135 {
6136 /* Restore newname to how it was, and return fail. */
6137 basename[digit] = file_number - 1 + '0';
6138 gln_watchdog_tick ();
6139 return FALSE;
6140 }
6141 fclose (stream);
6142
6143 /* Encourage game name re-lookup, and return success. */
6144 gln_gameid_game_name_reset ();
6145 gln_watchdog_tick ();
6146 return TRUE;
6147 }
6148
6149
6150 /*
6151 * os_set_filenumber()
6152 *
6153 * This function returns the next file in a game series for a disk-based
6154 * game (typically, gamedat1.dat, gamedat2.dat...). It finds a single digit
6155 * in a filename, and resets it to the new value passed in. The implemen-
6156 * tation here is based on the generic interface version, and with the same
6157 * limitations, specifically being limited to file numbers in the range 0
6158 * to 9, since it works on only the last digit character in the filename
6159 * buffer passed in.
6160 *
6161 * This function may also be a source of portability problems on platforms
6162 * that don't use "traditional" file path schemes.
6163 */
6164 void
6165 os_set_filenumber (char *newname, int size, int file_number)
6166 {
6167 char *basename;
6168 int index, digit;
6169 assert (newname);
6170
6171 /* Do nothing if the file number is beyond what we can handle. */
6172 if (file_number < 0 || file_number > 9)
6173 {
6174 gln_watchdog_tick ();
6175 return;
6176 }
6177
6178 /* Find the last element of the new filename. */
6179 basename = strrchr (newname, GLN_FILE_DELIM);
6180 basename = basename ? basename + 1 : newname;
6181
6182 /* Search for the last numeric character in the basename. */
6183 digit = -1;
6184 for (index = strlen (basename) - 1; index >= 0; index--)
6185 {
6186 if (isdigit (basename[index]))
6187 {
6188 digit = index;
6189 break;
6190 }
6191 }
6192 if (digit == -1)
6193 {
6194 gln_watchdog_tick ();
6195 return;
6196 }
6197
6198 /* Reset the digit in the file name. */
6199 basename[digit] = file_number + '0';
6200
6201 /* Flush pending output, then display the filename generated. */
6202 gln_output_flush ();
6203 gln_game_prompted ();
6204 gln_standout_string ("\nNext disk file: ");
6205 gln_standout_string (basename);
6206 gln_standout_string ("\n\n");
6207
6208 /* Encourage game name re-lookup, and return. */
6209 gln_gameid_game_name_reset ();
6210 gln_watchdog_tick ();
6211 }
6212
6213
6214 /*
6215 * os_open_script_file()
6216 *
6217 * Handles player calls to the "#play" meta-command. Because we have our
6218 * own way of handling scripts, this function is a stub.
6219 */
6220 FILE *
6221 os_open_script_file (void) {
6222 return NULL;
6223 }
6224
6225
6226 /*
6227 * os_find_file()
6228 *
6229 */
6230 L9BOOL os_find_file(char *NewName)
6231 {
6232 char *fname, *p;
6233 FILE *f;
6234
6235 f = fopen(NewName, "rb");
6236 if (f != NULL)
6237 {
6238 fclose(f);
6239 return TRUE;
6240 }
6241
6242 fname = strrchr(NewName, '/');
6243 if (fname != NULL)
6244 ++fname;
6245 else
6246 fname = NewName;
6247
6248 for (p = fname; *p != '\0'; ++p)
6249 *p = toupper(*p);
6250
6251 f = fopen(NewName, "rb");
6252 if (f != NULL)
6253 {
6254 fclose(f);
6255 return TRUE;
6256 }
6257
6258 for (p = fname; *p != '\0'; ++p)
6259 *p = tolower(*p);
6260
6261 f = fopen(NewName, "rb");
6262 if (f != NULL)
6263 {
6264 fclose(f);
6265 return TRUE;
6266 }
6267
6268 return FALSE;
6269 }
6270
6271
6272 /*---------------------------------------------------------------------*/
6273 /* Functions intercepted by link-time wrappers */
6274 /*---------------------------------------------------------------------*/
6275
6276 /*
6277 * __wrap_toupper()
6278 * __wrap_tolower()
6279 *
6280 * Wrapper functions around toupper() and tolower(). The Linux linker's
6281 * --wrap option will convert calls to mumble() to __wrap_mumble() if we
6282 * give it the right options. We'll use this feature to translate all
6283 * toupper() and tolower() calls in the interpreter code into calls to
6284 * Glk's versions of these functions.
6285 *
6286 * It's not critical that we do this. If a linker, say a non-Linux one,
6287 * won't do --wrap, then just do without it. It's unlikely that there
6288 * will be much noticeable difference.
6289 */
6290 int
6291 __wrap_toupper (int ch)
6292 {
6293 unsigned char uch;
6294
6295 uch = glk_char_to_upper ((unsigned char) ch);
6296 return (int) uch;
6297 }
6298
6299 int
6300 __wrap_tolower (int ch)
6301 {
6302 unsigned char lch;
6303
6304 lch = glk_char_to_lower ((unsigned char) ch);
6305 return (int) lch;
6306 }
6307
6308
6309 /*---------------------------------------------------------------------*/
6310 /* main() and options parsing */
6311 /*---------------------------------------------------------------------*/
6312
6313 /*
6314 * Watchdog timeout -- we'll wait for five seconds of silence from the core
6315 * interpreter before offering to stop the game forcibly, and we'll check
6316 * it every 10,240 opcodes.
6317 */
6318 static const int GLN_WATCHDOG_TIMEOUT = 5,
6319 GLN_WATCHDOG_PERIOD = 10240;
6320
6321 /*
6322 * The following values need to be passed between the startup_code and main
6323 * functions.
6324 */
6325 static char *gln_gamefile = NULL, /* Name of game file. */
6326 *gln_game_message = NULL; /* Error message. */
6327
6328
6329 /*
6330 * gln_establish_picture_filename()
6331 *
6332 * Given a game name, try to create an (optional) graphics data file. For
6333 * an input "file" X, the function looks for X.PIC or X.pic, then for
6334 * PICTURE.DAT or picture.dat in the same directory as X. If the input file
6335 * already ends with a three-letter extension, it's stripped first.
6336 *
6337 * The function returns NULL if a graphics file is not available. It's not
6338 * fatal for this to be the case. Filenames are malloc'ed, and need to be
6339 * freed by the caller.
6340 *
6341 * The function uses fopen() rather than access() since fopen() is an ANSI
6342 * standard function, and access() isn't.
6343 */
6344 static void
6345 gln_establish_picture_filename (char *name, char **graphics)
6346 {
6347 char *base, *directory_end, *graphics_file;
6348 FILE *stream = NULL;
6349 assert (name && graphics);
6350
6351 /* Take a destroyable copy of the input filename. */
6352 base = gln_malloc (strlen (name) + 1);
6353 strcpy (base, name);
6354
6355 /* If base has an extension .LEV, .SNA, or similar, remove it. */
6356 if (strrchr (base, '.'))
6357 {
6358 base[strlen (base) - strlen (strrchr (base, '.'))] = '\0';
6359 }
6360
6361 /* Allocate space for the return graphics file. */
6362 graphics_file = gln_malloc (strlen (base) + strlen (".___") + 1);
6363
6364 /* Form a candidate graphics file, using a .PIC extension. */
6365 if (!stream)
6366 {
6367 strcpy (graphics_file, base);
6368 strcat (graphics_file, ".PIC");
6369 stream = fopen (graphics_file, "rb");
6370 }
6371
6372 if (!stream)
6373 {
6374 strcpy (graphics_file, base);
6375 strcat (graphics_file, ".pic");
6376 stream = fopen (graphics_file, "rb");
6377 }
6378
6379 /* Form a candidate graphics file, using a .CGA extension. */
6380 if (!stream)
6381 {
6382 strcpy (graphics_file, base);
6383 strcat (graphics_file, ".CGA");
6384 stream = fopen (graphics_file, "rb");
6385 }
6386
6387 if (!stream)
6388 {
6389 strcpy (graphics_file, base);
6390 strcat (graphics_file, ".cga");
6391 stream = fopen (graphics_file, "rb");
6392 }
6393
6394 /* Form a candidate graphics file, using a .HRC extension. */
6395 if (!stream)
6396 {
6397 strcpy (graphics_file, base);
6398 strcat (graphics_file, ".HRC");
6399 stream = fopen (graphics_file, "rb");
6400 }
6401
6402 if (!stream)
6403 {
6404 strcpy (graphics_file, base);
6405 strcat (graphics_file, ".hrc");
6406 stream = fopen (graphics_file, "rb");
6407 }
6408
6409 /* No access to graphics file. */
6410 if (!stream)
6411 {
6412 free (graphics_file);
6413 graphics_file = NULL;
6414 }
6415
6416 if (stream)
6417 fclose (stream);
6418
6419 /* If we found a graphics file, return its name immediately. */
6420 if (graphics_file)
6421 {
6422 *graphics = graphics_file;
6423 free (base);
6424 return;
6425 }
6426
6427 /* Retry with base set to the game file directory part only. */
6428 directory_end = strrchr (base, GLN_FILE_DELIM);
6429 directory_end = directory_end ? directory_end + 1 : base;
6430 base[directory_end - base] = '\0';
6431
6432 /* Again, allocate space for the return graphics file. */
6433 graphics_file = gln_malloc (strlen (base) + strlen ("PICTURE.DAT") + 1);
6434
6435 /* As above, form a candidate graphics file. */
6436 strcpy (graphics_file, base);
6437 strcat (graphics_file, "PICTURE.DAT");
6438 stream = fopen (graphics_file, "rb");
6439 if (!stream)
6440 {
6441 /* Retry, using picture.dat extension instead. */
6442 strcpy (graphics_file, base);
6443 strcat (graphics_file, "picture.dat");
6444 stream = fopen (graphics_file, "rb");
6445 if (!stream)
6446 {
6447 /*
6448 * No access to this graphics file. In this case, free memory
6449 * and reset graphics file to NULL.
6450 */
6451 free (graphics_file);
6452 graphics_file = NULL;
6453 }
6454 }
6455 if (stream)
6456 fclose (stream);
6457
6458 /*
6459 * Return whatever we found for the graphics file (NULL if none found),
6460 * and free base.
6461 */
6462 *graphics = graphics_file;
6463 free (base);
6464 }
6465
6466
6467 /*
6468 * gln_startup_code()
6469 * gln_main()
6470 *
6471 * Together, these functions take the place of the original main(). The
6472 * first one is called from glkunix_startup_code(), to parse and generally
6473 * handle options. The second is called from glk_main(), and does the real
6474 * work of running the game.
6475 */
6476 static int
6477 gln_startup_code (int argc, char *argv[])
6478 {
6479 int argv_index;
6480
6481 /* Handle command line arguments. */
6482 for (argv_index = 1;
6483 argv_index < argc && argv[argv_index][0] == '-'; argv_index++)
6484 {
6485 if (strcmp (argv[argv_index], "-ni") == 0)
6486 {
6487 gln_intercept_enabled = FALSE;
6488 continue;
6489 }
6490 if (strcmp (argv[argv_index], "-nc") == 0)
6491 {
6492 gln_commands_enabled = FALSE;
6493 continue;
6494 }
6495 if (strcmp (argv[argv_index], "-na") == 0)
6496 {
6497 gln_abbreviations_enabled = FALSE;
6498 continue;
6499 }
6500 if (strcmp (argv[argv_index], "-np") == 0)
6501 {
6502 gln_graphics_enabled = FALSE;
6503 continue;
6504 }
6505 if (strcmp (argv[argv_index], "-ne") == 0)
6506 {
6507 gln_prompt_enabled = FALSE;
6508 continue;
6509 }
6510 if (strcmp (argv[argv_index], "-nl") == 0)
6511 {
6512 gln_loopcheck_enabled = FALSE;
6513 continue;
6514 }
6515 return FALSE;
6516 }
6517
6518 /*
6519 * Get the name of the game file. Since we need this in our call from
6520 * glk_main, we need to keep it in a module static variable. If the game
6521 * file name is omitted, then here we'll set the pointerto NULL, and
6522 * complain about it later in main. Passing the message string around
6523 * like this is a nuisance...
6524 */
6525 if (argv_index == argc - 1)
6526 {
6527 gln_gamefile = argv[argv_index];
6528 gln_game_message = NULL;
6529 #ifdef GARGLK
6530 {
6531 char *s;
6532 s = strrchr(gln_gamefile, '\\');
6533 if (s) garglk_set_story_name(s+1);
6534 s = strrchr(gln_gamefile, '/');
6535 if (s) garglk_set_story_name(s+1);
6536 }
6537 #endif
6538 }
6539 else
6540 {
6541 gln_gamefile = NULL;
6542 if (argv_index < argc - 1)
6543 gln_game_message = "More than one game file was given"
6544 " on the command line.";
6545 else
6546 gln_game_message = "No game file was given on the command line.";
6547 }
6548
6549 /* All startup options were handled successfully. */
6550 return TRUE;
6551 }
6552
6553 static void
6554 gln_main (void)
6555 {
6556 char *graphics_file = NULL;
6557 int is_running;
6558
6559 /* Ensure Level 9 internal types have the right sizes. */
6560 if (!(sizeof (gln_byte) == 1
6561 && sizeof (gln_uint16) == 2 && sizeof (gln_uint32) >= 4))
6562 {
6563 gln_fatal ("GLK: Types sized incorrectly, recompilation is needed");
6564 glk_exit ();
6565 }
6566
6567 /* Create the main Glk window, and set its stream as current. */
6568 gln_main_window = glk_window_open (0, 0, 0, wintype_TextBuffer, 0);
6569 if (!gln_main_window)
6570 {
6571 gln_fatal ("GLK: Can't open main window");
6572 glk_exit ();
6573 }
6574 glk_window_clear (gln_main_window);
6575 glk_set_window (gln_main_window);
6576 glk_set_style (style_Normal);
6577
6578 /* If there's a problem with the game file, complain now. */
6579 if (!gln_gamefile)
6580 {
6581 assert (gln_game_message);
6582 gln_header_string ("Glk Level 9 Error\n\n");
6583 gln_normal_string (gln_game_message);
6584 gln_normal_char ('\n');
6585 glk_exit ();
6586 }
6587
6588 /*
6589 * Given the basic game name, try to come up with a usable graphics
6590 * filenames. The graphics file may be null.
6591 */
6592 gln_establish_picture_filename (gln_gamefile, &graphics_file);
6593
6594 /*
6595 * Check Glk library capabilities, and note pictures are impossible if the
6596 * library can't offer both graphics and timers. We need timers to create
6597 * the background "thread" for picture updates.
6598 */
6599 gln_graphics_possible = glk_gestalt (gestalt_Graphics, 0)
6600 && glk_gestalt (gestalt_Timer, 0);
6601
6602 /*
6603 * If pictures are impossible, clear pictures enabled flag. That is, act
6604 * as if -np was given on the command line, even though it may not have
6605 * been. If pictures are impossible, they can never be enabled.
6606 */
6607 if (!gln_graphics_possible)
6608 gln_graphics_enabled = FALSE;
6609
6610 /* If pictures are possible, search for bitmap graphics. */
6611 if (gln_graphics_possible)
6612 gln_graphics_locate_bitmaps (gln_gamefile);
6613
6614 /* Try to create a one-line status window. We can live without it. */
6615 /*
6616 gln_status_window = glk_window_open (gln_main_window,
6617 winmethod_Above | winmethod_Fixed,
6618 1, wintype_TextGrid, 0);
6619 */
6620
6621 /*
6622 * The main interpreter uses rand(), but never seeds the random number
6623 * generator. This can lead to predictability in games that might be
6624 * better with a little less, so here, we'll seed the random number
6625 * generator ourselves.
6626 */
6627 srand (time (NULL));
6628
6629 /* Repeat this game until no more restarts requested. */
6630 do
6631 {
6632 glk_window_clear (gln_main_window);
6633
6634 /*
6635 * In a multi-file game, restarting may mean reverting back to part one
6636 * of the game. So we have to encourage a re-lookup of the game name
6637 * at this point.
6638 */
6639 gln_gameid_game_name_reset ();
6640
6641 /* Load the game, sending in any established graphics file. */
6642 errno = 0;
6643 if (!LoadGame (gln_gamefile, graphics_file))
6644 {
6645 if (gln_status_window)
6646 glk_window_close (gln_status_window, NULL);
6647 gln_header_string ("Glk Level 9 Error\n\n");
6648 gln_normal_string ("Can't find, open, or load game file '");
6649 gln_normal_string (gln_gamefile);
6650 gln_normal_char ('\'');
6651 if (errno != 0)
6652 {
6653 gln_normal_string (": ");
6654 gln_normal_string (strerror (errno));
6655 }
6656 gln_normal_char ('\n');
6657
6658 /*
6659 * Nothing more to be done, so we'll free interpreter allocated
6660 * memory, then break rather than exit, to run memory cleanup and
6661 * close any open streams.
6662 */
6663 FreeMemory ();
6664 break;
6665 }
6666
6667 /* Print out a short banner. */
6668 gln_header_string ("\nLevel 9 Interpreter, version 5.2\n");
6669 gln_banner_string ("Written by Glen Summers and David Kinder\n"
6670 "Glk interface by Simon Baldwin\n\n");
6671
6672 /*
6673 * Set the stop reason indicator to none. A game will then exit with a
6674 * reason if we call StopGame(), or none if it exits of its own accord
6675 * (or with the "#quit" command, say).
6676 */
6677 gln_stop_reason = STOP_NONE;
6678
6679 /* Start, or restart, watchdog checking. */
6680 gln_watchdog_start (GLN_WATCHDOG_TIMEOUT, GLN_WATCHDOG_PERIOD);
6681
6682 /* Run the game until StopGame called, or RunGame() returns FALSE. */
6683 do
6684 {
6685 is_running = RunGame ();
6686 glk_tick ();
6687
6688 /* Poll for watchdog timeout. */
6689 if (is_running && gln_watchdog_has_timed_out ())
6690 {
6691 gln_stop_reason = STOP_FORCE;
6692 StopGame ();
6693 break;
6694 }
6695 }
6696 while (is_running);
6697
6698 /* Stop watchdog functions, and flush any pending buffered output. */
6699 gln_watchdog_stop ();
6700 gln_status_notify ();
6701 gln_output_flush ();
6702
6703 /* Free interpreter allocated memory. */
6704 FreeMemory ();
6705
6706 /*
6707 * Unset any "stuck" game 'cheating' flag. This can get stuck on if
6708 * exit is forced from the #cheat mode in the Adrian Mole games, which
6709 * otherwise loop infinitely. Unsetting the flag here permits restarts;
6710 * without this, the core interpreter remains permanently in silent
6711 * #cheat mode.
6712 */
6713 Cheating = FALSE;
6714
6715 /*
6716 * If the stop reason is none, something in the game stopped itself, or
6717 * the user entered "#quit". If the stop reason is force, the user
6718 * terminated because of an apparent infinite loop. For both of these,
6719 * offer the choice to restart, or not (equivalent to exit).
6720 */
6721 if (gln_stop_reason == STOP_NONE || gln_stop_reason == STOP_FORCE)
6722 {
6723 gln_standout_string (gln_stop_reason == STOP_NONE
6724 ? "\nThe game has exited.\n"
6725 : "\nGame exit was forced. The current game"
6726 " state is unrecoverable. Sorry.\n");
6727
6728 if (gln_confirm ("\nDo you want to restart? [Y or N] "))
6729 gln_stop_reason = STOP_RESTART;
6730 else
6731 gln_stop_reason = STOP_EXIT;
6732 }
6733 }
6734 while (gln_stop_reason == STOP_RESTART);
6735
6736 /* Free any temporary memory that may have been used by graphics. */
6737 gln_graphics_cleanup ();
6738 gln_linegraphics_cleanup ();
6739
6740 /* Close any open transcript, input log, and/or read log. */
6741 if (gln_transcript_stream)
6742 {
6743 glk_stream_close (gln_transcript_stream, NULL);
6744 gln_transcript_stream = NULL;
6745 }
6746 if (gln_inputlog_stream)
6747 {
6748 glk_stream_close (gln_inputlog_stream, NULL);
6749 gln_inputlog_stream = NULL;
6750 }
6751 if (gln_readlog_stream)
6752 {
6753 glk_stream_close (gln_readlog_stream, NULL);
6754 gln_readlog_stream = NULL;
6755 }
6756
6757 /* Free any graphics file path. */
6758 free (graphics_file);
6759 }
6760
6761
6762 /*---------------------------------------------------------------------*/
6763 /* Linkage between Glk entry/exit calls and the real interpreter */
6764 /*---------------------------------------------------------------------*/
6765
6766 /*
6767 * Safety flags, to ensure we always get startup before main, and that
6768 * we only get a call to main once.
6769 */
6770 static int gln_startup_called = FALSE,
6771 gln_main_called = FALSE;
6772
6773 /*
6774 * glk_main()
6775 *
6776 * Main entry point for Glk. Here, all startup is done, and we call our
6777 * function to run the game.
6778 */
6779 void
6780 glk_main (void)
6781 {
6782 assert (gln_startup_called && !gln_main_called);
6783 gln_main_called = TRUE;
6784
6785 /* Call the interpreter main function. */
6786 gln_main ();
6787 }
6788
6789
6790 /*---------------------------------------------------------------------*/
6791 /* Glk linkage relevant only to the UNIX platform */
6792 /*---------------------------------------------------------------------*/
6793 #ifdef TRUE
6794
6795 #include "glkstart.h"
6796
6797 /*
6798 * Glk arguments for UNIX versions of the Glk interpreter.
6799 */
6800 glkunix_argumentlist_t glkunix_arguments[] = {
6801 {(char *) "-nc", glkunix_arg_NoValue,
6802 (char *) "-nc No local handling for Glk special commands"},
6803 {(char *) "-na", glkunix_arg_NoValue,
6804 (char *) "-na Turn off abbreviation expansions"},
6805 {(char *) "-ni", glkunix_arg_NoValue,
6806 (char *) "-ni No local handling for 'quit', 'restart',"
6807 " 'save', and 'restore'"},
6808 {(char *) "-np", glkunix_arg_NoValue,
6809 (char *) "-np Turn off pictures"},
6810 {(char *) "-ne", glkunix_arg_NoValue,
6811 (char *) "-ne Turn off additional interpreter prompt"},
6812 {(char *) "-nl", glkunix_arg_NoValue,
6813 (char *) "-nl Turn off infinite loop detection"},
6814 {(char *) "", glkunix_arg_ValueCanFollow,
6815 (char *) "filename game to run"},
6816 {NULL, glkunix_arg_End, NULL}
6817 };
6818
6819
6820 /*
6821 * glkunix_startup_code()
6822 *
6823 * Startup entry point for UNIX versions of Glk interpreter. Glk will
6824 * call glkunix_startup_code() to pass in arguments. On startup, we call
6825 * our function to parse arguments and generally set stuff up.
6826 */
6827 int
6828 glkunix_startup_code (glkunix_startup_t * data)
6829 {
6830 assert (!gln_startup_called);
6831 gln_startup_called = TRUE;
6832
6833 #ifdef GARGLK
6834 garglk_set_program_name("Level 9 5.1");
6835 garglk_set_program_info(
6836 "Level 9 5.1 by Glen Summers, David Kinder\n"
6837 "Alan Staniforth, Simon Baldwin and Dieter Baron\n"
6838 "Glk Graphics support by Tor Andersson\n");
6839 #endif
6840
6841 return gln_startup_code (data->argc, data->argv);
6842 }
6843 #endif /* __unix */
6844
6845
6846 /*---------------------------------------------------------------------*/
6847 /* Glk linkage relevant only to the Mac platform */
6848 /*---------------------------------------------------------------------*/
6849 #ifndef GARGLK
6850 #ifdef TARGET_OS_MAC
6851
6852 #include "macglk_startup.h"
6853
6854 /* Additional Mac variables. */
6855 static strid_t gln_mac_gamefile = NULL;
6856 static short gln_savedVRefNum = 0;
6857 static long gln_savedDirID = 0;
6858
6859
6860 /*
6861 * gln_mac_whenselected()
6862 * gln_mac_whenbuiltin()
6863 * macglk_startup_code()
6864 *
6865 * Startup entry points for Mac versions of Glk interpreter. Glk will
6866 * call macglk_startup_code() for details on what to do when the app-
6867 * lication is selected. On selection, an argv[] vector is built, and
6868 * passed to the normal interpreter startup code, after which, Glk will
6869 * call glk_main().
6870 */
6871 static Boolean
6872 gln_mac_whenselected (FSSpec * file, OSType filetype)
6873 {
6874 static char *argv[2];
6875 assert (!gln_startup_called);
6876 gln_startup_called = TRUE;
6877
6878 /* Set the WD to where the file is, so later fopens work. */
6879 if (HGetVol (0, &gln_savedVRefNum, &gln_savedDirID) != 0)
6880 {
6881 gln_fatal ("GLK: HGetVol failed");
6882 return FALSE;
6883 }
6884 if (HSetVol (0, file->vRefNum, file->parID) != 0)
6885 {
6886 gln_fatal ("GLK: HSetVol failed");
6887 return FALSE;
6888 }
6889
6890 /* Put a CString version of the PString name into argv[1]. */
6891 argv[1] = gln_malloc (file->name[0] + 1);
6892 BlockMoveData (file->name + 1, argv[1], file->name[0]);
6893 argv[1][file->name[0]] = '\0';
6894 argv[2] = NULL;
6895
6896 return gln_startup_code (2, argv);
6897 }
6898
6899 static Boolean
6900 gln_mac_whenbuiltin (void)
6901 {
6902 /* Not implemented yet. */
6903 return TRUE;
6904 }
6905
6906 Boolean
6907 macglk_startup_code (macglk_startup_t * data)
6908 {
6909 static OSType gln_mac_gamefile_types[] = { 'LVL9' };
6910
6911 data->startup_model = macglk_model_ChooseOrBuiltIn;
6912 data->app_creator = 'cAGL';
6913 data->gamefile_types = gln_mac_gamefile_types;
6914 data->num_gamefile_types = sizeof (gln_mac_gamefile_types)
6915 / sizeof (*gln_mac_gamefile_types);
6916 data->savefile_type = 'BINA';
6917 data->datafile_type = 0x3f3f3f3f;
6918 data->gamefile = &gln_mac_gamefile;
6919 data->when_selected = gln_mac_whenselected;
6920 data->when_builtin = gln_mac_whenbuiltin;
6921 /* macglk_setprefs(); */
6922 return TRUE;
6923 }
6924 #endif /* TARGET_OS_MAC */
6925 #endif