Debian Codegraph @

terps/magnetic/Glk/glk.c

raw symbols SCIP
1 /* vi: set ts=2 shiftwidth=2 expandtab:
2 *
3 * Copyright (C) 2002-2006 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 Magnetic Scrolls 2.3
23 * --------------------------------------
24 *
25 * This module contains the the Glk porting layer for the Magnetic
26 * Scrolls interpreter. It defines the Glk arguments list structure,
27 * the 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 Magnetic
34 * Scrolls 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 "defs.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
65 /*---------------------------------------------------------------------*/
66 /* Module variables, miscellaneous other stuff */
67 /*---------------------------------------------------------------------*/
68
69 /* Glk Magnetic Scrolls port version number. */
70 static const glui32 GMS_PORT_VERSION = 0x00010601;
71
72 /*
73 * We use a maximum of five Glk windows, one for status, one for pictures,
74 * two for hints, and one for everything else. The status and pictures
75 * windows may be NULL, depending on user selections and the capabilities
76 * of the Glk library. The hints windows will normally be NULL, except
77 * when in the hints subsystem.
78 */
79 static winid_t gms_main_window = NULL,
80 gms_status_window = NULL,
81 gms_graphics_window = NULL,
82 gms_hint_menu_window = NULL,
83 gms_hint_text_window = NULL;
84
85 /*
86 * Transcript stream and input log. These are NULL if there is no current
87 * collection of these strings.
88 */
89 static strid_t gms_transcript_stream = NULL,
90 gms_inputlog_stream = NULL;
91
92 /* Input read log stream, for reading back an input log. */
93 static strid_t gms_readlog_stream = NULL;
94
95 /* Note about whether graphics is possible, or not. */
96 static int gms_graphics_possible = TRUE;
97
98 /* Options that may be turned off or set by command line flags. */
99 static int gms_graphics_enabled = TRUE;
100 static enum {
101 GAMMA_OFF, GAMMA_NORMAL, GAMMA_HIGH
102 }
103 gms_gamma_mode = GAMMA_NORMAL;
104 static int gms_animation_enabled = TRUE,
105 gms_prompt_enabled = TRUE,
106 gms_abbreviations_enabled = TRUE,
107 gms_commands_enabled = TRUE;
108
109 /* Magnetic Scrolls standard input prompt string. */
110 static const char * const GMS_INPUT_PROMPT = ">";
111
112 /* Forward declaration of event wait function. */
113 static void gms_event_wait (glui32 wait_type, event_t * event);
114
115
116 /*---------------------------------------------------------------------*/
117 /* Glk port utility functions */
118 /*---------------------------------------------------------------------*/
119
120 /*
121 * gms_fatal()
122 *
123 * Fatal error handler. The function returns, expecting the caller to
124 * abort() or otherwise handle the error.
125 */
126 static void
127 gms_fatal (const char *string)
128 {
129 /*
130 * If the failure happens too early for us to have a window, print
131 * the message to stderr.
132 */
133 if (!gms_main_window)
134 {
135 fprintf (stderr, "\n\nINTERNAL ERROR: %s\n", string);
136
137 fprintf (stderr, "\nPlease record the details of this error, try to"
138 " note down everything you did to cause it, and email"
139 " this information to [email protected].\n\n");
140 return;
141 }
142
143 /* Cancel all possible pending window input events. */
144 glk_cancel_line_event (gms_main_window, NULL);
145 glk_cancel_char_event (gms_main_window);
146 if (gms_hint_menu_window)
147 {
148 glk_cancel_char_event (gms_hint_menu_window);
149 glk_window_close (gms_hint_menu_window, NULL);
150 }
151 if (gms_hint_text_window)
152 {
153 glk_cancel_char_event (gms_hint_text_window);
154 glk_window_close (gms_hint_text_window, NULL);
155 }
156
157 /* Print a message indicating the error. */
158 glk_set_window (gms_main_window);
159 glk_set_style (style_Normal);
160 glk_put_string ("\n\nINTERNAL ERROR: ");
161 glk_put_string ((char *) string);
162
163 glk_put_string ("\n\nPlease record the details of this error, try to"
164 " note down everything you did to cause it, and email"
165 " this information to [email protected].\n\n");
166 }
167
168
169 /*
170 * gms_malloc()
171 * gms_realloc()
172 *
173 * Non-failing malloc and realloc; call gms_fatal and exit if memory
174 * allocation fails.
175 */
176 static void *
177 gms_malloc (size_t size)
178 {
179 void *pointer;
180
181 pointer = malloc (size);
182 if (!pointer)
183 {
184 gms_fatal ("GLK: Out of system memory");
185 glk_exit ();
186 }
187
188 return pointer;
189 }
190
191 static void *
192 gms_realloc (void *ptr, size_t size)
193 {
194 void *pointer;
195
196 pointer = realloc (ptr, size);
197 if (!pointer)
198 {
199 gms_fatal ("GLK: Out of system memory");
200 glk_exit ();
201 }
202
203 return pointer;
204 }
205
206
207 /*
208 * gms_strncasecmp()
209 * gms_strcasecmp()
210 *
211 * Strncasecmp and strcasecmp are not ANSI functions, so here are local
212 * definitions to do the same jobs.
213 */
214 static int
215 gms_strncasecmp (const char *s1, const char *s2, size_t n)
216 {
217 size_t index;
218
219 for (index = 0; index < n; index++)
220 {
221 int diff;
222
223 diff = glk_char_to_lower (s1[index]) - glk_char_to_lower (s2[index]);
224 if (diff < 0 || diff > 0)
225 return diff < 0 ? -1 : 1;
226 }
227
228 return 0;
229 }
230
231 static int
232 gms_strcasecmp (const char *s1, const char *s2)
233 {
234 size_t s1len, s2len;
235 int result;
236
237 s1len = strlen (s1);
238 s2len = strlen (s2);
239
240 result = gms_strncasecmp (s1, s2, s1len < s2len ? s1len : s2len);
241 if (result < 0 || result > 0)
242 return result;
243 else
244 return s1len < s2len ? -1 : s1len > s2len ? 1 : 0;
245 }
246
247
248 /*---------------------------------------------------------------------*/
249 /* Glk port stub graphics functions */
250 /*---------------------------------------------------------------------*/
251
252 /*
253 * If we're working with a very stripped down, old, or lazy Glk library
254 * that neither offers Glk graphics nor graphics stubs functions, here
255 * we define our own stubs, to avoid link-time errors.
256 */
257 #ifndef GLK_MODULE_IMAGE
258 static glui32
259 glk_image_draw (winid_t win, glui32 image, glsi32 val1, glsi32 val2)
260 {
261 return FALSE;
262 }
263 static glui32
264 glk_image_draw_scaled (winid_t win, glui32 image, glsi32 val1, glsi32 val2,
265 glui32 width, glui32 height)
266 {
267 return FALSE;
268 }
269 static glui32
270 glk_image_get_info (glui32 image, glui32 * width, glui32 * height)
271 {
272 return FALSE;
273 }
274 static void
275 glk_window_flow_break (winid_t win)
276 {
277 }
278 static void
279 glk_window_erase_rect (winid_t win, glsi32 left, glsi32 top,
280 glui32 width, glui32 height)
281 {
282 }
283 static void
284 glk_window_fill_rect (winid_t win, glui32 color, glsi32 left, glsi32 top,
285 glui32 width, glui32 height)
286 {
287 }
288 static void
289 glk_window_set_background_color (winid_t win, glui32 color)
290 {
291 }
292 #endif
293
294
295 /*---------------------------------------------------------------------*/
296 /* Glk port CRC functions */
297 /*---------------------------------------------------------------------*/
298
299 /* CRC table initialization polynomial. */
300 static const glui32 GMS_CRC_POLYNOMIAL = 0xedb88320;
301
302
303 /*
304 * gms_get_buffer_crc()
305 *
306 * Return the CRC of the bytes in buffer[0..length-1].
307 *
308 * This algorithm is taken from the PNG specification, version 1.0.
309 */
310 static glui32
311 gms_get_buffer_crc (const void *void_buffer, size_t length)
312 {
313 static int is_initialized = FALSE;
314 static glui32 crc_table[UCHAR_MAX + 1];
315
316 const char *buffer = (const char *) void_buffer;
317 glui32 crc;
318 size_t index;
319
320 /* Build the static CRC lookup table on first call. */
321 if (!is_initialized)
322 {
323 for (index = 0; index < UCHAR_MAX + 1; index++)
324 {
325 int bit;
326
327 crc = (glui32) index;
328 for (bit = 0; bit < CHAR_BIT; bit++)
329 crc = crc & 1 ? GMS_CRC_POLYNOMIAL ^ (crc >> 1) : crc >> 1;
330
331 crc_table[index] = crc;
332 }
333
334 is_initialized = TRUE;
335
336 /* CRC lookup table self-test, after is_initialized set -- recursion. */
337 assert (gms_get_buffer_crc ("123456789", 9) == 0xcbf43926);
338 }
339
340 /*
341 * Start with all ones in the crc, then update using table entries. Xor
342 * with all ones again, finally, before returning.
343 */
344 crc = 0xffffffff;
345 for (index = 0; index < length; index++)
346 crc = crc_table[(crc ^ buffer[index]) & UCHAR_MAX] ^ (crc >> CHAR_BIT);
347 return crc ^ 0xffffffff;
348 }
349
350
351 /*---------------------------------------------------------------------*/
352 /* Glk port game identification data and identification functions */
353 /*---------------------------------------------------------------------*/
354
355 /*
356 * The game's name, suitable for printing out on a status line, or other
357 * location where game information is relevant. Set on game startup, by
358 * identifying the game from its text file header.
359 */
360 static const char *gms_gameid_game_name = NULL;
361
362
363 /*
364 * The following game database is built from Generic/games.txt, and is used
365 * to identify the game being run. Magnetic Scrolls games don't generally
366 * supply a status line, so this data can be used instead.
367 */
368 typedef const struct {
369 const type32 undo_size; /* Header word at offset 0x22 */
370 const type32 undo_pc; /* Header word at offset 0x26 */
371 const char * const name; /* Game title and platform */
372 } gms_game_table_t;
373 typedef gms_game_table_t *gms_game_tableref_t;
374
375 static gms_game_table_t GMS_GAME_TABLE[] = {
376 {0x2100, 0x427e, "Corruption v1.11 (Amstrad CPC)"},
377 {0x2100, 0x43a0, "Corruption v1.11 (Archimedes)"},
378 {0x2100, 0x43a0, "Corruption v1.11 (DOS)"},
379 {0x2100, 0x4336, "Corruption v1.11 (Commodore 64)"},
380 {0x2100, 0x4222, "Corruption v1.11 (Spectrum +3)"},
381 {0x2100, 0x4350, "Corruption v1.12 (Archimedes)"},
382 {0x2500, 0x6624, "Corruption v1.12 (DOS, Magnetic Windows)"},
383
384 {0x2300, 0x3fa0, "Fish v1.02 (DOS)"},
385 {0x2400, 0x4364, "Fish v1.03 (Spectrum +3)"},
386 {0x2300, 0x3f72, "Fish v1.07 (Commodore 64)"},
387 {0x2200, 0x3f9c, "Fish v1.08 (Archimedes)"},
388 {0x2a00, 0x583a, "Fish v1.10 (DOS, Magnetic Windows)"},
389
390 {0x5000, 0x6c30, "Guild v1.0 (Amstrad CPC)"},
391 {0x5000, 0x6cac, "Guild v1.0 (Commodore 64)"},
392 {0x5000, 0x6d5c, "Guild v1.1 (DOS)"},
393 {0x3300, 0x698a, "Guild v1.3 (Archimedes)"},
394 {0x3200, 0x6772, "Guild v1.3 (Spectrum +3)"},
395 {0x3400, 0x6528, "Guild v1.3 (DOS, Magnetic Windows)"},
396
397 {0x2b00, 0x488c, "Jinxter v1.05 (Commodore 64)"},
398 {0x2c00, 0x4a08, "Jinxter v1.05 (DOS)"},
399 {0x2c00, 0x487a, "Jinxter v1.05 (Spectrum +3)"},
400 {0x2c00, 0x4a56, "Jinxter v1.10 (DOS)"},
401 {0x2b00, 0x4924, "Jinxter v1.22 (Amstrad CPC)"},
402 {0x2c00, 0x4960, "Jinxter v1.30 (Archimedes)"},
403
404 {0x1600, 0x3940, "Myth v1.0 (Commodore 64)"},
405 {0x1500, 0x3a0a, "Myth v1.0 (DOS)"},
406
407 {0x3600, 0x42cc, "Pawn v2.3 (Amstrad CPC)"},
408 {0x3600, 0x4420, "Pawn v2.3 (Archimedes)"},
409 {0x3600, 0x3fb0, "Pawn v2.3 (Commodore 64)"},
410 {0x3600, 0x4420, "Pawn v2.3 (DOS)"},
411 {0x3900, 0x42e4, "Pawn v2.3 (Spectrum 128)"},
412 {0x3900, 0x42f4, "Pawn v2.4 (Spectrum +3)"},
413
414 {0x3900, 0x75f2, "Wonderland v1.21 (DOS, Magnetic Windows)"},
415 {0x3900, 0x75f8, "Wonderland v1.27 (Archimedes)"},
416 {0, 0, NULL}
417 };
418
419
420 /*
421 * gms_gameid_lookup_game()
422 *
423 * Look up and return the game table entry given a game's undo size and
424 * undo pc values. Returns the entry, or NULL if not found.
425 */
426 static gms_game_tableref_t
427 gms_gameid_lookup_game (type32 undo_size, type32 undo_pc)
428 {
429 gms_game_tableref_t game;
430
431 for (game = GMS_GAME_TABLE; game->name; game++)
432 {
433 if (game->undo_size == undo_size && game->undo_pc == undo_pc)
434 break;
435 }
436
437 return game->name ? game : NULL;
438 }
439
440
441 /*
442 * gms_gameid_read_uint32()
443 *
444 * Endian-safe unsigned 32 bit integer read from game text file. Returns
445 * 0 on error, a known unused table value.
446 */
447 static type32
448 gms_gameid_read_uint32 (int offset, FILE *stream)
449 {
450 unsigned char buffer[4];
451
452 if (fseek (stream, offset, SEEK_SET) != 0)
453 return 0;
454 if (fread (buffer, 1, sizeof (buffer), stream) != sizeof (buffer))
455 return 0;
456
457 return buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
458 }
459
460
461 /*
462 * gms_gameid_identify_game()
463 *
464 * Identify a game from its text file header, and cache the game's name for
465 * later queries. Sets the cache to NULL if not found.
466 */
467 static void
468 gms_gameid_identify_game (const char *text_file)
469 {
470 FILE *stream;
471 assert (text_file);
472
473 stream = fopen (text_file, "r");
474 if (stream)
475 {
476 type32 undo_size, undo_pc;
477 gms_game_tableref_t game;
478
479 /* Read the game's signature undo size and undo pc values. */
480 undo_size = gms_gameid_read_uint32 (0x22, stream);
481 undo_pc = gms_gameid_read_uint32 (0x26, stream);
482 fclose (stream);
483
484 /* Search for these values in the table, and set game name if found. */
485 game = gms_gameid_lookup_game (undo_size, undo_pc);
486 gms_gameid_game_name = game ? game->name : NULL;
487 }
488 else
489 gms_gameid_game_name = NULL;
490 }
491
492
493 /*
494 * gms_gameid_get_game_name()
495 *
496 * Return the name of the game, or NULL if not identifiable.
497 */
498 static const char *
499 gms_gameid_get_game_name (void)
500 {
501 return gms_gameid_game_name;
502 }
503
504
505 /*---------------------------------------------------------------------*/
506 /* Glk port picture functions */
507 /*---------------------------------------------------------------------*/
508
509 /*
510 * Color conversions lookup tables, and a word about gamma corrections.
511 *
512 * When uncorrected, some game pictures can look dark (Corruption, Won-
513 * derland), whereas others look just fine (Guild Of Thieves, Jinxter).
514 *
515 * The standard general-purpose gamma correction is around 2.1, with
516 * specific values, normally, of 2.5-2.7 for IBM PC systems, and 1.8 for
517 * Macintosh. However, applying even the low end of this range can make
518 * some pictures look washed out, yet improve others nicely.
519 *
520 * To try to solve this, here we'll set up a precalculated table with
521 * discrete gamma values. On displaying a picture, we'll try to find a
522 * gamma correction that seems to offer a reasonable level of contrast
523 * for the picture.
524 *
525 * Here's an AWK script to create the gamma table:
526 *
527 * BEGIN { max=255.0; step=max/7.0
528 * for (gamma=0.9; gamma<=2.7; gamma+=0.05) {
529 * printf " {\"%2.2f\", {0, ", gamma
530 * for (i=1; i<8; i++) {
531 * printf "%3.0f", (((step*i / max) ^ (1.0/gamma)) * max)
532 * printf "%s", (i<7) ? ", " : ""
533 * }
534 * printf "}, "
535 * printf "%s },\n", (gamma>0.99 && gamma<1.01) ? "FALSE" : "TRUE "
536 * } }
537 *
538 */
539 typedef const struct
540 {
541 const char * const level; /* Gamma correction level. */
542 const unsigned char table[8]; /* Color lookup table. */
543 const int is_corrected; /* Flag if non-linear. */
544 } gms_gamma_t;
545 typedef gms_gamma_t *gms_gammaref_t;
546
547 static gms_gamma_t GMS_GAMMA_TABLE[] = {
548 {"0.90", {0, 29, 63, 99, 137, 175, 215, 255}, TRUE},
549 {"0.95", {0, 33, 68, 105, 141, 179, 217, 255}, TRUE},
550 {"1.00", {0, 36, 73, 109, 146, 182, 219, 255}, FALSE},
551 {"1.05", {0, 40, 77, 114, 150, 185, 220, 255}, TRUE},
552 {"1.10", {0, 43, 82, 118, 153, 188, 222, 255}, TRUE},
553 {"1.15", {0, 47, 86, 122, 157, 190, 223, 255}, TRUE},
554 {"1.20", {0, 50, 90, 126, 160, 193, 224, 255}, TRUE},
555 {"1.25", {0, 54, 94, 129, 163, 195, 225, 255}, TRUE},
556 {"1.30", {0, 57, 97, 133, 166, 197, 226, 255}, TRUE},
557 {"1.35", {0, 60, 101, 136, 168, 199, 227, 255}, TRUE},
558 {"1.40", {0, 64, 104, 139, 171, 201, 228, 255}, TRUE},
559 {"1.45", {0, 67, 107, 142, 173, 202, 229, 255}, TRUE},
560 {"1.50", {0, 70, 111, 145, 176, 204, 230, 255}, TRUE},
561 {"1.55", {0, 73, 114, 148, 178, 205, 231, 255}, TRUE},
562 {"1.60", {0, 76, 117, 150, 180, 207, 232, 255}, TRUE},
563 {"1.65", {0, 78, 119, 153, 182, 208, 232, 255}, TRUE},
564 {"1.70", {0, 81, 122, 155, 183, 209, 233, 255}, TRUE},
565 {"1.75", {0, 84, 125, 157, 185, 210, 233, 255}, TRUE},
566 {"1.80", {0, 87, 127, 159, 187, 212, 234, 255}, TRUE},
567 {"1.85", {0, 89, 130, 161, 188, 213, 235, 255}, TRUE},
568 {"1.90", {0, 92, 132, 163, 190, 214, 235, 255}, TRUE},
569 {"1.95", {0, 94, 134, 165, 191, 215, 236, 255}, TRUE},
570 {"2.00", {0, 96, 136, 167, 193, 216, 236, 255}, TRUE},
571 {"2.05", {0, 99, 138, 169, 194, 216, 237, 255}, TRUE},
572 {"2.10", {0, 101, 140, 170, 195, 217, 237, 255}, TRUE},
573 {"2.15", {0, 103, 142, 172, 197, 218, 237, 255}, TRUE},
574 {"2.20", {0, 105, 144, 173, 198, 219, 238, 255}, TRUE},
575 {"2.25", {0, 107, 146, 175, 199, 220, 238, 255}, TRUE},
576 {"2.30", {0, 109, 148, 176, 200, 220, 238, 255}, TRUE},
577 {"2.35", {0, 111, 150, 178, 201, 221, 239, 255}, TRUE},
578 {"2.40", {0, 113, 151, 179, 202, 222, 239, 255}, TRUE},
579 {"2.45", {0, 115, 153, 180, 203, 222, 239, 255}, TRUE},
580 {"2.50", {0, 117, 154, 182, 204, 223, 240, 255}, TRUE},
581 {"2.55", {0, 119, 156, 183, 205, 223, 240, 255}, TRUE},
582 {"2.60", {0, 121, 158, 184, 206, 224, 240, 255}, TRUE},
583 {"2.65", {0, 122, 159, 185, 206, 225, 241, 255}, TRUE},
584 {"2.70", {0, 124, 160, 186, 207, 225, 241, 255}, TRUE},
585 {NULL, {0, 0, 0, 0, 0, 0, 0, 0}, FALSE}
586 };
587
588 /* R,G,B color triple definition. */
589 typedef struct
590 {
591 int red, green, blue;
592 } gms_rgb_t;
593 typedef gms_rgb_t *gms_rgbref_t;
594
595 /*
596 * Weighting values for calculating the luminance of a color. There are
597 * two commonly used sets of values for these -- 299,587,114, taken from
598 * NTSC (Never The Same Color) 1953 standards, and 212,716,72, which is the
599 * set that modern CRTs tend to match. The NTSC ones seem to give the best
600 * subjective results.
601 */
602 static const gms_rgb_t GMS_LUMINANCE_WEIGHTS = { 299, 587, 114 };
603
604 /*
605 * Maximum number of regions to consider in a single repaint pass. A
606 * couple of hundred seems to strike the right balance between not too
607 * sluggardly picture updates, and responsiveness to input during graphics
608 * rendering, when combined with short timeouts.
609 */
610 static const int GMS_REPAINT_LIMIT = 256;
611
612 /*
613 * Graphics timeout; we like an update call after this period (ms). In
614 * practice, this timeout may actually be shorter than the time taken
615 * to reach the limit on repaint regions, but because Glk guarantees that
616 * user interactions (in this case, line events) take precedence over
617 * timeouts, this should be okay; we'll still see a game that responds to
618 * input each time the background repaint function yields.
619 *
620 * Setting this value is tricky. We'd like it to be the shortest possible
621 * consistent with getting other stuff done, say 10ms. However, Xglk has
622 * a granularity of 50ms on checking for timeouts, as it uses a 1/20s
623 * timeout on X select. This means that the shortest timeout we'll ever
624 * get from Xglk will be 50ms, so there's no point in setting this shorter
625 * than that. With luck, other Glk libraries will be more efficient than
626 * this, and can give us higher timer resolution; we'll set 50ms here, and
627 * hope that no other Glk library is worse.
628 */
629 static const glui32 GMS_GRAPHICS_TIMEOUT = 50;
630
631 /*
632 * Count of timeouts to wait in between animation paints, and to wait on
633 * repaint request. Waiting for 2 timeouts of around 50ms, gets us to the
634 * 100ms recommended animation frame rate. Waiting after a repaint smooths
635 * the display where the frame is being resized, by helping to avoid
636 * graphics output while more resize events are received; around 1/2 second
637 * seems okay.
638 */
639 static const int GMS_GRAPHICS_ANIMATION_WAIT = 2,
640 GMS_GRAPHICS_REPAINT_WAIT = 10;
641
642 /* Pixel size multiplier for image size scaling. */
643 static int gms_graphics_pixel = 2;
644
645 /* Proportion of the display to use for graphics. */
646 static glui32 gms_graphics_proportion = 60;
647
648 /* Height, in pixels, of the graphics window. Takes precendence over
649 * gms_graphics_pixel. If 0, ignore.
650 */
651 static glui32 gms_graphics_height_pixels = 0;
652
653 /*
654 * Border and shading control. For cases where we can't detect the back-
655 * ground color of the main window, there's a default, white, background.
656 * Bordering is black, with a 1 pixel border, 2 pixel shading, and 8 steps
657 * of shading fade.
658 */
659 static const glui32 GMS_GRAPHICS_DEFAULT_BACKGROUND = 0x00ffffff,
660 GMS_GRAPHICS_BORDER_COLOR = 0x00000000;
661 static const int GMS_GRAPHICS_BORDER = 1,
662 GMS_GRAPHICS_SHADING = 2,
663 GMS_GRAPHICS_SHADE_STEPS = 8;
664
665 /*
666 * Guaranteed unused pixel value. This value is used to fill the on-screen
667 * buffer on new pictures or repaints, resulting in a full paint of all
668 * pixels since no off-screen, real picture, pixel will match it.
669 */
670 static const int GMS_GRAPHICS_UNUSED_PIXEL = 0xff;
671
672 /*
673 * The current picture bitmap being displayed, its width, height, palette,
674 * animation flag, and picture id.
675 */
676 enum { GMS_PALETTE_SIZE = 16 };
677 static type8 *gms_graphics_bitmap = NULL;
678 static type16 gms_graphics_width = 0,
679 gms_graphics_height = 0,
680 gms_graphics_palette[GMS_PALETTE_SIZE]; /* = { 0, ... }; */
681 static type8 gms_graphics_animated = FALSE;
682 static type32 gms_graphics_picture = 0;
683
684 /*
685 * Flags set on new picture, and on resize or arrange events, and a flag
686 * to indicate whether background repaint is stopped or active.
687 */
688 static int gms_graphics_new_picture = FALSE,
689 gms_graphics_repaint = FALSE,
690 gms_graphics_active = FALSE;
691
692 /* Flag to try to monitor the state of interpreter graphics. */
693 static int gms_graphics_interpreter = FALSE;
694
695 /*
696 * Pointer to the two graphics buffers, one the off-screen representation
697 * of pixels, and the other tracking on-screen data. These are temporary
698 * graphics malloc'ed memory, and should be free'd on exit.
699 */
700 static type8 *gms_graphics_off_screen = NULL,
701 *gms_graphics_on_screen = NULL;
702
703 /*
704 * Pointer to the current active gamma table entry. Because of the way
705 * it's queried, this may not be NULL, otherwise we risk a race, with
706 * admittedly a very low probability, with the updater. So, it's init-
707 * ialized instead to the gamma table. The real value in use is inserted
708 * on the first picture update timeout call for a new picture.
709 */
710 static gms_gammaref_t gms_graphics_current_gamma = GMS_GAMMA_TABLE;
711
712 /*
713 * The number of colors used in the palette by the current picture. This
714 * value is also at risk of a race with the updater, so it too has a mild
715 * lie for a default value.
716 */
717 static int gms_graphics_color_count = GMS_PALETTE_SIZE;
718
719
720 /*
721 * gms_graphics_open()
722 *
723 * If it's not open, open the graphics window. Returns TRUE if graphics
724 * was successfully started, or already on.
725 */
726 static int
727 gms_graphics_open (void)
728 {
729 if (!gms_graphics_window)
730 {
731 if (gms_graphics_height_pixels > 0)
732 {
733 gms_graphics_window = glk_window_open (gms_main_window,
734 winmethod_Above
735 | winmethod_Fixed,
736 gms_graphics_height_pixels,
737 wintype_Graphics, 0);
738 }
739 else
740 {
741 gms_graphics_window = glk_window_open (gms_main_window,
742 winmethod_Above
743 | winmethod_Proportional,
744 gms_graphics_proportion,
745 wintype_Graphics, 0);
746 }
747 }
748
749 return gms_graphics_window != NULL;
750 }
751
752
753 /*
754 * gms_graphics_close()
755 *
756 * If open, close the graphics window and set back to NULL.
757 */
758 static void
759 gms_graphics_close (void)
760 {
761 if (gms_graphics_window)
762 {
763 glk_window_close (gms_graphics_window, NULL);
764 gms_graphics_window = NULL;
765 }
766 }
767
768
769 /*
770 * gms_graphics_start()
771 *
772 * If graphics enabled, start any background picture update processing.
773 */
774 static void
775 gms_graphics_start (void)
776 {
777 if (gms_graphics_enabled)
778 {
779 /* If not running, start the updating "thread". */
780 if (!gms_graphics_active)
781 {
782 glk_request_timer_events (GMS_GRAPHICS_TIMEOUT);
783 gms_graphics_active = TRUE;
784 }
785 }
786 }
787
788
789 /*
790 * gms_graphics_stop()
791 *
792 * Stop any background picture update processing.
793 */
794 static void
795 gms_graphics_stop (void)
796 {
797 /* If running, stop the updating "thread". */
798 if (gms_graphics_active)
799 {
800 glk_request_timer_events (0);
801 gms_graphics_active = FALSE;
802 }
803 }
804
805
806 /*
807 * gms_graphics_are_displayed()
808 *
809 * Return TRUE if graphics are currently being displayed, FALSE otherwise.
810 */
811 static int
812 gms_graphics_are_displayed (void)
813 {
814 return gms_graphics_window != NULL;
815 }
816
817
818 /*
819 * gms_graphics_paint()
820 *
821 * Set up a complete repaint of the current picture in the graphics window.
822 * This function should be called on the appropriate Glk window resize and
823 * arrange events.
824 */
825 static void
826 gms_graphics_paint (void)
827 {
828 if (gms_graphics_enabled && gms_graphics_are_displayed ())
829 {
830 /* Set the repaint flag, and start graphics. */
831 gms_graphics_repaint = TRUE;
832 gms_graphics_start ();
833 }
834 }
835
836
837 /*
838 * gms_graphics_restart()
839 *
840 * Restart graphics as if the current picture is a new picture. This
841 * function should be called whenever graphics is re-enabled after being
842 * disabled, on change of gamma color correction policy, and on change
843 * of animation policy.
844 */
845 static void
846 gms_graphics_restart (void)
847 {
848 if (gms_graphics_enabled && gms_graphics_are_displayed ())
849 {
850 /*
851 * If the picture is animated, we'll need to be able to re-get the
852 * first animation frame so that the picture can be treated as if
853 * it is a new one. So here, we'll try to re-extract the current
854 * picture to do this. Calling ms_extract() is safe because we
855 * don't get here unless graphics are displayed, and graphics aren't
856 * displayed until there's a valid picture loaded, and ms_showpic
857 * only loads a picture after it's called ms_extract and set the
858 * picture id into gms_graphics_picture.
859 *
860 * The bitmap and other picture stuff can be ignored because it's
861 * the precise same stuff as we already have in picture details
862 * variables. If the ms_extract() fails, we'll carry on regardless,
863 * which may, or may not, result in the ideal picture display.
864 *
865 * One or two non-animated pictures return NULL from ms_extract()
866 * being re-called, so we'll restrict calls to animations only.
867 * And just to be safe, we'll also call only if we're already
868 * holding a bitmap (and we should be; how else could the graphics
869 * animation flag be set?...).
870 */
871 if (gms_graphics_animated && gms_graphics_bitmap)
872 {
873 type8 *bitmap, animated;
874 type16 width, height, palette[GMS_PALETTE_SIZE];
875
876 /* Extract the bitmap into dummy variables. */
877 bitmap = ms_extract (gms_graphics_picture, &width, &height,
878 palette, &animated);
879 }
880
881 /* Set the new picture flag, and start graphics. */
882 gms_graphics_new_picture = TRUE;
883 gms_graphics_start ();
884 }
885 }
886
887
888 /*
889 * gms_graphics_count_colors()
890 *
891 * Analyze an image, and return the usage count of each palette color, and
892 * an overall count of how many colors out of the palette are used. NULL
893 * arguments indicate no interest in the return value.
894 */
895 static void
896 gms_graphics_count_colors (type8 bitmap[], type16 width, type16 height,
897 int *color_count, long color_usage[])
898 {
899 int x, y, count;
900 long usage[GMS_PALETTE_SIZE], index_row;
901 assert (bitmap);
902
903 /*
904 * Traverse the image, counting each pixel usage. For the y iterator,
905 * maintain an index row as an optimization to avoid multiplications in
906 * the loop.
907 */
908 count = 0;
909 memset (usage, 0, sizeof (usage));
910 for (y = 0, index_row = 0; y < height; y++, index_row += width)
911 {
912 for (x = 0; x < width; x++)
913 {
914 long index;
915
916 /* Get the pixel index, and update the count for this color. */
917 index = index_row + x;
918 usage[bitmap[index]]++;
919
920 /* If color usage is now 1, note new color encountered. */
921 if (usage[bitmap[index]] == 1)
922 count++;
923 }
924 }
925
926 if (color_count)
927 *color_count = count;
928
929 if (color_usage)
930 memcpy (color_usage, usage, sizeof (usage));
931 }
932
933
934 /*
935 * gms_graphics_game_to_rgb_color()
936 * gms_graphics_split_color()
937 * gms_graphics_combine_color()
938 * gms_graphics_color_luminance()
939 *
940 * General graphics helper functions, to convert between Magnetic Scrolls
941 * and RGB color representations, and between RGB and Glk glui32 color
942 * representations, and to calculate color luminance.
943 */
944 static void
945 gms_graphics_game_to_rgb_color (type16 color, gms_gammaref_t gamma,
946 gms_rgbref_t rgb_color)
947 {
948 assert (gamma && rgb_color);
949
950 /*
951 * Convert Magnetic Scrolls color, through gamma, into RGB. This splits
952 * the color into components based on the 3-bits used in the game palette,
953 * and gamma-corrects and rescales each to the range 0-255, using the given
954 * correction.
955 */
956 rgb_color->red = gamma->table[(color & 0x700) >> 8];
957 rgb_color->green = gamma->table[(color & 0x070) >> 4];
958 rgb_color->blue = gamma->table[(color & 0x007)];
959 }
960
961 static void
962 gms_graphics_split_color (glui32 color, gms_rgbref_t rgb_color)
963 {
964 assert (rgb_color);
965
966 rgb_color->red = (color >> 16) & 0xff;
967 rgb_color->green = (color >> 8) & 0xff;
968 rgb_color->blue = color & 0xff;
969 }
970
971 static glui32
972 gms_graphics_combine_color (gms_rgbref_t rgb_color)
973 {
974 glui32 color;
975 assert (rgb_color);
976
977 color = (rgb_color->red << 16) | (rgb_color->green << 8) | rgb_color->blue;
978 return color;
979 }
980
981 static int
982 gms_graphics_color_luminance (gms_rgbref_t rgb_color)
983 {
984 static int is_initialized = FALSE;
985 static int weighting = 0;
986
987 long luminance;
988
989 /* On the first call, calculate the overall weighting. */
990 if (!is_initialized)
991 {
992 weighting = GMS_LUMINANCE_WEIGHTS.red + GMS_LUMINANCE_WEIGHTS.green
993 + GMS_LUMINANCE_WEIGHTS.blue;
994
995 is_initialized = TRUE;
996 }
997
998 /* Calculate the luminance and scale back by 1000 to 0-255 before return. */
999 luminance = ((long) rgb_color->red * (long) GMS_LUMINANCE_WEIGHTS.red
1000 + (long) rgb_color->green * (long) GMS_LUMINANCE_WEIGHTS.green
1001 + (long) rgb_color->blue * (long) GMS_LUMINANCE_WEIGHTS.blue);
1002
1003 assert (weighting > 0);
1004 return (int) (luminance / weighting);
1005 }
1006
1007
1008 /*
1009 * gms_graphics_compare_luminance()
1010 * gms_graphics_constrast_variance()
1011 *
1012 * Calculate the contrast variance of the given palette and color usage, at
1013 * the given gamma correction level. Helper functions for automatic gamma
1014 * correction.
1015 */
1016 static int
1017 gms_graphics_compare_luminance (const void *void_first,
1018 const void *void_second)
1019 {
1020 int first = *(int *) void_first;
1021 int second = *(int *) void_second;
1022
1023 return first > second ? 1 : second > first ? -1 : 0;
1024 }
1025
1026 static long
1027 gms_graphics_contrast_variance (type16 palette[],
1028 long color_usage[], gms_gammaref_t gamma)
1029 {
1030 int index, count, has_black, mean;
1031 long sum;
1032 int contrast[GMS_PALETTE_SIZE];
1033 int luminance[GMS_PALETTE_SIZE + 1]; /* Luminance for each color,
1034 plus one extra for black */
1035
1036 /* Calculate the luminance energy of each palette color at this gamma. */
1037 has_black = FALSE;
1038 for (index = 0, count = 0; index < GMS_PALETTE_SIZE; index++)
1039 {
1040 if (color_usage[index] > 0)
1041 {
1042 gms_rgb_t rgb_color;
1043
1044 /*
1045 * Convert the 16-bit base picture color to RGB using the gamma
1046 * currently under consideration. Calculate luminance for this
1047 * color and store in the next available luminance array entry.
1048 */
1049 gms_graphics_game_to_rgb_color (palette[index], gamma, &rgb_color);
1050 luminance[count++] = gms_graphics_color_luminance (&rgb_color);
1051
1052 /* Note if black is present in the palette. */
1053 has_black |= luminance[count - 1] == 0;
1054 }
1055 }
1056
1057 /*
1058 * For best results, we want to anchor contrast calculations to black, so
1059 * if black is not represented in the palette, add it as an extra luminance.
1060 */
1061 if (!has_black)
1062 luminance[count++] = 0;
1063
1064 /* Sort luminance values so that the darkest color is at index 0. */
1065 qsort (luminance, count,
1066 sizeof (*luminance), gms_graphics_compare_luminance);
1067
1068 /*
1069 * Calculate the difference in luminance between adjacent luminances in
1070 * the sorted array, as contrast, and at the same time sum contrasts to
1071 * calculate the mean.
1072 */
1073 sum = 0;
1074 for (index = 0; index < count - 1; index++)
1075 {
1076 contrast[index] = luminance[index + 1] - luminance[index];
1077 sum += contrast[index];
1078 }
1079 mean = sum / (count - 1);
1080
1081 /* Calculate and return the variance in contrasts. */
1082 sum = 0;
1083 for (index = 0; index < count - 1; index++)
1084 sum += (contrast[index] - mean) * (contrast[index] - mean);
1085
1086 return sum / (count - 1);
1087 }
1088
1089
1090 /*
1091 * gms_graphics_equal_contrast_gamma()
1092 *
1093 * Try to find a gamma correction for the given palette and color usage that
1094 * gives relatively equal contrast among the displayed colors.
1095 *
1096 * To do this, we search the gamma tables, computing color luminance for each
1097 * color in the palette given this gamma. From luminances, we then compute
1098 * the contrasts between the colors, and settle on the gamma correction that
1099 * gives the most even and well-distributed picture contrast. We ignore
1100 * colors not used in the palette.
1101 *
1102 * Note that we don't consider how often a palette color is used, only whether
1103 * it's represented, or not. Some weighting might improve things, but the
1104 * simple method seems to work adequately. In practice, as there are only 16
1105 * colors in a palette, most pictures use most colors in a relatively well
1106 * distributed manner. This algorithm probably wouldn't work well on real
1107 * photographs, though.
1108 */
1109 static gms_gammaref_t
1110 gms_graphics_equal_contrast_gamma (type16 palette[], long color_usage[])
1111 {
1112 gms_gammaref_t gamma, result;
1113 long lowest_variance;
1114 assert (palette && color_usage);
1115
1116 result = NULL;
1117 lowest_variance = LONG_MAX;
1118
1119 /* Search the gamma table for the entry with the lowest contrast variance. */
1120 for (gamma = GMS_GAMMA_TABLE; gamma->level; gamma++)
1121 {
1122 long variance;
1123
1124 /* Find the color contrast variance of the palette at this gamma. */
1125 variance = gms_graphics_contrast_variance (palette, color_usage, gamma);
1126
1127 /*
1128 * Compare the variance to the lowest so far, and if it is lower, note
1129 * the gamma entry that produced it as being the current best found.
1130 */
1131 if (variance < lowest_variance)
1132 {
1133 result = gamma;
1134 lowest_variance = variance;
1135 }
1136 }
1137
1138 assert (result);
1139 return result;
1140 }
1141
1142
1143 /*
1144 * gms_graphics_select_gamma()
1145 *
1146 * Select a suitable gamma for the picture, based on the current gamma mode.
1147 *
1148 * The function returns either the linear gamma, a gamma value half way
1149 * between linear and the gamma that gives the most even contrast, or just
1150 * the gamma that gives the most even contrast.
1151 *
1152 * In the normal case, a value half way to the extreme case of making color
1153 * contrast equal for all colors is, subjectively, a reasonable value to use.
1154 * The problem cases are the darkest pictures, and selecting this value
1155 * brightens them while at the same time not making them look overbright or
1156 * too "sunny".
1157 */
1158 static gms_gammaref_t
1159 gms_graphics_select_gamma (type8 bitmap[], type16 width, type16 height,
1160 type16 palette[])
1161 {
1162 static int is_initialized = FALSE;
1163 static gms_gammaref_t linear_gamma = NULL;
1164
1165 long color_usage[GMS_PALETTE_SIZE];
1166 int color_count;
1167 gms_gammaref_t contrast_gamma;
1168
1169 /* On first call, find and cache the uncorrected gamma table entry. */
1170 if (!is_initialized)
1171 {
1172 gms_gammaref_t gamma;
1173
1174 for (gamma = GMS_GAMMA_TABLE; gamma->level; gamma++)
1175 {
1176 if (!gamma->is_corrected)
1177 {
1178 linear_gamma = gamma;
1179 break;
1180 }
1181 }
1182
1183 is_initialized = TRUE;
1184 }
1185 assert (linear_gamma);
1186
1187 /*
1188 * Check to see if automated correction is turned off; if it is, return
1189 * the linear gamma.
1190 */
1191 if (gms_gamma_mode == GAMMA_OFF)
1192 return linear_gamma;
1193
1194 /*
1195 * Get the color usage and count of total colors represented. For a
1196 * degenerate picture with one color or less, return the linear gamma.
1197 */
1198 gms_graphics_count_colors (bitmap, width, height, &color_count, color_usage);
1199 if (color_count <= 1)
1200 return linear_gamma;
1201
1202 /*
1203 * Now calculate a gamma setting to give the most equal contrast across the
1204 * picture colors. We'll return either half this gamma, or all of it.
1205 */
1206 contrast_gamma = gms_graphics_equal_contrast_gamma (palette, color_usage);
1207
1208 /*
1209 * For normal automated correction, return a gamma value half way between
1210 * the linear gamma and the equal contrast gamma.
1211 */
1212 if (gms_gamma_mode == GAMMA_NORMAL)
1213 return linear_gamma + (contrast_gamma - linear_gamma) / 2;
1214
1215 /* Correction must be high; return the equal contrast gamma. */
1216 assert (gms_gamma_mode == GAMMA_HIGH);
1217 return contrast_gamma;
1218 }
1219
1220
1221 /*
1222 * gms_graphics_clear_and_border()
1223 *
1224 * Clear the graphics window, and border and shade the area where the
1225 * picture is going to be rendered. This attempts a small raised effect
1226 * for the picture, in keeping with modern trends.
1227 */
1228 static void
1229 gms_graphics_clear_and_border (winid_t glk_window, int x_offset, int y_offset,
1230 int pixel_size, type16 width, type16 height)
1231 {
1232 glui32 background, fade_color, shading_color;
1233 gms_rgb_t rgb_background, rgb_border, rgb_fade;
1234 int index;
1235 assert (glk_window);
1236
1237 /*
1238 * Try to detect the background color of the main window, by getting the
1239 * background for Normal style (Glk offers no way to directly get a window's
1240 * background color). If we can get it, we'll match the graphics window
1241 * background to it. If we can't, we'll default the color to white.
1242 */
1243 if (!glk_style_measure (gms_main_window,
1244 style_Normal, stylehint_BackColor, &background))
1245 {
1246 /*
1247 * Unable to get the main window background, so assume, and default
1248 * graphics to white.
1249 */
1250 background = GMS_GRAPHICS_DEFAULT_BACKGROUND;
1251 }
1252
1253 /*
1254 * Set the graphics window background to match the main window background,
1255 * as best as we can tell, and clear the window.
1256 */
1257 glk_window_set_background_color (glk_window, background);
1258 glk_window_clear (glk_window);
1259
1260 /*
1261 * For very small pictures, just border them, but don't try and do any
1262 * shading. Failing this check is probably highly unlikely.
1263 */
1264 if (width < 2 * GMS_GRAPHICS_SHADE_STEPS
1265 || height < 2 * GMS_GRAPHICS_SHADE_STEPS)
1266 {
1267 /* Paint a rectangle bigger than the picture by border pixels. */
1268 glk_window_fill_rect (glk_window,
1269 GMS_GRAPHICS_BORDER_COLOR,
1270 x_offset - GMS_GRAPHICS_BORDER,
1271 y_offset - GMS_GRAPHICS_BORDER,
1272 width * pixel_size + GMS_GRAPHICS_BORDER * 2,
1273 height * pixel_size + GMS_GRAPHICS_BORDER * 2);
1274 return;
1275 }
1276
1277 /*
1278 * Paint a rectangle bigger than the picture by border pixels all round,
1279 * and with additional shading pixels right and below. Some of these
1280 * shading pixels are later overwritten by the fading loop below. The
1281 * picture will sit over this rectangle.
1282 */
1283 glk_window_fill_rect (glk_window,
1284 GMS_GRAPHICS_BORDER_COLOR,
1285 x_offset - GMS_GRAPHICS_BORDER,
1286 y_offset - GMS_GRAPHICS_BORDER,
1287 width * pixel_size + GMS_GRAPHICS_BORDER * 2
1288 + GMS_GRAPHICS_SHADING,
1289 height * pixel_size + GMS_GRAPHICS_BORDER * 2
1290 + GMS_GRAPHICS_SHADING);
1291
1292 /*
1293 * Split the main window background color and the border color into
1294 * components.
1295 */
1296 gms_graphics_split_color (background, &rgb_background);
1297 gms_graphics_split_color (GMS_GRAPHICS_BORDER_COLOR, &rgb_border);
1298
1299 /*
1300 * Generate the incremental color to use in fade steps. Here we're
1301 * assuming that the border is always darker than the main window
1302 * background (currently valid, as we're using black).
1303 */
1304 rgb_fade.red = (rgb_background.red - rgb_border.red)
1305 / GMS_GRAPHICS_SHADE_STEPS;
1306 rgb_fade.green = (rgb_background.green - rgb_border.green)
1307 / GMS_GRAPHICS_SHADE_STEPS;
1308 rgb_fade.blue = (rgb_background.blue - rgb_border.blue)
1309 / GMS_GRAPHICS_SHADE_STEPS;
1310
1311 /* Combine RGB fade into a single incremental Glk color. */
1312 fade_color = gms_graphics_combine_color (&rgb_fade);
1313
1314 /* Fade in edge, from background to border, shading in stages. */
1315 shading_color = background;
1316 for (index = 0; index < GMS_GRAPHICS_SHADE_STEPS; index++)
1317 {
1318 /* Shade the two border areas with this color. */
1319 glk_window_fill_rect (glk_window, shading_color,
1320 x_offset + width * pixel_size
1321 + GMS_GRAPHICS_BORDER,
1322 y_offset + index - GMS_GRAPHICS_BORDER,
1323 GMS_GRAPHICS_SHADING, 1);
1324 glk_window_fill_rect (glk_window, shading_color,
1325 x_offset + index - GMS_GRAPHICS_BORDER,
1326 y_offset + height * pixel_size
1327 + GMS_GRAPHICS_BORDER,
1328 1, GMS_GRAPHICS_SHADING);
1329
1330 /* Update the shading color for the fade next iteration. */
1331 shading_color -= fade_color;
1332 }
1333 }
1334
1335
1336 /*
1337 * gms_graphics_convert_palette()
1338 *
1339 * Convert a Magnetic Scrolls color palette to a Glk one, using the given
1340 * gamma corrections.
1341 */
1342 static void
1343 gms_graphics_convert_palette (type16 ms_palette[], gms_gammaref_t gamma,
1344 glui32 glk_palette[])
1345 {
1346 int index;
1347 assert (ms_palette && gamma && glk_palette);
1348
1349 for (index = 0; index < GMS_PALETTE_SIZE; index++)
1350 {
1351 gms_rgb_t rgb_color;
1352
1353 /*
1354 * Convert the 16-bit base picture color through gamma to a 32-bit
1355 * RGB color, and combine into a Glk color and store in the Glk palette.
1356 */
1357 gms_graphics_game_to_rgb_color (ms_palette[index], gamma, &rgb_color);
1358 glk_palette[index] = gms_graphics_combine_color (&rgb_color);
1359 }
1360 }
1361
1362
1363 /*
1364 * gms_graphics_position_picture()
1365 *
1366 * Given a picture width and height, return the x and y offsets to center
1367 * this picture in the current graphics window.
1368 */
1369 static void
1370 gms_graphics_position_picture (winid_t glk_window,
1371 int pixel_size, type16 width, type16 height,
1372 int *x_offset, int *y_offset)
1373 {
1374 glui32 window_width, window_height;
1375 assert (glk_window && x_offset && y_offset);
1376
1377 /* Measure the current graphics window dimensions. */
1378 glk_window_get_size (glk_window, &window_width, &window_height);
1379
1380 /*
1381 * Calculate and return an x and y offset to use on point plotting, so that
1382 * the image centers inside the graphical window.
1383 */
1384 *x_offset = ((int) window_width - width * pixel_size) / 2;
1385 *y_offset = ((int) window_height - height * pixel_size) / 2;
1386 }
1387
1388
1389 /*
1390 * gms_graphics_apply_animation_frame()
1391 *
1392 * Apply a single animation frame to the given off-screen image buffer, using
1393 * the frame bitmap, width, height and mask, the off-screen buffer, and the
1394 * width and height of the main picture.
1395 *
1396 * Note that 'mask' may be NULL, implying that no frame pixel is transparent.
1397 */
1398 static void
1399 gms_graphics_apply_animation_frame (type8 bitmap[],
1400 type16 frame_width, type16 frame_height,
1401 type8 mask[], int frame_x, int frame_y,
1402 type8 off_screen[], type16 width,
1403 type16 height)
1404 {
1405 int mask_width, x, y;
1406 type8 mask_hibit;
1407 long frame_row, buffer_row, mask_row;
1408 assert (bitmap && off_screen);
1409
1410 /*
1411 * It turns out that the mask isn't quite as described in defs.h, and thanks
1412 * to Torbjorn Andersson and his Gtk port of Magnetic for illuminating this.
1413 * The mask is made up of lines of 16-bit words, so the mask width is always
1414 * even. Here we'll calculate the real width of a mask, and also set a high
1415 * bit for later on.
1416 */
1417 mask_width = (((frame_width - 1) / CHAR_BIT) + 2) & (~1);
1418 mask_hibit = 1 << (CHAR_BIT - 1);
1419
1420 /*
1421 * Initialize row index components; these are optimizations to avoid the
1422 * need for multiplications in the frame iteration loop.
1423 */
1424 frame_row = 0;
1425 buffer_row = frame_y * width;
1426 mask_row = 0;
1427
1428 /*
1429 * Iterate over each frame row, clipping where y lies outside the main
1430 * picture area.
1431 */
1432 for (y = 0; y < frame_height; y++)
1433 {
1434 /* Clip if y is outside the main picture area. */
1435 if (y + frame_y < 0 || y + frame_y >= height)
1436 {
1437 /* Update optimization variables as if not clipped. */
1438 frame_row += frame_width;
1439 buffer_row += width;
1440 mask_row += mask_width;
1441 continue;
1442 }
1443
1444 /* Iterate over each frame column, clipping again. */
1445 for (x = 0; x < frame_width; x++)
1446 {
1447 long frame_index, buffer_index;
1448
1449 /* Clip if x is outside the main picture area. */
1450 if (x + frame_x < 0 || x + frame_x >= width)
1451 continue;
1452
1453 /*
1454 * If there's a mask, check the bit associated with this x,y, and
1455 * ignore any transparent pixels.
1456 */
1457 if (mask)
1458 {
1459 type8 mask_byte;
1460
1461 /* Isolate the mask byte, and test the transparency bit. */
1462 mask_byte = mask[mask_row + (x / CHAR_BIT)];
1463 if ((mask_byte & (mask_hibit >> (x % CHAR_BIT))) != 0)
1464 continue;
1465 }
1466
1467 /*
1468 * Calculate indexes for this pixel into the frame, and into the
1469 * main off-screen buffer, and transfer the frame pixel into the
1470 * off-screen buffer.
1471 */
1472 frame_index = frame_row + x;
1473 buffer_index = buffer_row + x + frame_x;
1474 off_screen[buffer_index] = bitmap[frame_index];
1475 }
1476
1477 /* Update row index components on change of y. */
1478 frame_row += frame_width;
1479 buffer_row += width;
1480 mask_row += mask_width;
1481 }
1482 }
1483
1484
1485 /*
1486 * gms_graphics_animate()
1487 *
1488 * This function finds and applies the next set of animation frames to the
1489 * given off-screen image buffer. It's handed the width and height of the
1490 * main picture, and the off-screen buffer.
1491 *
1492 * It returns FALSE if at the end of animations, TRUE if more animations
1493 * remain.
1494 */
1495 static int
1496 gms_graphics_animate (type8 off_screen[], type16 width, type16 height)
1497 {
1498 struct ms_position *positions;
1499 type16 count;
1500 type8 status;
1501 int frame;
1502 assert (off_screen);
1503
1504 /* Search for more animation frames, and return zero if none. */
1505 status = ms_animate (&positions, &count);
1506 if (status == 0)
1507 return FALSE;
1508
1509 /* Apply each animation frame to the off-screen buffer. */
1510 for (frame = 0; frame < count; frame++)
1511 {
1512 type8 *bitmap, *mask;
1513 type16 frame_width, frame_height;
1514
1515 /*
1516 * Get the bitmap and other details for this frame. If we can't get
1517 * this animation frame, skip it and see if any others are available.
1518 */
1519 bitmap = ms_get_anim_frame (positions[frame].number,
1520 &frame_width, &frame_height, &mask);
1521 if (bitmap)
1522 {
1523 gms_graphics_apply_animation_frame (bitmap,
1524 frame_width, frame_height, mask,
1525 positions[frame].x,
1526 positions[frame].y,
1527 off_screen, width, height);
1528 }
1529 }
1530
1531 /* Return TRUE since more animation frames remain. */
1532 return TRUE;
1533 }
1534
1535
1536 /*
1537 * gms_graphics_is_vertex()
1538 *
1539 * Given a point, return TRUE if that point is the vertex of a fillable
1540 * region. This is a helper function for layering pictures. When assign-
1541 * ing layers, we want to weight the colors that have the most complex
1542 * shapes, or the largest count of isolated areas, heavier than simpler
1543 * areas.
1544 *
1545 * By painting the colors with the largest number of isolated areas or
1546 * the most complex shapes first, we help to minimize the number of fill
1547 * regions needed to render the complete picture.
1548 */
1549 static int
1550 gms_graphics_is_vertex (type8 off_screen[], type16 width, type16 height,
1551 int x, int y)
1552 {
1553 type8 pixel;
1554 int above, below, left, right;
1555 long index_row;
1556 assert (off_screen);
1557
1558 /* Use an index row to cut down on multiplications. */
1559 index_row = y * width;
1560
1561 /* Find the color of the reference pixel. */
1562 pixel = off_screen[index_row + x];
1563 assert (pixel < GMS_PALETTE_SIZE);
1564
1565 /*
1566 * Detect differences between the reference pixel and its upper, lower, left
1567 * and right neighbors. Mark as different if the neighbor doesn't exist,
1568 * that is, at the edge of the picture.
1569 */
1570 above = (y == 0 || off_screen[index_row - width + x] != pixel);
1571 below = (y == height - 1 || off_screen[index_row + width + x] != pixel);
1572 left = (x == 0 || off_screen[index_row + x - 1] != pixel);
1573 right = (x == width - 1 || off_screen[index_row + x + 1] != pixel);
1574
1575 /*
1576 * Return TRUE if this pixel lies at the vertex of a rectangular, fillable,
1577 * area. That is, if two adjacent neighbors aren't the same color (or if
1578 * absent -- at the edge of the picture).
1579 */
1580 return ((above || below) && (left || right));
1581 }
1582
1583
1584 /*
1585 * gms_graphics_compare_layering_inverted()
1586 * gms_graphics_assign_layers()
1587 *
1588 * Given two sets of image bitmaps, and a palette, this function will
1589 * assign layers palette colors.
1590 *
1591 * Layers are assigned by first counting the number of vertices in the
1592 * color plane, to get a measure of the complexity of shapes displayed in
1593 * this color, and also the raw number of times each palette color is
1594 * used. This is then sorted, so that layers are assigned to colors, with
1595 * the lowest layer being the color with the most complex shapes, and
1596 * within this (or where the count of vertices is zero, as it could be
1597 * in some animation frames) the most used color.
1598 *
1599 * The function compares pixels in the two image bitmaps given, these
1600 * being the off-screen and on-screen buffers, and generates counts only
1601 * where these bitmaps differ. This ensures that only pixels not yet
1602 * painted are included in layering.
1603 *
1604 * As well as assigning layers, this function returns a set of layer usage
1605 * flags, to help the rendering loop to terminate as early as possible.
1606 *
1607 * By painting lower layers first, the paint can take in larger areas if
1608 * it's permitted to include not-yet-validated higher levels. This helps
1609 * minimize the amount of Glk areas fills needed to render a picture.
1610 */
1611 typedef struct {
1612 long complexity; /* Count of vertices for this color. */
1613 long usage; /* Color usage count. */
1614 int color; /* Color index into palette. */
1615 } gms_layering_t;
1616
1617 static int
1618 gms_graphics_compare_layering_inverted (const void *void_first,
1619 const void *void_second)
1620 {
1621 gms_layering_t * first = (gms_layering_t *) void_first;
1622 gms_layering_t * second = (gms_layering_t *) void_second;
1623
1624 /*
1625 * Order by complexity first, then by usage, putting largest first. Some
1626 * colors may have no vertices at all when doing animation frames, but
1627 * rendering optimization relies on the first layer that contains no areas
1628 * to fill halting the rendering loop. So it's important here that we order
1629 * indexes so that colors that render complex shapes come first, non-empty,
1630 * but simpler shaped colors next, and finally all genuinely empty layers.
1631 */
1632 return second->complexity > first->complexity ? 1 :
1633 first->complexity > second->complexity ? -1 :
1634 second->usage > first->usage ? 1 :
1635 first->usage > second->usage ? -1 : 0;
1636 }
1637
1638 static void
1639 gms_graphics_assign_layers (type8 off_screen[], type8 on_screen[],
1640 type16 width, type16 height,
1641 int layers[], long layer_usage[])
1642 {
1643 int index, x, y;
1644 long index_row;
1645 gms_layering_t layering[GMS_PALETTE_SIZE];
1646 assert (off_screen && on_screen && layers && layer_usage);
1647
1648 /* Clear initial complexity and usage counts, and set initial colors. */
1649 for (index = 0; index < GMS_PALETTE_SIZE; index++)
1650 {
1651 layering[index].complexity = 0;
1652 layering[index].usage = 0;
1653 layering[index].color = index;
1654 }
1655
1656 /*
1657 * Traverse the image, counting vertices and pixel usage where the pixels
1658 * differ between the off-screen and on-screen buffers. Optimize by
1659 * maintaining an index row to avoid multiplications.
1660 */
1661 for (y = 0, index_row = 0; y < height; y++, index_row += width)
1662 {
1663 for (x = 0; x < width; x++)
1664 {
1665 long index;
1666
1667 /*
1668 * Get the index for this pixel, and update complexity and usage
1669 * if off-screen and on-screen pixels differ.
1670 */
1671 index = index_row + x;
1672 if (on_screen[index] != off_screen[index])
1673 {
1674 if (gms_graphics_is_vertex (off_screen, width, height, x, y))
1675 layering[off_screen[index]].complexity++;
1676
1677 layering[off_screen[index]].usage++;
1678 }
1679 }
1680 }
1681
1682 /*
1683 * Sort counts to form color indexes. The primary sort is on the shape
1684 * complexity, and within this, on color usage.
1685 */
1686 qsort (layering, GMS_PALETTE_SIZE,
1687 sizeof (*layering), gms_graphics_compare_layering_inverted);
1688
1689 /*
1690 * Assign a layer to each palette color, and also return the layer usage
1691 * for each layer.
1692 */
1693 for (index = 0; index < GMS_PALETTE_SIZE; index++)
1694 {
1695 layers[layering[index].color] = index;
1696 layer_usage[index] = layering[index].usage;
1697 }
1698 }
1699
1700
1701 /*
1702 * gms_graphics_paint_region()
1703 *
1704 * This is a partially optimized point plot. Given a point in the graphics
1705 * bitmap, it tries to extend the point to a color region, and fill a number
1706 * of pixels in a single Glk rectangle fill. The goal here is to reduce the
1707 * number of Glk rectangle fills, which tend to be extremely inefficient
1708 * operations for generalized point plotting.
1709 *
1710 * The extension works in image layers; each palette color is assigned a
1711 * layer, and we paint each layer individually, starting at the lowest. So,
1712 * the region is free to fill any invalidated pixel in a higher layer, and
1713 * all pixels, invalidated or already validated, in the same layer. In
1714 * practice, it is good enough to look for either invalidated pixels or pixels
1715 * in the same layer, and construct a region as large as possible from these,
1716 * then on marking points as validated, mark only those in the same layer as
1717 * the initial point.
1718 *
1719 * The optimization here is not the best possible, but is reasonable. What
1720 * we do is to try and stretch the region horizontally first, then vertically.
1721 * In practice, we might find larger areas by stretching vertically and then
1722 * horizontally, or by stretching both dimensions at the same time. In
1723 * mitigation, the number of colors in a picture is small (16), and the
1724 * aspect ratio of pictures makes them generally wider than they are tall.
1725 *
1726 * Once we've found the region, we render it with a single Glk rectangle fill,
1727 * and mark all the pixels in this region that match the layer of the initial
1728 * given point as validated.
1729 */
1730 static void
1731 gms_graphics_paint_region (winid_t glk_window, glui32 palette[], int layers[],
1732 type8 off_screen[], type8 on_screen[],
1733 int x, int y, int x_offset, int y_offset,
1734 int pixel_size, type16 width, type16 height)
1735 {
1736 type8 pixel;
1737 int layer, x_min, x_max, y_min, y_max, x_index, y_index;
1738 long index_row;
1739 assert (glk_window && palette && layers && off_screen && on_screen);
1740
1741 /* Find the color and layer for the initial pixel. */
1742 pixel = off_screen[y * width + x];
1743 layer = layers[pixel];
1744 assert (pixel < GMS_PALETTE_SIZE);
1745
1746 /*
1747 * Start by finding the extent to which we can pull the x coordinate and
1748 * still find either invalidated pixels, or pixels in this layer.
1749 *
1750 * Use an index row to remove multiplications from the loops.
1751 */
1752 index_row = y * width;
1753 for (x_min = x; x_min - 1 >= 0; x_min--)
1754 {
1755 long index = index_row + x_min - 1;
1756
1757 if (on_screen[index] == off_screen[index]
1758 && layers[off_screen[index]] != layer)
1759 break;
1760 }
1761 for (x_max = x; x_max + 1 < width; x_max++)
1762 {
1763 long index = index_row + x_max + 1;
1764
1765 if (on_screen[index] == off_screen[index]
1766 && layers[off_screen[index]] != layer)
1767 break;
1768 }
1769
1770 /*
1771 * Now try to stretch the height of the region, by extending the y
1772 * coordinate as much as possible too. Again, we're looking for pixels
1773 * that are invalidated or ones in the same layer. We need to check
1774 * across the full width of the current region.
1775 *
1776 * As above, an index row removes multiplications from the loops.
1777 */
1778 for (y_min = y, index_row = (y - 1) * width;
1779 y_min - 1 >= 0; y_min--, index_row -= width)
1780 {
1781 for (x_index = x_min; x_index <= x_max; x_index++)
1782 {
1783 long index = index_row + x_index;
1784
1785 if (on_screen[index] == off_screen[index]
1786 && layers[off_screen[index]] != layer)
1787 goto break_y_min;
1788 }
1789 }
1790 break_y_min:
1791
1792 for (y_max = y, index_row = (y + 1) * width;
1793 y_max + 1 < height; y_max++, index_row += width)
1794 {
1795 for (x_index = x_min; x_index <= x_max; x_index++)
1796 {
1797 long index = index_row + x_index;
1798
1799 if (on_screen[index] == off_screen[index]
1800 && layers[off_screen[index]] != layer)
1801 goto break_y_max;
1802 }
1803 }
1804 break_y_max:
1805
1806 /* Fill the region using Glk's rectangle fill. */
1807 glk_window_fill_rect (glk_window, palette[pixel],
1808 x_min * pixel_size + x_offset,
1809 y_min * pixel_size + y_offset,
1810 (x_max - x_min + 1) * pixel_size,
1811 (y_max - y_min + 1) * pixel_size);
1812
1813 /*
1814 * Validate each pixel in the reference layer that was rendered by the
1815 * rectangle fill. We don't validate pixels that are not in this layer
1816 * (and are by definition in higher layers, as we've validated all lower
1817 * layers), since although we colored them, we did it for optimization
1818 * reasons, and they're not yet colored correctly.
1819 *
1820 * Maintain an index row as an optimization to avoid multiplication.
1821 */
1822 index_row = y_min * width;
1823 for (y_index = y_min; y_index <= y_max; y_index++)
1824 {
1825 for (x_index = x_min; x_index <= x_max; x_index++)
1826 {
1827 long index;
1828
1829 /*
1830 * Get the index for x_index,y_index. If the layers match, update
1831 * the on-screen buffer.
1832 */
1833 index = index_row + x_index;
1834 if (layers[off_screen[index]] == layer)
1835 {
1836 assert (off_screen[index] == pixel);
1837 on_screen[index] = off_screen[index];
1838 }
1839 }
1840
1841 /* Update row index component on change of y. */
1842 index_row += width;
1843 }
1844 }
1845
1846 #ifdef GARGLK
1847 static void
1848 gms_graphics_paint_everything (winid_t glk_window, glui32 palette[],
1849 type8 off_screen[], int x_offset,
1850 int y_offset, type16 width, type16 height)
1851 {
1852 type8 pixel; /* Reference pixel color */
1853 int x, y;
1854
1855 for (y = 0; y < height; y++)
1856 {
1857 for (x = 0; x < width; x++)
1858 {
1859 pixel = off_screen[y * width + x];
1860 glk_window_fill_rect (glk_window,
1861 palette[pixel],
1862 x * gms_graphics_pixel + x_offset,
1863 y * gms_graphics_pixel + y_offset,
1864 gms_graphics_pixel, gms_graphics_pixel);
1865 }
1866 }
1867 }
1868 #endif
1869
1870 /*
1871 * gms_graphics_timeout()
1872 *
1873 * This is a background function, called on Glk timeouts. Its job is to
1874 * repaint some of the current graphics image. On successive calls, it
1875 * does a part of the repaint, then yields to other processing. This is
1876 * useful since the Glk primitive to plot points in graphical windows is
1877 * extremely slow; this way, the repaint doesn't block game play.
1878 *
1879 * The function should be called on Glk timeout events. When the repaint
1880 * is complete, the function will turn off Glk timers.
1881 *
1882 * The function uses double-buffering to track how much of the graphics
1883 * buffer has been rendered. This helps to minimize the amount of point
1884 * plots required, as only the differences between the two buffers need
1885 * to be rendered.
1886 */
1887 static void
1888 gms_graphics_timeout (void)
1889 {
1890 static glui32 palette[GMS_PALETTE_SIZE]; /* Precomputed Glk palette */
1891 static int layers[GMS_PALETTE_SIZE]; /* Assigned image layers */
1892 static long layer_usage[GMS_PALETTE_SIZE]; /* Image layer occupancies */
1893
1894 static int deferred_repaint = FALSE; /* Local delayed repaint flag */
1895 static int ignore_counter; /* Count of calls ignored */
1896
1897 static int x_offset, y_offset; /* Point plot offsets */
1898 static int yield_counter; /* Yields in rendering */
1899 static int saved_layer; /* Saved current layer */
1900 static int saved_x, saved_y; /* Saved x,y coord */
1901
1902 static int total_regions; /* Debug statistic */
1903
1904 type8 *on_screen; /* On-screen image buffer */
1905 type8 *off_screen; /* Off-screen image buffer */
1906 long picture_size; /* Picture size in pixels */
1907 int layer; /* Image layer iterator */
1908 int x, y; /* Image iterators */
1909 int regions; /* Count of regions painted */
1910
1911 /* Ignore the call if the current graphics state is inactive. */
1912 if (!gms_graphics_active)
1913 return;
1914 assert (gms_graphics_window);
1915
1916 /*
1917 * On detecting a repaint request, note the flag in a local static variable,
1918 * then set up a graphics delay to wait until, hopefully, the resize, if
1919 * that's what caused it, is complete, and return. This makes resizing the
1920 * window a lot smoother, since it prevents unnecessary region paints where
1921 * we are receiving consecutive Glk arrange or redraw events.
1922 */
1923 if (gms_graphics_repaint)
1924 {
1925 deferred_repaint = TRUE;
1926 gms_graphics_repaint = FALSE;
1927 ignore_counter = GMS_GRAPHICS_REPAINT_WAIT - 1;
1928 return;
1929 }
1930
1931 /*
1932 * If asked to ignore a given number of calls, decrement the ignore counter
1933 * and return having done nothing more. This lets us delay graphics
1934 * operations by a number of timeouts, providing animation timing and
1935 * partial protection from resize event "storms".
1936 *
1937 * Note -- to wait for N timeouts, set the count of timeouts to be ignored
1938 * to N-1.
1939 */
1940 assert (ignore_counter >= 0);
1941 if (ignore_counter > 0)
1942 {
1943 ignore_counter--;
1944 return;
1945 }
1946
1947 /* Calculate the picture size, and synchronize screen buffer pointers. */
1948 picture_size = gms_graphics_width * gms_graphics_height;
1949 off_screen = gms_graphics_off_screen;
1950 on_screen = gms_graphics_on_screen;
1951
1952 /*
1953 * If we received a new picture, set up the local static variables for that
1954 * picture -- decide on gamma correction, convert the color palette, and
1955 * initialize the off_screen buffer to be the base picture.
1956 */
1957 if (gms_graphics_new_picture)
1958 {
1959 /* Initialize the off_screen buffer to be a copy of the base picture. */
1960 free (off_screen);
1961 off_screen = gms_malloc (picture_size * sizeof (*off_screen));
1962 memcpy (off_screen, gms_graphics_bitmap,
1963 picture_size * sizeof (*off_screen));
1964
1965 /* Note the buffer for freeing on cleanup. */
1966 gms_graphics_off_screen = off_screen;
1967
1968 /*
1969 * If the picture is animated, apply the first animation frames now.
1970 * This is important, since they form an intrinsic part of the first
1971 * displayed image (in type2 animation cases, perhaps _all_ of the
1972 * first displayed image).
1973 */
1974 if (gms_graphics_animated)
1975 {
1976 gms_graphics_animate (off_screen,
1977 gms_graphics_width, gms_graphics_height);
1978 }
1979
1980 /*
1981 * Select a suitable gamma for the picture, taking care to use the
1982 * off-screen buffer.
1983 */
1984 gms_graphics_current_gamma =
1985 gms_graphics_select_gamma (off_screen,
1986 gms_graphics_width,
1987 gms_graphics_height,
1988 gms_graphics_palette);
1989
1990 /*
1991 * Pre-convert all the picture palette colors into their corresponding
1992 * Glk colors.
1993 */
1994 gms_graphics_convert_palette (gms_graphics_palette,
1995 gms_graphics_current_gamma, palette);
1996
1997 /* Save the color count for possible queries later. */
1998 gms_graphics_count_colors (off_screen,
1999 gms_graphics_width, gms_graphics_height,
2000 &gms_graphics_color_count, NULL);
2001 }
2002
2003 /*
2004 * For a new picture, or a repaint of a prior one, calculate new values for
2005 * the x and y offsets used to draw image points, and set the on-screen
2006 * buffer to an unused pixel value, in effect invalidating all on-screen
2007 * data. Also, reset the saved image scan coordinates so that we scan for
2008 * unpainted pixels from top left starting at layer zero, and clear the
2009 * graphics window.
2010 */
2011 if (gms_graphics_new_picture || deferred_repaint)
2012 {
2013 /*
2014 * Calculate the x and y offset to center the picture in the graphics
2015 * window.
2016 */
2017 gms_graphics_position_picture (gms_graphics_window,
2018 gms_graphics_pixel,
2019 gms_graphics_width, gms_graphics_height,
2020 &x_offset, &y_offset);
2021
2022 /*
2023 * Reset all on-screen pixels to an unused value, guaranteed not to
2024 * match any in a real picture. This forces all pixels to be repainted
2025 * on a buffer/on-screen comparison.
2026 */
2027 free (on_screen);
2028 on_screen = gms_malloc (picture_size * sizeof (*on_screen));
2029 memset (on_screen, GMS_GRAPHICS_UNUSED_PIXEL,
2030 picture_size * sizeof (*on_screen));
2031
2032 /* Note the buffer for freeing on cleanup. */
2033 gms_graphics_on_screen = on_screen;
2034
2035 /*
2036 * Assign new layers to the current image. This sorts colors by usage
2037 * and puts the most used colors in the lower layers. It also hands us
2038 * a count of pixels in each layer, useful for knowing when to stop
2039 * scanning for layers in the rendering loop.
2040 */
2041 #ifndef GARGLK
2042 gms_graphics_assign_layers (off_screen, on_screen,
2043 gms_graphics_width, gms_graphics_height,
2044 layers, layer_usage);
2045 #endif
2046
2047 /* Clear the graphics window. */
2048 gms_graphics_clear_and_border (gms_graphics_window,
2049 x_offset, y_offset,
2050 gms_graphics_pixel,
2051 gms_graphics_width, gms_graphics_height);
2052
2053 /* Start a fresh picture rendering pass. */
2054 yield_counter = 0;
2055 saved_layer = 0;
2056 saved_x = 0;
2057 saved_y = 0;
2058 total_regions = 0;
2059
2060 /* Clear the new picture and deferred repaint flags. */
2061 gms_graphics_new_picture = FALSE;
2062 deferred_repaint = FALSE;
2063 }
2064
2065 #ifndef GARGLK
2066 /*
2067 * Make a portion of an image pass, from lower to higher image layers,
2068 * scanning for invalidated pixels that are in the current image layer we
2069 * are painting. Each invalidated pixel gives rise to a region paint,
2070 * which equates to one Glk rectangle fill.
2071 *
2072 * When the limit on regions is reached, save the current image pass layer
2073 * and coordinates, and yield control to the main game playing code by
2074 * returning. On the next call, pick up where we left off.
2075 *
2076 * As an optimization, we can leave the loop on the first empty layer we
2077 * encounter. Since layers are ordered by complexity and color usage, all
2078 * layers higher than the first unused one will also be empty, so we don't
2079 * need to scan them.
2080 */
2081 regions = 0;
2082 for (layer = saved_layer;
2083 layer < GMS_PALETTE_SIZE && layer_usage[layer] > 0; layer++)
2084 {
2085 long index_row;
2086
2087 /*
2088 * As an optimization to avoid multiplications in the loop, maintain a
2089 * separate index row.
2090 */
2091 index_row = saved_y * gms_graphics_width;
2092 for (y = saved_y; y < gms_graphics_height; y++)
2093 {
2094 for (x = saved_x; x < gms_graphics_width; x++)
2095 {
2096 long index;
2097
2098 /* Get the index for this pixel. */
2099 index = index_row + x;
2100 assert (index < picture_size * sizeof (*off_screen));
2101
2102 /*
2103 * Ignore pixels not in the current layer, and pixels not
2104 * currently invalid (that is, ones whose on-screen represen-
2105 * tation matches the off-screen buffer).
2106 */
2107 if (layers[off_screen[index]] == layer
2108 && on_screen[index] != off_screen[index])
2109 {
2110 /*
2111 * Rather than painting just one pixel, here we try to
2112 * paint the maximal region we can for the layer of the
2113 * given pixel.
2114 */
2115 gms_graphics_paint_region (gms_graphics_window,
2116 palette, layers,
2117 off_screen, on_screen,
2118 x, y, x_offset, y_offset,
2119 gms_graphics_pixel,
2120 gms_graphics_width,
2121 gms_graphics_height);
2122
2123 /*
2124 * Increment count of regions handled, and yield, by
2125 * returning, if the limit on paint regions is reached.
2126 * Before returning, save the current layer and scan
2127 * coordinates, so we can pick up here on the next call.
2128 */
2129 regions++;
2130 if (regions >= GMS_REPAINT_LIMIT)
2131 {
2132 yield_counter++;
2133 saved_layer = layer;
2134 saved_x = x;
2135 saved_y = y;
2136 total_regions += regions;
2137 return;
2138 }
2139 }
2140 }
2141
2142 /* Reset the saved x coordinate on y increment. */
2143 saved_x = 0;
2144
2145 /* Update the index row on change of y. */
2146 index_row += gms_graphics_width;
2147 }
2148
2149 /* Reset the saved y coordinate on layer change. */
2150 saved_y = 0;
2151 }
2152
2153 /*
2154 * If we reach this point, then we didn't get to the limit on regions
2155 * painted on this pass. In that case, we've finished rendering the
2156 * image.
2157 */
2158 assert (regions < GMS_REPAINT_LIMIT);
2159 total_regions += regions;
2160
2161 #else
2162 gms_graphics_paint_everything (gms_graphics_window, palette, off_screen,
2163 x_offset, y_offset,
2164 gms_graphics_width, gms_graphics_height);
2165 #endif
2166
2167 /*
2168 * If animated, and if animations are enabled, handle further animation
2169 * frames, if any.
2170 */
2171 if (gms_animation_enabled && gms_graphics_animated)
2172 {
2173 int more_animation;
2174
2175 /*
2176 * Reset the off-screen buffer to a copy of the base picture. This is
2177 * the correct state for applying animation frames.
2178 */
2179 memcpy (off_screen, gms_graphics_bitmap,
2180 picture_size * sizeof (*off_screen));
2181
2182 /*
2183 * Apply any further animations. If none, then stop the graphics
2184 * "thread" and return. There's no more to be done until something
2185 * restarts us.
2186 */
2187 more_animation = gms_graphics_animate (off_screen,
2188 gms_graphics_width,
2189 gms_graphics_height);
2190 if (!more_animation)
2191 {
2192 /*
2193 * There's one extra wrinkle here. The base picture we've just put
2194 * into the off-screen buffer isn't really complete (and for type2
2195 * animations, might be pure garbage), so if we happen to get a
2196 * repaint after an animation has ended, the off-screen data we'll
2197 * be painting could well look wrong.
2198 *
2199 * So... here we want to set the off-screen buffer to contain the
2200 * final animation frame. Fortunately, we still have it in the
2201 * on-screen buffer.
2202 */
2203 memcpy (off_screen, on_screen, picture_size * sizeof (*off_screen));
2204 gms_graphics_stop ();
2205 return;
2206 }
2207
2208 /*
2209 * Re-assign layers based on animation changes to the off-screen
2210 * buffer.
2211 */
2212 #ifndef GARGLK
2213 gms_graphics_assign_layers (off_screen, on_screen,
2214 gms_graphics_width, gms_graphics_height,
2215 layers, layer_usage);
2216 #endif
2217
2218 /*
2219 * Set up an animation wait, adjusted here by the number of times we
2220 * had to yield while rendering, as we're now that late with animations,
2221 * and capped at zero, as we can't do anything to compensate for being
2222 * too late. In practice, we're running too close to the edge to have
2223 * much of an effect here, but nevertheless...
2224 */
2225 ignore_counter = GMS_GRAPHICS_ANIMATION_WAIT - 1;
2226 if (yield_counter > ignore_counter)
2227 ignore_counter = 0;
2228 else
2229 ignore_counter -= yield_counter;
2230
2231 /* Start a fresh picture rendering pass. */
2232 yield_counter = 0;
2233 saved_layer = 0;
2234 saved_x = 0;
2235 saved_y = 0;
2236 total_regions = 0;
2237 }
2238 else
2239 {
2240 /*
2241 * Not an animated picture, so just stop graphics, as again, there's
2242 * no more to be done until something restarts us.
2243 */
2244 gms_graphics_stop ();
2245 }
2246 }
2247
2248
2249 /*
2250 * ms_showpic()
2251 *
2252 * Called by the main interpreter when it wants us to display a picture.
2253 * The function gets the picture bitmap, palette, and dimensions, and
2254 * saves them, and the picture id, in module variables for the background
2255 * rendering function.
2256 *
2257 * The graphics window is opened if required, or closed if mode is zero.
2258 *
2259 * The function checks for changes of actual picture by calculating the
2260 * CRC for picture data; this helps to prevent unnecessary repaints in
2261 * cases where the interpreter passes us the same picture as we're already
2262 * displaying. There is a less than 1 in 4,294,967,296 chance that a new
2263 * picture will be missed. We'll live with that.
2264 *
2265 * Why use CRCs, rather than simply storing the values of picture passed in
2266 * a static variable? Because some games, typically Magnetic Windows, use
2267 * the picture argument as a form of string pointer, and can pass in the
2268 * same value for several, perhaps all, game pictures. If we just checked
2269 * for a change in the picture argument, we'd never see one. So we must
2270 * instead look for changes in the real picture data.
2271 */
2272 void
2273 ms_showpic (type32 picture, type8 mode)
2274 {
2275 static glui32 current_crc = 0; /* CRC of the current picture */
2276
2277 type8 *bitmap, animated;
2278 type16 width, height, palette[GMS_PALETTE_SIZE];
2279 long picture_bytes;
2280 glui32 crc;
2281
2282 /* See if the mode indicates no graphics. */
2283 if (mode == 0)
2284 {
2285 /* Note that the interpreter turned graphics off. */
2286 gms_graphics_interpreter = FALSE;
2287
2288 /*
2289 * If we are currently displaying the graphics window, stop any update
2290 * "thread" and turn off graphics.
2291 */
2292 if (gms_graphics_enabled && gms_graphics_are_displayed ())
2293 {
2294 gms_graphics_stop ();
2295 gms_graphics_close ();
2296 }
2297
2298 /* Nothing more to do now graphics are off. */
2299 return;
2300 }
2301
2302 /* Note that the interpreter turned graphics on. */
2303 gms_graphics_interpreter = TRUE;
2304
2305 /*
2306 * Obtain the image details for the requested picture. The call returns
2307 * NULL if there's a problem with the picture.
2308 */
2309 bitmap = ms_extract (picture, &width, &height, palette, &animated);
2310 if (!bitmap)
2311 return;
2312
2313 /* Note the last thing passed to ms_extract, in case of graphics restarts. */
2314 gms_graphics_picture = picture;
2315
2316 /* Calculate the picture size, and the CRC for the bitmap data. */
2317 picture_bytes = width * height * sizeof (*bitmap);
2318 crc = gms_get_buffer_crc (bitmap, picture_bytes);
2319
2320 /*
2321 * If there is no change of picture, we might be able to largely ignore the
2322 * call. Check for a change, and if we don't see one, and if graphics are
2323 * enabled and being displayed, we can safely ignore the call.
2324 */
2325 if (width == gms_graphics_width
2326 && height == gms_graphics_height
2327 && crc == current_crc
2328 && gms_graphics_enabled && gms_graphics_are_displayed ())
2329 return;
2330
2331 /*
2332 * We know now that this is either a genuine change of picture, or graphics
2333 * were off and have been turned on. So, record picture details, ensure
2334 * graphics is on, set the flags, and start the background graphics update.
2335 */
2336
2337 /*
2338 * Save the picture details for the update code. Here we take a complete
2339 * local copy of the bitmap, since the interpreter core may reuse part of
2340 * its memory for animations.
2341 */
2342 free (gms_graphics_bitmap);
2343 gms_graphics_bitmap = gms_malloc (picture_bytes);
2344 memcpy (gms_graphics_bitmap, bitmap, picture_bytes);
2345 gms_graphics_width = width;
2346 gms_graphics_height = height;
2347 memcpy (gms_graphics_palette, palette, sizeof (palette));
2348 gms_graphics_animated = animated;
2349
2350 /* Retain the new picture CRC. */
2351 current_crc = crc;
2352
2353 /*
2354 * If graphics are enabled, ensure the window is displayed, set the
2355 * appropriate flags, and start graphics update. If they're not enabled,
2356 * the picture details will simply stick around in module variables until
2357 * they are required.
2358 */
2359 if (gms_graphics_enabled)
2360 {
2361 /*
2362 * Ensure graphics on, then set the new picture flag and start the
2363 * updating "thread".
2364 */
2365 if (gms_graphics_open ())
2366 {
2367 gms_graphics_new_picture = TRUE;
2368 gms_graphics_start ();
2369 }
2370 }
2371 }
2372
2373
2374 /*
2375 * gms_graphics_picture_is_available()
2376 *
2377 * Return TRUE if the graphics module data is loaded with a usable picture,
2378 * FALSE if there is no picture available to display.
2379 */
2380 static int
2381 gms_graphics_picture_is_available (void)
2382 {
2383 return gms_graphics_bitmap != NULL;
2384 }
2385
2386
2387 /*
2388 * gms_graphics_get_picture_details()
2389 *
2390 * Return the width, height, and animation flag of the currently loaded
2391 * picture. The function returns FALSE if no picture is loaded, otherwise
2392 * TRUE, with picture details in the return arguments.
2393 */
2394 static int
2395 gms_graphics_get_picture_details (int *width, int *height, int *is_animated)
2396 {
2397 if (gms_graphics_picture_is_available ())
2398 {
2399 if (width)
2400 *width = gms_graphics_width;
2401 if (height)
2402 *height = gms_graphics_height;
2403 if (is_animated)
2404 *is_animated = gms_graphics_animated;
2405
2406 return TRUE;
2407 }
2408
2409 return FALSE;
2410 }
2411
2412
2413 /*
2414 * gms_graphics_get_rendering_details()
2415 *
2416 * Returns the current level of applied gamma correction, as a string, the
2417 * count of colors in the picture, and a flag indicating if graphics is
2418 * active (busy). The function return FALSE if graphics is not enabled or
2419 * if not being displayed, otherwise TRUE with the gamma, color count, and
2420 * active flag in the return arguments.
2421 *
2422 * This function races with the graphics timeout, as it returns information
2423 * set up by the first timeout following a new picture. There's a very,
2424 * very small chance that it might win the race, in which case out-of-date
2425 * gamma and color count values are returned.
2426 */
2427 static int
2428 gms_graphics_get_rendering_details (const char **gamma, int *color_count,
2429 int *is_active)
2430 {
2431 if (gms_graphics_enabled && gms_graphics_are_displayed ())
2432 {
2433 /*
2434 * Return the string representing the gamma correction. If racing
2435 * with timeouts, we might return the gamma for the last picture.
2436 */
2437 if (gamma)
2438 {
2439 assert (gms_graphics_current_gamma);
2440 *gamma = gms_graphics_current_gamma->level;
2441 }
2442
2443 /*
2444 * Return the color count noted by timeouts on the first timeout
2445 * following a new picture. Again, we might return the one for
2446 * the prior picture.
2447 */
2448 if (color_count)
2449 *color_count = gms_graphics_color_count;
2450
2451 /* Return graphics active flag. */
2452 if (is_active)
2453 *is_active = gms_graphics_active;
2454
2455 return TRUE;
2456 }
2457
2458 return FALSE;
2459 }
2460
2461
2462 /*
2463 * gms_graphics_interpreter_enabled()
2464 *
2465 * Return TRUE if it looks like interpreter graphics are turned on, FALSE
2466 * otherwise.
2467 */
2468 static int
2469 gms_graphics_interpreter_enabled (void)
2470 {
2471 return gms_graphics_interpreter;
2472 }
2473
2474
2475 /*
2476 * gms_graphics_cleanup()
2477 *
2478 * Free memory resources allocated by graphics functions. Called on game
2479 * end.
2480 */
2481 static void
2482 gms_graphics_cleanup (void)
2483 {
2484 free (gms_graphics_bitmap);
2485 gms_graphics_bitmap = NULL;
2486 free (gms_graphics_off_screen);
2487 gms_graphics_off_screen = NULL;
2488 free (gms_graphics_on_screen);
2489 gms_graphics_on_screen = NULL;
2490
2491 gms_graphics_animated = FALSE;
2492 gms_graphics_picture = 0;
2493 }
2494
2495
2496 /*---------------------------------------------------------------------*/
2497 /* Glk port status line functions */
2498 /*---------------------------------------------------------------------*/
2499
2500 /*
2501 * The interpreter feeds us status line characters one at a time, with Tab
2502 * indicating right justify, and CR indicating the line is complete. To get
2503 * this to fit with the Glk event and redraw model, here we'll buffer each
2504 * completed status line, so we have a stable string to output when needed.
2505 * It's also handy to have this buffer for Glk libraries that don't support
2506 * separate windows.
2507 */
2508 enum { GMS_STATBUFFER_LENGTH = 1024 };
2509 static char gms_status_buffer[GMS_STATBUFFER_LENGTH];
2510 static int gms_status_length = 0;
2511
2512 /* Default width used for non-windowing Glk status lines. */
2513 static const int GMS_DEFAULT_STATUS_WIDTH = 74;
2514
2515
2516 /*
2517 * ms_statuschar()
2518 *
2519 * Receive one status character from the interpreter. Characters are
2520 * buffered internally, and on CR, the buffer is copied to the main static
2521 * status buffer for use by the status line printing function.
2522 */
2523 void
2524 ms_statuschar (type8 c)
2525 {
2526 static char buffer[GMS_STATBUFFER_LENGTH];
2527 static int length = 0;
2528
2529 /*
2530 * If the status character is newline, transfer locally buffered data to
2531 * the common buffer, empty the local buffer; otherwise, if space permits,
2532 * buffer the character.
2533 */
2534 if (c == '\n')
2535 {
2536 memcpy (gms_status_buffer, buffer, length);
2537 gms_status_length = length;
2538
2539 length = 0;
2540 }
2541 else
2542 {
2543 if (length < sizeof (buffer))
2544 buffer[length++] = c;
2545 }
2546 }
2547
2548
2549 /*
2550 * gms_status_update()
2551 *
2552 * Update the information in the status window with the current contents of
2553 * the completed status line buffer, or a default string if no completed
2554 * status line.
2555 */
2556 static void
2557 gms_status_update (void)
2558 {
2559 glui32 width, height;
2560 assert (gms_status_window);
2561
2562 glk_window_get_size (gms_status_window, &width, &height);
2563 if (height > 0)
2564 {
2565 glk_window_clear (gms_status_window);
2566 glk_window_move_cursor (gms_status_window, 0, 0);
2567 glk_set_window (gms_status_window);
2568
2569 #ifdef GARGLK
2570 glk_set_style (style_User1);
2571 for (glui32 index = 0; index < width; index++)
2572 glk_put_char (' ');
2573 glk_window_move_cursor (gms_status_window, 1, 0);
2574 #endif
2575
2576 if (gms_status_length > 0)
2577 {
2578 int index;
2579
2580 /*
2581 * Output each character from the status line buffer. If the
2582 * character is Tab, position the cursor to eleven characters shy
2583 * of the status window right.
2584 */
2585 for (index = 0; index < gms_status_length; index++)
2586 {
2587 if (gms_status_buffer[index] == '\t')
2588 glk_window_move_cursor (gms_status_window, width - 11, 0);
2589 else
2590 glk_put_char (gms_status_buffer[index]);
2591 }
2592 }
2593 else
2594 {
2595 const char *game_name;
2596
2597 /*
2598 * We have no status line to display, so print the game's name, or
2599 * a standard message if unable to identify the game. Having no
2600 * status line is common with Magnetic Windows games, which don't,
2601 * in general, seem to use one.
2602 */
2603 game_name = gms_gameid_get_game_name ();
2604 glk_put_string (game_name ? (char *) game_name
2605 : "Glk Magnetic version 2.3");
2606 }
2607
2608 glk_set_window (gms_main_window);
2609 }
2610 }
2611
2612
2613 /*
2614 * gms_status_print()
2615 *
2616 * Print the current contents of the completed status line buffer out in the
2617 * main window, if it has changed since the last call. This is for non-
2618 * windowing Glk libraries.
2619 */
2620 static void
2621 gms_status_print (void)
2622 {
2623 static char buffer[GMS_STATBUFFER_LENGTH];
2624 static int length = 0;
2625
2626 int index, column;
2627
2628 /*
2629 * Do nothing if there is no status line to print, or if the status
2630 * line hasn't changed since last printed.
2631 */
2632 if (gms_status_length == 0
2633 || (gms_status_length == length
2634 && strncmp (buffer, gms_status_buffer, length)) == 0)
2635 return;
2636
2637 /* Set fixed width font to try to preserve status line formatting. */
2638 glk_set_style (style_Preformatted);
2639
2640 /* Bracket, and output the status line buffer. */
2641 glk_put_string ("[ ");
2642 column = 1;
2643 for (index = 0; index < gms_status_length; index++)
2644 {
2645 /*
2646 * If the character is Tab, position the cursor to eleven characters
2647 * shy of the right edge. In the absence of the real window dimensions,
2648 * we'll select 74 characters, which gives us a 78 character status
2649 * line; pretty standard.
2650 */
2651 if (gms_status_buffer[index] == '\t')
2652 {
2653 while (column <= GMS_DEFAULT_STATUS_WIDTH - 11)
2654 {
2655 glk_put_char (' ');
2656 column++;
2657 }
2658 }
2659 else
2660 {
2661 glk_put_char (gms_status_buffer[index]);
2662 column++;
2663 }
2664 }
2665
2666 while (column <= GMS_DEFAULT_STATUS_WIDTH)
2667 {
2668 glk_put_char (' ');
2669 column++;
2670 }
2671 glk_put_string (" ]\n");
2672
2673 /* Save the details of the printed status buffer. */
2674 memcpy (buffer, gms_status_buffer, gms_status_length);
2675 length = gms_status_length;
2676 }
2677
2678
2679 /*
2680 * gms_status_notify()
2681 *
2682 * Front end function for updating status. Either updates the status window
2683 * or prints the status line to the main window.
2684 */
2685 static void
2686 gms_status_notify (void)
2687 {
2688 if (gms_status_window)
2689 gms_status_update ();
2690 else
2691 gms_status_print ();
2692 }
2693
2694
2695 /*
2696 * gms_status_redraw()
2697 *
2698 * Redraw the contents of any status window with the buffered status string.
2699 * This function should be called on the appropriate Glk window resize and
2700 * arrange events.
2701 */
2702 static void
2703 gms_status_redraw (void)
2704 {
2705 if (gms_status_window)
2706 {
2707 winid_t parent;
2708
2709 /*
2710 * Rearrange the status window, without changing its actual arrangement
2711 * in any way. This is a hack to work round incorrect window repainting
2712 * in Xglk; it forces a complete repaint of affected windows on Glk
2713 * window resize and arrange events, and works in part because Xglk
2714 * doesn't check for actual arrangement changes in any way before
2715 * invalidating its windows. The hack should be harmless to Glk
2716 * libraries other than Xglk, moreover, we're careful to activate it
2717 * only on resize and arrange events.
2718 */
2719 parent = glk_window_get_parent (gms_status_window);
2720 glk_window_set_arrangement (parent,
2721 winmethod_Above | winmethod_Fixed, 1, NULL);
2722
2723 gms_status_update ();
2724 }
2725 }
2726
2727
2728 /*---------------------------------------------------------------------*/
2729 /* Glk port output functions */
2730 /*---------------------------------------------------------------------*/
2731
2732 /*
2733 * Flag for if the user entered "help" as their last input, or if hints have
2734 * been silenced as a result of already using a Glk command.
2735 */
2736 static int gms_help_requested = FALSE,
2737 gms_help_hints_silenced = FALSE;
2738
2739 /*
2740 * Output buffer. We receive characters one at a time, and it's a bit
2741 * more efficient for everyone if we buffer them, and output a complete
2742 * string on a flush call.
2743 */
2744 static char *gms_output_buffer = NULL;
2745 static int gms_output_allocation = 0,
2746 gms_output_length = 0;
2747
2748 /*
2749 * Flag to indicate if the last buffer flushed looked like it ended in a
2750 * ">" prompt.
2751 */
2752 static int gms_output_prompt = FALSE;
2753
2754
2755 /*
2756 * gms_output_register_help_request()
2757 * gms_output_silence_help_hints()
2758 * gms_output_provide_help_hint()
2759 *
2760 * Register a request for help, and print a note of how to get Glk command
2761 * help from the interpreter unless silenced.
2762 */
2763 static void
2764 gms_output_register_help_request (void)
2765 {
2766 gms_help_requested = TRUE;
2767 }
2768
2769 static void
2770 gms_output_silence_help_hints (void)
2771 {
2772 gms_help_hints_silenced = TRUE;
2773 }
2774
2775 static void
2776 gms_output_provide_help_hint (void)
2777 {
2778 if (gms_help_requested && !gms_help_hints_silenced)
2779 {
2780 glk_set_style (style_Emphasized);
2781 glk_put_string ("[Try 'glk help' for help on special interpreter"
2782 " commands]\n");
2783
2784 gms_help_requested = FALSE;
2785 glk_set_style (style_Normal);
2786 }
2787 }
2788
2789
2790 /*
2791 * gms_game_prompted()
2792 *
2793 * Return TRUE if the last game output appears to have been a ">" prompt.
2794 * Once called, the flag is reset to FALSE, and requires more game output
2795 * to set it again.
2796 */
2797 static int
2798 gms_game_prompted (void)
2799 {
2800 int result;
2801
2802 result = gms_output_prompt;
2803 gms_output_prompt = FALSE;
2804
2805 return result;
2806 }
2807
2808
2809 /*
2810 * gms_detect_game_prompt()
2811 *
2812 * See if the last non-newline-terminated line in the output buffer seems
2813 * to be a prompt, and set the game prompted flag if it does, otherwise
2814 * clear it.
2815 */
2816 static void
2817 gms_detect_game_prompt (void)
2818 {
2819 int index;
2820
2821 gms_output_prompt = FALSE;
2822
2823 /*
2824 * Search for a prompt across any last unterminated buffered line; a prompt
2825 * is any non-space character on that line.
2826 */
2827 for (index = gms_output_length - 1;
2828 index >= 0 && gms_output_buffer[index] != '\n'; index--)
2829 {
2830 if (gms_output_buffer[index] != ' ')
2831 {
2832 gms_output_prompt = TRUE;
2833 break;
2834 }
2835 }
2836 }
2837
2838
2839 /*
2840 * gms_output_delete()
2841 *
2842 * Delete all buffered output text. Free all malloc'ed buffer memory, and
2843 * return the buffer variables to their initial values.
2844 */
2845 static void
2846 gms_output_delete (void)
2847 {
2848 free (gms_output_buffer);
2849 gms_output_buffer = NULL;
2850 gms_output_allocation = gms_output_length = 0;
2851 }
2852
2853
2854 /*
2855 * gms_output_flush()
2856 *
2857 * Flush any buffered output text to the Glk main window, and clear the
2858 * buffer.
2859 */
2860 static void
2861 gms_output_flush (void)
2862 {
2863 assert (glk_stream_get_current ());
2864
2865 if (gms_output_length > 0)
2866 {
2867 /*
2868 * See if the game issued a standard prompt, then print the buffer to
2869 * the main window. If providing a help hint, position that before
2870 * the game's prompt (if any).
2871 */
2872 gms_detect_game_prompt ();
2873 glk_set_style (style_Normal);
2874
2875 if (gms_output_prompt)
2876 {
2877 int index;
2878
2879 for (index = gms_output_length - 1;
2880 index >= 0 && gms_output_buffer[index] != '\n'; )
2881 index--;
2882
2883 glk_put_buffer (gms_output_buffer, index + 1);
2884 gms_output_provide_help_hint ();
2885 glk_put_buffer (gms_output_buffer + index + 1,
2886 gms_output_length - index - 1);
2887 }
2888 else
2889 {
2890 glk_put_buffer (gms_output_buffer, gms_output_length);
2891 gms_output_provide_help_hint ();
2892 }
2893
2894 gms_output_delete ();
2895 }
2896 }
2897
2898
2899 /*
2900 * ms_putchar()
2901 *
2902 * Buffer a character for eventual printing to the main window.
2903 */
2904 void
2905 ms_putchar (type8 c)
2906 {
2907 int bytes;
2908 assert (gms_output_length <= gms_output_allocation);
2909
2910 /*
2911 * See if the character is a backspace. Magnetic Scrolls games can send
2912 * backspace characters to the display. We'll need to handle such
2913 * characters specially, by taking the last character out of the buffer.
2914 */
2915 if (c == '\b')
2916 {
2917 if (gms_output_length > 0)
2918 gms_output_length--;
2919
2920 return;
2921 }
2922
2923 /* Grow the output buffer if necessary, then add the character. */
2924 for (bytes = gms_output_allocation; bytes < gms_output_length + 1; )
2925 bytes = bytes == 0 ? 1 : bytes << 1;
2926
2927 if (bytes > gms_output_allocation)
2928 {
2929 gms_output_buffer = gms_realloc (gms_output_buffer, bytes);
2930 gms_output_allocation = bytes;
2931 }
2932
2933 gms_output_buffer[gms_output_length++] = c;
2934 }
2935
2936
2937 /*
2938 * gms_styled_string()
2939 * gms_styled_char()
2940 * gms_standout_string()
2941 * gms_standout_char()
2942 * gms_normal_string()
2943 * gms_normal_char()
2944 * gms_header_string()
2945 * gms_banner_string()
2946 *
2947 * Convenience functions to print strings in assorted styles. A standout
2948 * string is one that hints that it's from the interpreter, not the game.
2949 */
2950 static void
2951 gms_styled_string (glui32 style, const char *message)
2952 {
2953 assert (message);
2954
2955 glk_set_style (style);
2956 glk_put_string ((char *) message);
2957 glk_set_style (style_Normal);
2958 }
2959
2960 static void
2961 gms_styled_char (glui32 style, char c)
2962 {
2963 char buffer[2];
2964
2965 buffer[0] = c;
2966 buffer[1] = '\0';
2967 gms_styled_string (style, buffer);
2968 }
2969
2970 static void
2971 gms_standout_string (const char *message)
2972 {
2973 gms_styled_string (style_Emphasized, message);
2974 }
2975
2976 static void
2977 gms_standout_char (char c)
2978 {
2979 gms_styled_char (style_Emphasized, c);
2980 }
2981
2982 static void
2983 gms_normal_string (const char *message)
2984 {
2985 gms_styled_string (style_Normal, message);
2986 }
2987
2988 static void
2989 gms_normal_char (char c)
2990 {
2991 gms_styled_char (style_Normal, c);
2992 }
2993
2994 static void
2995 gms_header_string (const char *message)
2996 {
2997 gms_styled_string (style_Header, message);
2998 }
2999
3000 static void
3001 gms_banner_string (const char *message)
3002 {
3003 gms_styled_string (style_Subheader, message);
3004 }
3005
3006
3007 /*
3008 * ms_fatal()
3009 *
3010 * Handle fatal interpreter error message.
3011 */
3012 void
3013 ms_fatal (type8s * string)
3014 {
3015 gms_status_notify ();
3016 gms_output_flush ();
3017
3018 gms_fatal (string);
3019 glk_exit ();
3020 }
3021
3022
3023 /*
3024 * ms_flush()
3025 *
3026 * Handle a core interpreter call to flush the output buffer. Because Glk
3027 * only flushes its buffers and displays text on glk_select(), we can ignore
3028 * these calls as long as we call gms_output_flush() when reading line input.
3029 *
3030 * Taking ms_flush() at face value can cause game text to appear before status
3031 * line text where we are working with a non-windowing Glk, so it's best
3032 * ignored where we can.
3033 */
3034 void
3035 ms_flush (void)
3036 {
3037 }
3038
3039
3040 /*---------------------------------------------------------------------*/
3041 /* Glk port hint functions */
3042 /*---------------------------------------------------------------------*/
3043
3044 /* Hint type definitions. */
3045 enum {
3046 GMS_HINT_TYPE_FOLDER = 1,
3047 GMS_HINT_TYPE_TEXT = 2
3048 };
3049
3050 /* Success and fail return codes from hint functions. */
3051 static const type8 GMS_HINT_SUCCESS = 1,
3052 GMS_HINT_ERROR = 0;
3053
3054 /* Default window sizes for non-windowing Glk libraries. */
3055 static const glui32 GMS_HINT_DEFAULT_WIDTH = 72,
3056 GMS_HINT_DEFAULT_HEIGHT = 25;
3057
3058 /*
3059 * Special hint nodes indicating the root hint node, and a value to signal
3060 * quit from hints subsystem.
3061 */
3062 static const type16 GMS_HINT_ROOT_NODE = 0,
3063 GMS_HINTS_DONE = USHRT_MAX;
3064
3065 /* Generic hint topic for the root hints node. */
3066 static const char * const GMS_GENERIC_TOPIC = "Hints Menu";
3067
3068 /*
3069 * Note of the interpreter's hints array. Note that keeping its address
3070 * like this assumes that it's either static or heap in the interpreter.
3071 */
3072 static struct ms_hint *gms_hints = NULL;
3073
3074 /* Details of the current hint node on display from the hints array. */
3075 static type16 gms_current_hint_node = 0;
3076
3077 /*
3078 * Array of cursors for each hint. The cursor indicates the current hint
3079 * position in a folder, and the last hint shown in text hints. Space
3080 * is allocated as needed for a given set of hints, and needs to be freed
3081 * on interpreter exit.
3082 */
3083 static int *gms_hint_cursor = NULL;
3084
3085
3086 /*
3087 * gms_get_hint_max_node()
3088 *
3089 * Return the maximum hint node referred to by the tree under the given node.
3090 * The result is the largest index found, or node, if greater. Because the
3091 * interpreter doesn't supply it, we need to uncover it the hard way. The
3092 * function is recursive, and since it is a tree search, assumes that hints
3093 * is a tree, not a graph.
3094 */
3095 static type16
3096 gms_get_hint_max_node (const struct ms_hint hints[], type16 node)
3097 {
3098 const struct ms_hint *hint;
3099 int index;
3100 type16 max_node;
3101 assert (hints);
3102
3103 hint = hints + node;
3104 max_node = node;
3105
3106 switch (hint->nodetype)
3107 {
3108 case GMS_HINT_TYPE_TEXT:
3109 break;
3110
3111 case GMS_HINT_TYPE_FOLDER:
3112 /*
3113 * Recursively find the maximum node reference for each link, and keep
3114 * the largest value found.
3115 */
3116 for (index = 0; index < hint->elcount; index++)
3117 {
3118 type16 link_max;
3119
3120 link_max = gms_get_hint_max_node (hints, hint->links[index]);
3121 if (link_max > max_node)
3122 max_node = link_max;
3123 }
3124 break;
3125
3126 default:
3127 gms_fatal ("GLK: Invalid hints node type encountered");
3128 glk_exit ();
3129 }
3130
3131 /*
3132 * Return the largest node reference found, capped to avoid overlapping the
3133 * special end-hints value.
3134 */
3135 return max_node < GMS_HINTS_DONE ? max_node : GMS_HINTS_DONE - 1;
3136 }
3137
3138
3139 /*
3140 * gms_get_hint_content()
3141 *
3142 * Return the content string for a given hint number within a given node.
3143 * This counts over 'number' ASCII NULs in the node's content, returning
3144 * the address of the string located this way.
3145 */
3146 static const char *
3147 gms_get_hint_content (const struct ms_hint hints[], type16 node, int number)
3148 {
3149 const struct ms_hint *hint;
3150 int offset, index;
3151 assert (hints);
3152
3153 hint = hints + node;
3154
3155 /* Run through content until 'number' strings found. */
3156 offset = 0;
3157 for (index = 0; index < number; index++)
3158 offset += strlen (hint->content + offset) + 1;
3159
3160 /* Return the start of the number'th string encountered. */
3161 return hint->content + offset;
3162 }
3163
3164
3165 /*
3166 * gms_get_hint_topic()
3167 *
3168 * Return the topic string for a given hint node. This is found by searching
3169 * the parent node for a link to the node handed in. For the root node, the
3170 * string is defaulted, since the root node has no parent.
3171 */
3172 static const char *
3173 gms_get_hint_topic (const struct ms_hint hints[], type16 node)
3174 {
3175 assert (hints);
3176
3177 if (node == GMS_HINT_ROOT_NODE)
3178 {
3179 /* If the node is the root node, return a generic string. */
3180 return GMS_GENERIC_TOPIC;
3181 }
3182 else
3183 {
3184 type16 parent;
3185 int index;
3186 const char *topic;
3187
3188 /*
3189 * Search the parent for a link to node, and use that as the hint topic;
3190 * NULL if none found.
3191 */
3192 parent = hints[node].parent;
3193
3194 topic = NULL;
3195 for (index = 0; index < hints[parent].elcount; index++)
3196 {
3197 if (hints[parent].links[index] == node)
3198 {
3199 topic = gms_get_hint_content (hints, parent, index);
3200 break;
3201 }
3202 }
3203
3204 return topic ? topic : GMS_GENERIC_TOPIC;
3205 }
3206 }
3207
3208
3209 /*
3210 * gms_hint_open()
3211 *
3212 * If not already open, open the hints windows. Returns TRUE if the windows
3213 * opened, or were already open.
3214 *
3215 * The function creates two hints windows -- a text grid on top, for menus,
3216 * and a text buffer below for hints.
3217 */
3218 static int
3219 gms_hint_open (void)
3220 {
3221 if (!gms_hint_menu_window)
3222 {
3223 assert (!gms_hint_text_window);
3224
3225 /*
3226 * Open the hint menu window. The initial size is two lines, but we'll
3227 * change this later to suit the hint.
3228 */
3229 gms_hint_menu_window = glk_window_open (gms_main_window,
3230 winmethod_Above | winmethod_Fixed,
3231 2, wintype_TextGrid, 0);
3232 if (!gms_hint_menu_window)
3233 return FALSE;
3234
3235 /*
3236 * Now open the hints text window. This is set to be 100% of the size
3237 * of the main window, so should cover what remains of it completely.
3238 */
3239 gms_hint_text_window = glk_window_open (gms_main_window,
3240 winmethod_Above
3241 | winmethod_Proportional,
3242 100, wintype_TextBuffer, 0);
3243 if (!gms_hint_text_window)
3244 {
3245 glk_window_close (gms_hint_menu_window, NULL);
3246 gms_hint_menu_window = NULL;
3247 return FALSE;
3248 }
3249 }
3250
3251 return TRUE;
3252 }
3253
3254
3255 /*
3256 * gms_hint_close()
3257 *
3258 * If open, close the hints windows.
3259 */
3260 static void
3261 gms_hint_close (void)
3262 {
3263 if (gms_hint_menu_window)
3264 {
3265 assert (gms_hint_text_window);
3266
3267 glk_window_close (gms_hint_menu_window, NULL);
3268 gms_hint_menu_window = NULL;
3269 glk_window_close (gms_hint_text_window, NULL);
3270 gms_hint_text_window = NULL;
3271 }
3272 }
3273
3274
3275 /*
3276 * gms_hint_windows_available()
3277 *
3278 * Return TRUE if hints windows are available. If they're not, the hints
3279 * system will need to use alternative output methods.
3280 */
3281 static int
3282 gms_hint_windows_available (void)
3283 {
3284 return (gms_hint_menu_window && gms_hint_text_window);
3285 }
3286
3287
3288 /*
3289 * gms_hint_menu_print()
3290 * gms_hint_menu_header()
3291 * gms_hint_menu_justify()
3292 * gms_hint_text_print()
3293 * gms_hint_menutext_done()
3294 * gms_hint_menutext_start()
3295 *
3296 * Output functions for writing hints. These functions will write to hints
3297 * windows where available, and to the main window where not. When writing
3298 * to hints windows, they also take care not to line wrap in the menu window.
3299 * Limited formatting is available.
3300 */
3301 static void
3302 gms_hint_menu_print (int line, int column, const char *string,
3303 glui32 width, glui32 height)
3304 {
3305 assert (string);
3306
3307 /* Ignore the call if the text position is outside the window. */
3308 if (!(line > height || column > width))
3309 {
3310 if (gms_hint_windows_available ())
3311 {
3312 int posn, index;
3313
3314 glk_window_move_cursor (gms_hint_menu_window, column, line);
3315 glk_set_window (gms_hint_menu_window);
3316
3317 /* Write until the end of the string, or the end of the window. */
3318 for (posn = column, index = 0;
3319 posn < width && index < strlen (string); posn++, index++)
3320 {
3321 glk_put_char (string[index]);
3322 }
3323
3324 glk_set_window (gms_main_window);
3325 }
3326 else
3327 {
3328 static int current_line = 0; /* Retained line number */
3329 static int current_column = 0; /* Retained col number */
3330
3331 int index;
3332
3333 /*
3334 * Check the line number against the last one output. If it is less,
3335 * assume the start of a new block. In this case, perform a hokey
3336 * type of screen clear.
3337 */
3338 if (line < current_line)
3339 {
3340 for (index = 0; index < height; index++)
3341 gms_normal_char ('\n');
3342
3343 current_line = 0;
3344 current_column = 0;
3345 }
3346
3347 /* Print blank lines until the target line is reached. */
3348 for (; current_line < line; current_line++)
3349 {
3350 gms_normal_char ('\n');
3351 current_column = 0;
3352 }
3353
3354 /* Now print spaces until the target column is reached. */
3355 for (; current_column < column; current_column++)
3356 gms_normal_char (' ');
3357
3358 /*
3359 * Write characters until the end of the string, or the end of the
3360 * (self-imposed not-really-there) window.
3361 */
3362 for (index = 0;
3363 current_column < width && index < strlen (string);
3364 current_column++, index++)
3365 {
3366 gms_normal_char (string[index]);
3367 }
3368 }
3369 }
3370 }
3371
3372 static void
3373 gms_hint_menu_header (int line, const char *string,
3374 glui32 width, glui32 height)
3375 {
3376 int posn, length;
3377 assert (string);
3378
3379 /* Output the text in the approximate line center. */
3380 length = strlen (string);
3381 posn = length < width ? (width - length) / 2 : 0;
3382 gms_hint_menu_print (line, posn, string, width, height);
3383 }
3384
3385 static void
3386 gms_hint_menu_justify (int line,
3387 const char *left_string, const char *right_string,
3388 glui32 width, glui32 height)
3389 {
3390 int posn, length;
3391 assert (left_string && right_string);
3392
3393 /* Write left text normally to window left. */
3394 gms_hint_menu_print (line, 0, left_string, width, height);
3395
3396 /* Output the right text flush with the right of the window. */
3397 length = strlen (right_string);
3398 posn = length < width ? width - length : 0;
3399 gms_hint_menu_print (line, posn, right_string, width, height);
3400 }
3401
3402 static void
3403 gms_hint_text_print (const char *string)
3404 {
3405 assert (string);
3406
3407 if (gms_hint_windows_available ())
3408 {
3409 glk_set_window (gms_hint_text_window);
3410 glk_put_string ((char *) string);
3411 glk_set_window (gms_main_window);
3412 }
3413 else
3414 gms_normal_string (string);
3415 }
3416
3417 static void
3418 gms_hint_menutext_start (void)
3419 {
3420 /*
3421 * Twiddle for non-windowing libraries; 'clear' the main window by writing
3422 * a null string at line 1, then a null string at line 0. This works
3423 * because we know the current output line in gms_hint_menu_print() is zero,
3424 * since we set it that way with gms_hint_menutext_done(), or if this is
3425 * the first call, then that's its initial value.
3426 */
3427 if (!gms_hint_windows_available ())
3428 {
3429 gms_hint_menu_print (1, 0, "",
3430 GMS_HINT_DEFAULT_WIDTH, GMS_HINT_DEFAULT_HEIGHT);
3431 gms_hint_menu_print (0, 0, "",
3432 GMS_HINT_DEFAULT_WIDTH, GMS_HINT_DEFAULT_HEIGHT);
3433 }
3434 }
3435
3436 static void
3437 gms_hint_menutext_done (void)
3438 {
3439 /*
3440 * Twiddle for non-windowing libraries; 'clear' the main window by writing
3441 * an empty string to line zero. For windowing Glk libraries, this function
3442 * does nothing.
3443 */
3444 if (!gms_hint_windows_available ())
3445 {
3446 gms_hint_menu_print (0, 0, "",
3447 GMS_HINT_DEFAULT_WIDTH, GMS_HINT_DEFAULT_HEIGHT);
3448 }
3449 }
3450
3451
3452 /*
3453 * gms_hint_menutext_char_event()
3454 *
3455 * Request and return a character event from the hints windows. In practice,
3456 * this means either of the hints windows if available, or the main window
3457 * if not.
3458 */
3459 static void
3460 gms_hint_menutext_char_event (event_t * event)
3461 {
3462 assert (event);
3463
3464 if (gms_hint_windows_available ())
3465 {
3466 glk_request_char_event (gms_hint_menu_window);
3467 glk_request_char_event (gms_hint_text_window);
3468
3469 gms_event_wait (evtype_CharInput, event);
3470 assert (event->win == gms_hint_menu_window
3471 || event->win == gms_hint_text_window);
3472
3473 glk_cancel_char_event (gms_hint_menu_window);
3474 glk_cancel_char_event (gms_hint_text_window);
3475 }
3476 else
3477 {
3478 glk_request_char_event (gms_main_window);
3479 gms_event_wait (evtype_CharInput, event);
3480 }
3481 }
3482
3483
3484 /*
3485 * gms_hint_arrange_windows()
3486 *
3487 * Arrange the hints windows so that the hint menu window has the requested
3488 * number of lines. Returns the actual hint menu window width and height,
3489 * or defaults if no hints windows are available.
3490 */
3491 static void
3492 gms_hint_arrange_windows (int requested_lines, glui32 * width, glui32 * height)
3493 {
3494 if (gms_hint_windows_available ())
3495 {
3496 winid_t parent;
3497
3498 /* Resize the hint menu window to fit the current hint. */
3499 parent = glk_window_get_parent (gms_hint_menu_window);
3500 glk_window_set_arrangement (parent,
3501 winmethod_Above | winmethod_Fixed,
3502 requested_lines, NULL);
3503
3504 /* Measure, and return the size of the hint menu window. */
3505 glk_window_get_size (gms_hint_menu_window, width, height);
3506
3507 /* Clear both the hint menu and the hint text window. */
3508 glk_window_clear (gms_hint_menu_window);
3509 glk_window_clear (gms_hint_text_window);
3510 }
3511 else
3512 {
3513 /*
3514 * No hints windows, so default width and height. The hints output
3515 * functions will cope with this.
3516 */
3517 if (width)
3518 *width = GMS_HINT_DEFAULT_WIDTH;
3519 if (height)
3520 *height = GMS_HINT_DEFAULT_HEIGHT;
3521 }
3522 }
3523
3524
3525 /*
3526 * gms_hint_display_folder()
3527 *
3528 * Update the hints windows for the given folder hint node.
3529 */
3530 static void
3531 gms_hint_display_folder (const struct ms_hint hints[],
3532 const int cursor[], type16 node)
3533 {
3534 glui32 width, height;
3535 int line, index;
3536 assert (hints && cursor);
3537
3538 /*
3539 * Arrange windows to suit the hint folder. For a folder menu window we
3540 * use one line for each element, three for the controls, and two spacers,
3541 * making a total of five additional lines. Width and height receive the
3542 * actual menu window dimensions.
3543 */
3544 gms_hint_arrange_windows (hints[node].elcount + 5, &width, &height);
3545
3546 /* Paint in the menu header. */
3547 line = 0;
3548 gms_hint_menu_header (line++,
3549 gms_get_hint_topic (hints, node),
3550 width, height);
3551 gms_hint_menu_justify (line++,
3552 " N = next subject ", " P = previous ",
3553 width, height);
3554 gms_hint_menu_justify (line++,
3555 " RETURN = read subject ",
3556 node == GMS_HINT_ROOT_NODE
3557 ? " Q = resume game " : " Q = previous menu ",
3558 width, height);
3559
3560 /*
3561 * Output a blank line, then the menu for the node's folder hint. The folder
3562 * text for the selected hint is preceded by a '>' pointer.
3563 */
3564 line++;
3565 for (index = 0; index < hints[node].elcount; index++)
3566 {
3567 gms_hint_menu_print (line, 3,
3568 index == cursor[node] ? ">" : " ",
3569 width, height);
3570 gms_hint_menu_print (line++, 5,
3571 gms_get_hint_content (hints, node, index),
3572 width, height);
3573 }
3574
3575 /*
3576 * Terminate with a blank line; using a single space here improves cursor
3577 * positioning for optimized output libraries (for example, without it,
3578 * curses output will leave the cursor at the end of the previous line).
3579 */
3580 gms_hint_menu_print (line, 0, " ", width, height);
3581 }
3582
3583
3584 /*
3585 * gms_hint_display_text()
3586 *
3587 * Update the hints windows for the given text hint node.
3588 */
3589 static void
3590 gms_hint_display_text (const struct ms_hint hints[],
3591 const int cursor[], type16 node)
3592 {
3593 glui32 width, height;
3594 int line, index;
3595 assert (hints && cursor);
3596
3597 /*
3598 * Arrange windows to suit the hint text. For a hint menu, we use a simple
3599 * two-line set of controls; everything else is in the hints text window.
3600 * Width and height receive the actual menu window dimensions.
3601 */
3602 gms_hint_arrange_windows (2, &width, &height);
3603
3604 /* Paint in a short menu header. */
3605 line = 0;
3606 gms_hint_menu_header (line++,
3607 gms_get_hint_topic (hints, node),
3608 width, height);
3609 gms_hint_menu_justify (line++,
3610 " RETURN = read hint ", " Q = previous menu ",
3611 width, height);
3612
3613 /*
3614 * Output hints to the hints text window. Hints not yet exposed are
3615 * indicated by the cursor for the hint, and are displayed as a dash.
3616 */
3617 gms_hint_text_print ("\n");
3618 for (index = 0; index < hints[node].elcount; index++)
3619 {
3620 char buffer[16];
3621
3622 sprintf (buffer, "%3d. ", index + 1);
3623 gms_hint_text_print (buffer);
3624
3625 gms_hint_text_print (index < cursor[node]
3626 ? gms_get_hint_content (hints, node, index) : "-");
3627 gms_hint_text_print ("\n");
3628 }
3629 }
3630
3631
3632 /*
3633 * gms_hint_display()
3634 *
3635 * Display the given hint using the appropriate display function.
3636 */
3637 static void
3638 gms_hint_display (const struct ms_hint hints[],
3639 const int cursor[], type16 node)
3640 {
3641 assert (hints && cursor);
3642
3643 switch (hints[node].nodetype)
3644 {
3645 case GMS_HINT_TYPE_TEXT:
3646 gms_hint_display_text (hints, cursor, node);
3647 break;
3648
3649 case GMS_HINT_TYPE_FOLDER:
3650 gms_hint_display_folder (hints, cursor, node);
3651 break;
3652
3653 default:
3654 gms_fatal ("GLK: Invalid hints node type encountered");
3655 glk_exit ();
3656 }
3657 }
3658
3659
3660 /*
3661 * gms_hint_handle_folder()
3662 *
3663 * Handle a Glk keycode for the given folder hint. Return the next node to
3664 * handle, or the special end-hints on Quit at the root node.
3665 */
3666 static type16
3667 gms_hint_handle_folder (const struct ms_hint hints[],
3668 int cursor[], type16 node, glui32 keycode)
3669 {
3670 unsigned char response;
3671 type16 next_node;
3672 assert (hints && cursor);
3673
3674 /* Convert key code into a single response character. */
3675 switch (keycode)
3676 {
3677 case keycode_Down:
3678 response = 'N';
3679 break;
3680 case keycode_Up:
3681 response = 'P';
3682 break;
3683 case keycode_Right:
3684 case keycode_Return:
3685 response = '\n';
3686 break;
3687 case keycode_Left:
3688 case keycode_Escape:
3689 response = 'Q';
3690 break;
3691 default:
3692 response = keycode <= UCHAR_MAX ? glk_char_to_upper (keycode) : 0;
3693 break;
3694 }
3695
3696 /*
3697 * Now handle the response character. We'll default the next node to be
3698 * this node, but a response case can change it.
3699 */
3700 next_node = node;
3701 switch (response)
3702 {
3703 case 'N':
3704 /* Advance the hint cursor, wrapping at the folder end. */
3705 if (cursor[node] < hints[node].elcount - 1)
3706 cursor[node]++;
3707 else
3708 cursor[node] = 0;
3709 break;
3710
3711 case 'P':
3712 /* Regress the hint cursor, wrapping at the folder start. */
3713 if (cursor[node] > 0)
3714 cursor[node]--;
3715 else
3716 cursor[node] = hints[node].elcount - 1;
3717 break;
3718
3719 case '\n':
3720 /* The next node is the hint node at the cursor position. */
3721 next_node = hints[node].links[cursor[node]];
3722 break;
3723
3724 case 'Q':
3725 /* If root, we're done; if not, next node is node's parent. */
3726 next_node = node == GMS_HINT_ROOT_NODE
3727 ? GMS_HINTS_DONE : hints[node].parent;
3728 break;
3729
3730 default:
3731 break;
3732 }
3733
3734 return next_node;
3735 }
3736
3737
3738 /*
3739 * gms_hint_handle_text()
3740 *
3741 * Handle a Glk keycode for the given text hint. Return the next node to
3742 * handle.
3743 */
3744 static type16
3745 gms_hint_handle_text (const struct ms_hint hints[],
3746 int cursor[], type16 node, glui32 keycode)
3747 {
3748 unsigned char response;
3749 type16 next_node;
3750 assert (hints && cursor);
3751
3752 /* Convert key code into a single response character. */
3753 switch (keycode)
3754 {
3755 case keycode_Right:
3756 case keycode_Return:
3757 response = '\n';
3758 break;
3759 case keycode_Left:
3760 case keycode_Escape:
3761 response = 'Q';
3762 break;
3763 default:
3764 response = keycode <= UCHAR_MAX ? glk_char_to_upper (keycode) : 0;
3765 break;
3766 }
3767
3768 /*
3769 * Now handle the response character. We'll default the next node to be
3770 * this node, but a response case can change it.
3771 */
3772 next_node = node;
3773 switch (response)
3774 {
3775 case '\n':
3776 /* If not at end of the hint, advance the hint cursor. */
3777 if (cursor[node] < hints[node].elcount)
3778 cursor[node]++;
3779 break;
3780
3781 case 'Q':
3782 /* Done with this hint node, so next node is its parent. */
3783 next_node = hints[node].parent;
3784 break;
3785
3786 default:
3787 break;
3788 }
3789
3790 return next_node;
3791 }
3792
3793
3794 /*
3795 * gms_hint_handle()
3796 *
3797 * Handle a Glk keycode for the given hint using the appropriate handler
3798 * function. Return the next node to handle.
3799 */
3800 static type16
3801 gms_hint_handle (const struct ms_hint hints[],
3802 int cursor[], type16 node, glui32 keycode)
3803 {
3804 type16 next_node;
3805 assert (hints && cursor);
3806
3807 next_node = GMS_HINT_ROOT_NODE;
3808 switch (hints[node].nodetype)
3809 {
3810 case GMS_HINT_TYPE_TEXT:
3811 next_node = gms_hint_handle_text (hints, cursor, node, keycode);
3812 break;
3813
3814 case GMS_HINT_TYPE_FOLDER:
3815 next_node = gms_hint_handle_folder (hints, cursor, node, keycode);
3816 break;
3817
3818 default:
3819 gms_fatal ("GLK: Invalid hints node type encountered");
3820 glk_exit ();
3821 }
3822
3823 return next_node;
3824 }
3825
3826
3827 /*
3828 * ms_showhints()
3829 *
3830 * Start game hints. These are modal, though there's no overriding Glk
3831 * reason why. It's just that this matches the way they're implemented by
3832 * most Inform games. This may not be the best way of doing help, but at
3833 * least it's likely to be familiar, and anything more ambitious may be
3834 * beyond the current Glk capabilities.
3835 *
3836 * This function uses CRCs to detect any change of hints data. Normally,
3837 * we'd expect none, at least within a given game run, but we can probably
3838 * handle it okay if it happens.
3839 */
3840 type8
3841 ms_showhints (struct ms_hint * hints)
3842 {
3843 static int is_initialized = FALSE;
3844 static glui32 current_crc = 0;
3845
3846 type16 hint_count;
3847 glui32 crc;
3848 assert (hints);
3849
3850 /*
3851 * Find the number of hints in the array. To do this, we'll visit every
3852 * node in a tree search, starting at the root, to locate the maximum node
3853 * number found, then add one to that. It's a pity that the interpreter
3854 * doesn't hand us this information directly.
3855 */
3856 hint_count = gms_get_hint_max_node (hints, GMS_HINT_ROOT_NODE) + 1;
3857
3858 /*
3859 * Calculate a CRC for the hints array data. If the CRC has changed, or
3860 * this is the first call, assign a new cursor array.
3861 */
3862 crc = gms_get_buffer_crc (hints, hint_count * sizeof (*hints));
3863 if (crc != current_crc || !is_initialized)
3864 {
3865 int bytes;
3866
3867 /* Allocate new cursors, and set all to zero initial state. */
3868 free (gms_hint_cursor);
3869 bytes = hint_count * sizeof (*gms_hint_cursor);
3870 gms_hint_cursor = gms_malloc (bytes);
3871 memset (gms_hint_cursor, 0, bytes);
3872
3873 /*
3874 * Retain the hints CRC, for later comparisons, and set is_initialized
3875 * flag.
3876 */
3877 current_crc = crc;
3878 is_initialized = TRUE;
3879 }
3880
3881 /*
3882 * Save the hints array passed in. This is done here since even if the data
3883 * remains the same (found by the CRC check above), the pointer to it might
3884 * have changed.
3885 */
3886 gms_hints = hints;
3887
3888 /*
3889 * Try to create the hints windows. If they can't be created, perhaps
3890 * because the Glk library doesn't support it, the output functions will
3891 * work around this.
3892 */
3893 gms_hint_open ();
3894 gms_hint_menutext_start ();
3895
3896 /*
3897 * Begin hints display at the root node, and navigate until the user exits
3898 * hints.
3899 */
3900 gms_current_hint_node = GMS_HINT_ROOT_NODE;
3901 while (gms_current_hint_node != GMS_HINTS_DONE)
3902 {
3903 event_t event;
3904
3905 assert (gms_current_hint_node < hint_count);
3906 gms_hint_display (gms_hints, gms_hint_cursor, gms_current_hint_node);
3907
3908 /* Get and handle a character key event for hint navigation. */
3909 gms_hint_menutext_char_event (&event);
3910 assert (event.type == evtype_CharInput);
3911 gms_current_hint_node = gms_hint_handle (gms_hints,
3912 gms_hint_cursor,
3913 gms_current_hint_node,
3914 event.val1);
3915 }
3916
3917 /* Done with hint windows. */
3918 gms_hint_menutext_done ();
3919 gms_hint_close ();
3920
3921 return GMS_HINT_SUCCESS;
3922 }
3923
3924
3925 /*
3926 * gms_hint_redraw()
3927 *
3928 * Update the hints windows for the current hint. This function should be
3929 * called from the event handler on resize events, to repaint the hints
3930 * display. It does nothing if no hints windows have been opened, since
3931 * in this case, there's no resize action required -- either we're not in
3932 * the hints subsystem, or hints are being displayed in the main game
3933 * window, for whatever reason.
3934 */
3935 static void
3936 gms_hint_redraw (void)
3937 {
3938 if (gms_hint_windows_available ())
3939 {
3940 assert (gms_hints && gms_hint_cursor);
3941 gms_hint_display (gms_hints, gms_hint_cursor, gms_current_hint_node);
3942 }
3943 }
3944
3945
3946 /*
3947 * gms_hints_cleanup()
3948 *
3949 * Free memory resources allocated by hints functions. Called on game
3950 * end.
3951 */
3952 static void
3953 gms_hints_cleanup (void)
3954 {
3955 free (gms_hint_cursor);
3956 gms_hint_cursor = NULL;
3957
3958 gms_hints = NULL;
3959 gms_current_hint_node = 0;
3960 }
3961
3962
3963 void ms_playmusic(type8 * midi_data, type32 length, type16 tempo)
3964 {
3965 }
3966
3967
3968 /*---------------------------------------------------------------------*/
3969 /* Glk command escape functions */
3970 /*---------------------------------------------------------------------*/
3971
3972 /*
3973 * gms_command_undo()
3974 *
3975 * Stub function for the undo command. The real work is to return the
3976 * undo code to the input functions.
3977 */
3978 static void
3979 gms_command_undo (const char *argument)
3980 {
3981 assert (argument);
3982 }
3983
3984
3985 /*
3986 * gms_command_script()
3987 *
3988 * Turn game output scripting (logging) on and off.
3989 */
3990 static void
3991 gms_command_script (const char *argument)
3992 {
3993 assert (argument);
3994
3995 if (gms_strcasecmp (argument, "on") == 0)
3996 {
3997 frefid_t fileref;
3998
3999 if (gms_transcript_stream)
4000 {
4001 gms_normal_string ("Glk transcript is already on.\n");
4002 return;
4003 }
4004
4005 fileref = glk_fileref_create_by_prompt (fileusage_Transcript
4006 | fileusage_TextMode,
4007 filemode_WriteAppend, 0);
4008 if (!fileref)
4009 {
4010 gms_standout_string ("Glk transcript failed.\n");
4011 return;
4012 }
4013
4014 gms_transcript_stream = glk_stream_open_file (fileref,
4015 filemode_WriteAppend, 0);
4016 glk_fileref_destroy (fileref);
4017 if (!gms_transcript_stream)
4018 {
4019 gms_standout_string ("Glk transcript failed.\n");
4020 return;
4021 }
4022
4023 glk_window_set_echo_stream (gms_main_window, gms_transcript_stream);
4024
4025 gms_normal_string ("Glk transcript is now on.\n");
4026 }
4027
4028 else if (gms_strcasecmp (argument, "off") == 0)
4029 {
4030 if (!gms_transcript_stream)
4031 {
4032 gms_normal_string ("Glk transcript is already off.\n");
4033 return;
4034 }
4035
4036 glk_stream_close (gms_transcript_stream, NULL);
4037 gms_transcript_stream = NULL;
4038
4039 glk_window_set_echo_stream (gms_main_window, NULL);
4040
4041 gms_normal_string ("Glk transcript is now off.\n");
4042 }
4043
4044 else if (strlen (argument) == 0)
4045 {
4046 gms_normal_string ("Glk transcript is ");
4047 gms_normal_string (gms_transcript_stream ? "on" : "off");
4048 gms_normal_string (".\n");
4049 }
4050
4051 else
4052 {
4053 gms_normal_string ("Glk transcript can be ");
4054 gms_standout_string ("on");
4055 gms_normal_string (", or ");
4056 gms_standout_string ("off");
4057 gms_normal_string (".\n");
4058 }
4059 }
4060
4061
4062 /*
4063 * gms_command_inputlog()
4064 *
4065 * Turn game input logging on and off.
4066 */
4067 static void
4068 gms_command_inputlog (const char *argument)
4069 {
4070 assert (argument);
4071
4072 if (gms_strcasecmp (argument, "on") == 0)
4073 {
4074 frefid_t fileref;
4075
4076 if (gms_inputlog_stream)
4077 {
4078 gms_normal_string ("Glk input logging is already on.\n");
4079 return;
4080 }
4081
4082 fileref = glk_fileref_create_by_prompt (fileusage_InputRecord
4083 | fileusage_BinaryMode,
4084 filemode_WriteAppend, 0);
4085 if (!fileref)
4086 {
4087 gms_standout_string ("Glk input logging failed.\n");
4088 return;
4089 }
4090
4091 gms_inputlog_stream = glk_stream_open_file (fileref,
4092 filemode_WriteAppend, 0);
4093 glk_fileref_destroy (fileref);
4094 if (!gms_inputlog_stream)
4095 {
4096 gms_standout_string ("Glk input logging failed.\n");
4097 return;
4098 }
4099
4100 gms_normal_string ("Glk input logging is now on.\n");
4101 }
4102
4103 else if (gms_strcasecmp (argument, "off") == 0)
4104 {
4105 if (!gms_inputlog_stream)
4106 {
4107 gms_normal_string ("Glk input logging is already off.\n");
4108 return;
4109 }
4110
4111 glk_stream_close (gms_inputlog_stream, NULL);
4112 gms_inputlog_stream = NULL;
4113
4114 gms_normal_string ("Glk input log is now off.\n");
4115 }
4116
4117 else if (strlen (argument) == 0)
4118 {
4119 gms_normal_string ("Glk input logging is ");
4120 gms_normal_string (gms_inputlog_stream ? "on" : "off");
4121 gms_normal_string (".\n");
4122 }
4123
4124 else
4125 {
4126 gms_normal_string ("Glk input logging can be ");
4127 gms_standout_string ("on");
4128 gms_normal_string (", or ");
4129 gms_standout_string ("off");
4130 gms_normal_string (".\n");
4131 }
4132 }
4133
4134
4135 /*
4136 * gms_command_readlog()
4137 *
4138 * Set the game input log, to read input from a file.
4139 */
4140 static void
4141 gms_command_readlog (const char *argument)
4142 {
4143 assert (argument);
4144
4145 if (gms_strcasecmp (argument, "on") == 0)
4146 {
4147 frefid_t fileref;
4148
4149 if (gms_readlog_stream)
4150 {
4151 gms_normal_string ("Glk read log is already on.\n");
4152 return;
4153 }
4154
4155 fileref = glk_fileref_create_by_prompt (fileusage_InputRecord
4156 | fileusage_BinaryMode,
4157 filemode_Read, 0);
4158 if (!fileref)
4159 {
4160 gms_standout_string ("Glk read log failed.\n");
4161 return;
4162 }
4163
4164 if (!glk_fileref_does_file_exist (fileref))
4165 {
4166 glk_fileref_destroy (fileref);
4167 gms_standout_string ("Glk read log failed.\n");
4168 return;
4169 }
4170
4171 gms_readlog_stream = glk_stream_open_file (fileref, filemode_Read, 0);
4172 glk_fileref_destroy (fileref);
4173 if (!gms_readlog_stream)
4174 {
4175 gms_standout_string ("Glk read log failed.\n");
4176 return;
4177 }
4178
4179 gms_normal_string ("Glk read log is now on.\n");
4180 }
4181
4182 else if (gms_strcasecmp (argument, "off") == 0)
4183 {
4184 if (!gms_readlog_stream)
4185 {
4186 gms_normal_string ("Glk read log is already off.\n");
4187 return;
4188 }
4189
4190 glk_stream_close (gms_readlog_stream, NULL);
4191 gms_readlog_stream = NULL;
4192
4193 gms_normal_string ("Glk read log is now off.\n");
4194 }
4195
4196 else if (strlen (argument) == 0)
4197 {
4198 gms_normal_string ("Glk read log is ");
4199 gms_normal_string (gms_readlog_stream ? "on" : "off");
4200 gms_normal_string (".\n");
4201 }
4202
4203 else
4204 {
4205 gms_normal_string ("Glk read log can be ");
4206 gms_standout_string ("on");
4207 gms_normal_string (", or ");
4208 gms_standout_string ("off");
4209 gms_normal_string (".\n");
4210 }
4211 }
4212
4213
4214 /*
4215 * gms_command_abbreviations()
4216 *
4217 * Turn abbreviation expansions on and off.
4218 */
4219 static void
4220 gms_command_abbreviations (const char *argument)
4221 {
4222 assert (argument);
4223
4224 if (gms_strcasecmp (argument, "on") == 0)
4225 {
4226 if (gms_abbreviations_enabled)
4227 {
4228 gms_normal_string ("Glk abbreviation expansions are already on.\n");
4229 return;
4230 }
4231
4232 gms_abbreviations_enabled = TRUE;
4233 gms_normal_string ("Glk abbreviation expansions are now on.\n");
4234 }
4235
4236 else if (gms_strcasecmp (argument, "off") == 0)
4237 {
4238 if (!gms_abbreviations_enabled)
4239 {
4240 gms_normal_string ("Glk abbreviation expansions are already off.\n");
4241 return;
4242 }
4243
4244 gms_abbreviations_enabled = FALSE;
4245 gms_normal_string ("Glk abbreviation expansions are now off.\n");
4246 }
4247
4248 else if (strlen (argument) == 0)
4249 {
4250 gms_normal_string ("Glk abbreviation expansions are ");
4251 gms_normal_string (gms_abbreviations_enabled ? "on" : "off");
4252 gms_normal_string (".\n");
4253 }
4254
4255 else
4256 {
4257 gms_normal_string ("Glk abbreviation expansions can be ");
4258 gms_standout_string ("on");
4259 gms_normal_string (", or ");
4260 gms_standout_string ("off");
4261 gms_normal_string (".\n");
4262 }
4263 }
4264
4265
4266 /*
4267 * gms_command_graphics()
4268 *
4269 * Enable or disable graphics more permanently than is done by the main
4270 * interpreter. Also, print out a few brief details about the graphics
4271 * state of the program.
4272 */
4273 static void
4274 gms_command_graphics (const char *argument)
4275 {
4276 assert (argument);
4277
4278 if (!gms_graphics_possible)
4279 {
4280 gms_normal_string ("Glk graphics are not available.\n");
4281 return;
4282 }
4283
4284 if (gms_strcasecmp (argument, "on") == 0)
4285 {
4286 if (gms_graphics_enabled)
4287 {
4288 gms_normal_string ("Glk graphics are already on.\n");
4289 return;
4290 }
4291
4292 gms_graphics_enabled = TRUE;
4293
4294 /* If a picture is loaded, call the restart function to repaint it. */
4295 if (gms_graphics_picture_is_available ())
4296 {
4297 if (!gms_graphics_open ())
4298 {
4299 gms_normal_string ("Glk graphics error.\n");
4300 return;
4301 }
4302 gms_graphics_restart ();
4303 }
4304
4305 gms_normal_string ("Glk graphics are now on.\n");
4306 }
4307
4308 else if (gms_strcasecmp (argument, "off") == 0)
4309 {
4310 if (!gms_graphics_enabled)
4311 {
4312 gms_normal_string ("Glk graphics are already off.\n");
4313 return;
4314 }
4315
4316 /*
4317 * Set graphics to disabled, and stop any graphics processing. Close
4318 * the graphics window.
4319 */
4320 gms_graphics_enabled = FALSE;
4321 gms_graphics_stop ();
4322 gms_graphics_close ();
4323
4324 gms_normal_string ("Glk graphics are now off.\n");
4325 }
4326
4327 else if (strlen (argument) == 0)
4328 {
4329 gms_normal_string ("Glk graphics are available,");
4330 gms_normal_string (gms_graphics_enabled
4331 ? " and enabled.\n" : " but disabled.\n");
4332
4333 if (gms_graphics_picture_is_available ())
4334 {
4335 int width, height, is_animated;
4336
4337 if (gms_graphics_get_picture_details (&width, &height, &is_animated))
4338 {
4339 char buffer[16];
4340
4341 gms_normal_string ("There is ");
4342 gms_normal_string (is_animated ? "an animated" : "a");
4343 gms_normal_string (" picture loaded, ");
4344
4345 sprintf (buffer, "%d", width);
4346 gms_normal_string (buffer);
4347 gms_normal_string (" by ");
4348
4349 sprintf (buffer, "%d", height);
4350 gms_normal_string (buffer);
4351
4352 gms_normal_string (" pixels.\n");
4353 }
4354 }
4355
4356 if (!gms_graphics_interpreter_enabled ())
4357 gms_normal_string ("Interpreter graphics are disabled.\n");
4358
4359 if (gms_graphics_enabled && gms_graphics_are_displayed ())
4360 {
4361 int color_count, is_active;
4362 const char *gamma;
4363
4364 if (gms_graphics_get_rendering_details (&gamma, &color_count,
4365 &is_active))
4366 {
4367 char buffer[16];
4368
4369 gms_normal_string ("Graphics are ");
4370 gms_normal_string (is_active ? "active, " : "displayed, ");
4371
4372 sprintf (buffer, "%d", color_count);
4373 gms_normal_string (buffer);
4374 gms_normal_string (" colours");
4375
4376 if (gms_gamma_mode == GAMMA_OFF)
4377 gms_normal_string (", without gamma correction");
4378 else
4379 {
4380 gms_normal_string (", with gamma ");
4381 gms_normal_string (gamma);
4382 gms_normal_string (" correction");
4383 }
4384 gms_normal_string (".\n");
4385 }
4386 else
4387 gms_normal_string ("Graphics are being displayed.\n");
4388 }
4389
4390 if (gms_graphics_enabled && !gms_graphics_are_displayed ())
4391 gms_normal_string ("Graphics are not being displayed.\n");
4392 }
4393
4394 else
4395 {
4396 gms_normal_string ("Glk graphics can be ");
4397 gms_standout_string ("on");
4398 gms_normal_string (", or ");
4399 gms_standout_string ("off");
4400 gms_normal_string (".\n");
4401 }
4402 }
4403
4404
4405 /*
4406 * gms_command_gamma()
4407 *
4408 * Enable or disable picture gamma corrections.
4409 */
4410 static void
4411 gms_command_gamma (const char *argument)
4412 {
4413 assert (argument);
4414
4415 if (!gms_graphics_possible)
4416 {
4417 gms_normal_string ("Glk automatic gamma correction is not available.\n");
4418 return;
4419 }
4420
4421 if (gms_strcasecmp (argument, "high") == 0)
4422 {
4423 if (gms_gamma_mode == GAMMA_HIGH)
4424 {
4425 gms_normal_string ("Glk automatic gamma correction mode is"
4426 " already 'high'.\n");
4427 return;
4428 }
4429
4430 gms_gamma_mode = GAMMA_HIGH;
4431 gms_graphics_restart ();
4432
4433 gms_normal_string ("Glk automatic gamma correction mode is"
4434 " now 'high'.\n");
4435 }
4436
4437 else if (gms_strcasecmp (argument, "normal") == 0
4438 || gms_strcasecmp (argument, "on") == 0)
4439 {
4440 if (gms_gamma_mode == GAMMA_NORMAL)
4441 {
4442 gms_normal_string ("Glk automatic gamma correction mode is"
4443 " already 'normal'.\n");
4444 return;
4445 }
4446
4447 gms_gamma_mode = GAMMA_NORMAL;
4448 gms_graphics_restart ();
4449
4450 gms_normal_string ("Glk automatic gamma correction mode is"
4451 " now 'normal'.\n");
4452 }
4453
4454 else if (gms_strcasecmp (argument, "none") == 0
4455 || gms_strcasecmp (argument, "off") == 0)
4456 {
4457 if (gms_gamma_mode == GAMMA_OFF)
4458 {
4459 gms_normal_string ("Glk automatic gamma correction mode is"
4460 " already 'off'.\n");
4461 return;
4462 }
4463
4464 gms_gamma_mode = GAMMA_OFF;
4465 gms_graphics_restart ();
4466
4467 gms_normal_string ("Glk automatic gamma correction mode is"
4468 " now 'off'.\n");
4469 }
4470
4471 else if (strlen (argument) == 0)
4472 {
4473 gms_normal_string ("Glk automatic gamma correction mode is '");
4474 switch (gms_gamma_mode)
4475 {
4476 case GAMMA_OFF:
4477 gms_normal_string ("off");
4478 break;
4479 case GAMMA_NORMAL:
4480 gms_normal_string ("normal");
4481 break;
4482 case GAMMA_HIGH:
4483 gms_normal_string ("high");
4484 break;
4485 }
4486 gms_normal_string ("'.\n");
4487 }
4488
4489 else
4490 {
4491 gms_normal_string ("Glk automatic gamma correction mode can be ");
4492 gms_standout_string ("high");
4493 gms_normal_string (", ");
4494 gms_standout_string ("normal");
4495 gms_normal_string (", or ");
4496 gms_standout_string ("off");
4497 gms_normal_string (".\n");
4498 }
4499 }
4500
4501
4502 /*
4503 * gms_command_animations()
4504 *
4505 * Enable or disable picture animations.
4506 */
4507 static void
4508 gms_command_animations (const char *argument)
4509 {
4510 assert (argument);
4511
4512 if (!gms_graphics_possible)
4513 {
4514 gms_normal_string ("Glk graphics animations are not available.\n");
4515 return;
4516 }
4517
4518 if (gms_strcasecmp (argument, "on") == 0)
4519 {
4520 int is_animated;
4521
4522 if (gms_animation_enabled)
4523 {
4524 gms_normal_string ("Glk graphics animations are already on.\n");
4525 return;
4526 }
4527
4528 /*
4529 * Set animation to on, and restart graphics if the current picture
4530 * is animated; if it isn't, we can leave it displayed as is, since
4531 * changing animation mode doesn't affect this picture.
4532 */
4533 gms_animation_enabled = TRUE;
4534 if (gms_graphics_get_picture_details (NULL, NULL, &is_animated))
4535 {
4536 if (is_animated)
4537 gms_graphics_restart ();
4538 }
4539
4540 gms_normal_string ("Glk graphics animations are now on.\n");
4541 }
4542
4543 else if (gms_strcasecmp (argument, "off") == 0)
4544 {
4545 int is_animated;
4546
4547 if (!gms_animation_enabled)
4548 {
4549 gms_normal_string ("Glk graphics animations are already off.\n");
4550 return;
4551 }
4552
4553 gms_animation_enabled = FALSE;
4554 if (gms_graphics_get_picture_details (NULL, NULL, &is_animated))
4555 {
4556 if (is_animated)
4557 gms_graphics_restart ();
4558 }
4559
4560 gms_normal_string ("Glk graphics animations are now off.\n");
4561 }
4562
4563 else if (strlen (argument) == 0)
4564 {
4565 gms_normal_string ("Glk graphics animations are ");
4566 gms_normal_string (gms_animation_enabled ? "on" : "off");
4567 gms_normal_string (".\n");
4568 }
4569
4570 else
4571 {
4572 gms_normal_string ("Glk graphics animations can be ");
4573 gms_standout_string ("on");
4574 gms_normal_string (", or ");
4575 gms_standout_string ("off");
4576 gms_normal_string (".\n");
4577 }
4578 }
4579
4580
4581 /*
4582 * gms_command_prompts()
4583 *
4584 * Turn the extra "> " prompt output on and off.
4585 */
4586 static void
4587 gms_command_prompts (const char *argument)
4588 {
4589 assert (argument);
4590
4591 if (gms_strcasecmp (argument, "on") == 0)
4592 {
4593 if (gms_prompt_enabled)
4594 {
4595 gms_normal_string ("Glk extra prompts are already on.\n");
4596 return;
4597 }
4598
4599 gms_prompt_enabled = TRUE;
4600 gms_normal_string ("Glk extra prompts are now on.\n");
4601
4602 /* Check for a game prompt to clear the flag. */
4603 gms_game_prompted ();
4604 }
4605
4606 else if (gms_strcasecmp (argument, "off") == 0)
4607 {
4608 if (!gms_prompt_enabled)
4609 {
4610 gms_normal_string ("Glk extra prompts are already off.\n");
4611 return;
4612 }
4613
4614 gms_prompt_enabled = FALSE;
4615 gms_normal_string ("Glk extra prompts are now off.\n");
4616 }
4617
4618 else if (strlen (argument) == 0)
4619 {
4620 gms_normal_string ("Glk extra prompts are ");
4621 gms_normal_string (gms_prompt_enabled ? "on" : "off");
4622 gms_normal_string (".\n");
4623 }
4624
4625 else
4626 {
4627 gms_normal_string ("Glk extra prompts can be ");
4628 gms_standout_string ("on");
4629 gms_normal_string (", or ");
4630 gms_standout_string ("off");
4631 gms_normal_string (".\n");
4632 }
4633 }
4634
4635
4636 /*
4637 * gms_command_print_version_number()
4638 * gms_command_version()
4639 *
4640 * Print out the Glk library version number.
4641 */
4642 static void
4643 gms_command_print_version_number (glui32 version)
4644 {
4645 char buffer[64];
4646
4647 sprintf (buffer, "%lu.%lu.%lu",
4648 (unsigned long) version >> 16,
4649 (unsigned long) (version >> 8) & 0xff,
4650 (unsigned long) version & 0xff);
4651 gms_normal_string (buffer);
4652 }
4653
4654 static void
4655 gms_command_version (const char *argument)
4656 {
4657 glui32 version;
4658 assert (argument);
4659
4660 gms_normal_string ("This is version ");
4661 gms_command_print_version_number (GMS_PORT_VERSION);
4662 gms_normal_string (" of the Glk Magnetic port.\n");
4663
4664 version = glk_gestalt (gestalt_Version, 0);
4665 gms_normal_string ("The Glk library version is ");
4666 gms_command_print_version_number (version);
4667 gms_normal_string (".\n");
4668 }
4669
4670
4671 /*
4672 * gms_command_commands()
4673 *
4674 * Turn command escapes off. Once off, there's no way to turn them back on.
4675 * Commands must be on already to enter this function.
4676 */
4677 static void
4678 gms_command_commands (const char *argument)
4679 {
4680 assert (argument);
4681
4682 if (gms_strcasecmp (argument, "on") == 0)
4683 {
4684 gms_normal_string ("Glk commands are already on.\n");
4685 }
4686
4687 else if (gms_strcasecmp (argument, "off") == 0)
4688 {
4689 gms_commands_enabled = FALSE;
4690 gms_normal_string ("Glk commands are now off.\n");
4691 }
4692
4693 else if (strlen (argument) == 0)
4694 {
4695 gms_normal_string ("Glk commands are ");
4696 gms_normal_string (gms_commands_enabled ? "on" : "off");
4697 gms_normal_string (".\n");
4698 }
4699
4700 else
4701 {
4702 gms_normal_string ("Glk commands can be ");
4703 gms_standout_string ("on");
4704 gms_normal_string (", or ");
4705 gms_standout_string ("off");
4706 gms_normal_string (".\n");
4707 }
4708 }
4709
4710
4711 /*
4712 * gms_command_license()
4713 *
4714 * Print licensing terms.
4715 */
4716 static void
4717 gms_command_license (const char *argument)
4718 {
4719 assert (argument);
4720
4721 gms_normal_string ("This program is free software; you can redistribute it"
4722 " and/or modify it under the terms of version 2 of the"
4723 " GNU General Public License as published by the Free"
4724 " Software Foundation.\n\n");
4725
4726 gms_normal_string ("This program is distributed in the hope that it will be"
4727 " useful, but ");
4728 gms_standout_string ("WITHOUT ANY WARRANTY");
4729 gms_normal_string ("; without even the implied warranty of ");
4730 gms_standout_string ("MERCHANTABILITY");
4731 gms_normal_string (" or ");
4732 gms_standout_string ("FITNESS FOR A PARTICULAR PURPOSE");
4733 gms_normal_string (". See the GNU General Public License for more"
4734 " details.\n\n");
4735
4736 gms_normal_string ("You should have received a copy of the GNU General"
4737 " Public License along with this program; if not, write"
4738 " to the Free Software Foundation, Inc., 59 Temple"
4739 " Place, Suite 330, Boston, MA 02111-1307 USA\n\n");
4740
4741 gms_normal_string ("Please report any bugs, omissions, or misfeatures to ");
4742 gms_standout_string ("[email protected]");
4743 gms_normal_string (".\n");
4744 }
4745
4746
4747 /* Glk subcommands and handler functions. */
4748 typedef const struct
4749 {
4750 const char * const command; /* Glk subcommand. */
4751 void (* const handler) (const char *argument); /* Subcommand handler. */
4752 const int takes_argument; /* Argument flag. */
4753 const int undo_return; /* "Undo" return value. */
4754 } gms_command_t;
4755 typedef gms_command_t *gms_commandref_t;
4756
4757 static void gms_command_summary (const char *argument);
4758 static void gms_command_help (const char *argument);
4759
4760 static gms_command_t GMS_COMMAND_TABLE[] = {
4761 {"summary", gms_command_summary, FALSE, FALSE},
4762 {"undo", gms_command_undo, FALSE, TRUE},
4763 {"script", gms_command_script, TRUE, FALSE},
4764 {"inputlog", gms_command_inputlog, TRUE, FALSE},
4765 {"readlog", gms_command_readlog, TRUE, FALSE},
4766 {"abbreviations", gms_command_abbreviations, TRUE, FALSE},
4767 {"graphics", gms_command_graphics, TRUE, FALSE},
4768 {"gamma", gms_command_gamma, TRUE, FALSE},
4769 {"animations", gms_command_animations, TRUE, FALSE},
4770 {"prompts", gms_command_prompts, TRUE, FALSE},
4771 {"version", gms_command_version, FALSE, FALSE},
4772 {"commands", gms_command_commands, TRUE, FALSE},
4773 {"license", gms_command_license, FALSE, FALSE},
4774 {"help", gms_command_help, TRUE, FALSE},
4775 {NULL, NULL, FALSE, FALSE}
4776 };
4777
4778
4779 /*
4780 * gms_command_summary()
4781 *
4782 * Report all current Glk settings.
4783 */
4784 static void
4785 gms_command_summary (const char *argument)
4786 {
4787 gms_commandref_t entry;
4788 assert (argument);
4789
4790 /*
4791 * Call handlers that have status to report with an empty argument,
4792 * prompting each to print its current setting.
4793 */
4794 for (entry = GMS_COMMAND_TABLE; entry->command; entry++)
4795 {
4796 if (entry->handler == gms_command_summary
4797 || entry->handler == gms_command_undo
4798 || entry->handler == gms_command_license
4799 || entry->handler == gms_command_help)
4800 continue;
4801
4802 entry->handler ("");
4803 }
4804 }
4805
4806
4807 /*
4808 * gms_command_help()
4809 *
4810 * Document the available Glk commands.
4811 */
4812 static void
4813 gms_command_help (const char *command)
4814 {
4815 gms_commandref_t entry, matched;
4816 assert (command);
4817
4818 if (strlen (command) == 0)
4819 {
4820 gms_normal_string ("Glk commands are");
4821 for (entry = GMS_COMMAND_TABLE; entry->command; entry++)
4822 {
4823 gms_commandref_t next;
4824
4825 next = entry + 1;
4826 gms_normal_string (next->command ? " " : " and ");
4827 gms_standout_string (entry->command);
4828 gms_normal_string (next->command ? "," : ".\n\n");
4829 }
4830
4831 gms_normal_string ("Glk commands may be abbreviated, as long as"
4832 " the abbreviation is unambiguous. Use ");
4833 gms_standout_string ("glk help");
4834 gms_normal_string (" followed by a Glk command name for help on that"
4835 " command.\n");
4836 return;
4837 }
4838
4839 matched = NULL;
4840 for (entry = GMS_COMMAND_TABLE; entry->command; entry++)
4841 {
4842 if (gms_strncasecmp (command, entry->command, strlen (command)) == 0)
4843 {
4844 if (matched)
4845 {
4846 gms_normal_string ("The Glk command ");
4847 gms_standout_string (command);
4848 gms_normal_string (" is ambiguous. Try ");
4849 gms_standout_string ("glk help");
4850 gms_normal_string (" for more information.\n");
4851 return;
4852 }
4853 matched = entry;
4854 }
4855 }
4856 if (!matched)
4857 {
4858 gms_normal_string ("The Glk command ");
4859 gms_standout_string (command);
4860 gms_normal_string (" is not valid. Try ");
4861 gms_standout_string ("glk help");
4862 gms_normal_string (" for more information.\n");
4863 return;
4864 }
4865
4866 if (matched->handler == gms_command_summary)
4867 {
4868 gms_normal_string ("Prints a summary of all the current Glk Magnetic"
4869 " settings.\n");
4870 }
4871
4872 else if (matched->handler == gms_command_undo)
4873 {
4874 gms_normal_string ("Undoes a single game turn.\n\nEquivalent to the"
4875 " standalone game 'undo' command.\n");
4876 }
4877
4878 else if (matched->handler == gms_command_script)
4879 {
4880 gms_normal_string ("Logs the game's output to a file.\n\nUse ");
4881 gms_standout_string ("glk script on");
4882 gms_normal_string (" to begin logging game output, and ");
4883 gms_standout_string ("glk script off");
4884 gms_normal_string (" to end it. Glk Magnetic will ask you for a file"
4885 " when you turn scripts on.\n");
4886 }
4887
4888 else if (matched->handler == gms_command_inputlog)
4889 {
4890 gms_normal_string ("Records the commands you type into a game.\n\nUse ");
4891 gms_standout_string ("glk inputlog on");
4892 gms_normal_string (", to begin recording your commands, and ");
4893 gms_standout_string ("glk inputlog off");
4894 gms_normal_string (" to turn off input logs. You can play back"
4895 " recorded commands into a game with the ");
4896 gms_standout_string ("glk readlog");
4897 gms_normal_string (" command.\n");
4898 }
4899
4900 else if (matched->handler == gms_command_readlog)
4901 {
4902 gms_normal_string ("Plays back commands recorded with ");
4903 gms_standout_string ("glk inputlog on");
4904 gms_normal_string (".\n\nUse ");
4905 gms_standout_string ("glk readlog on");
4906 gms_normal_string (". Command play back stops at the end of the"
4907 " file. You can also play back commands from a"
4908 " text file created using any standard editor.\n");
4909 }
4910
4911 else if (matched->handler == gms_command_abbreviations)
4912 {
4913 gms_normal_string ("Controls abbreviation expansion.\n\nGlk Magnetic"
4914 " automatically expands several standard single"
4915 " letter abbreviations for you; for example, \"x\""
4916 " becomes \"examine\". Use ");
4917 gms_standout_string ("glk abbreviations on");
4918 gms_normal_string (" to turn this feature on, and ");
4919 gms_standout_string ("glk abbreviations off");
4920 gms_normal_string (" to turn it off. While the feature is on, you"
4921 " can bypass abbreviation expansion for an"
4922 " individual game command by prefixing it with a"
4923 " single quote.\n");
4924 }
4925
4926 else if (matched->handler == gms_command_graphics)
4927 {
4928 gms_normal_string ("Turns interpreter graphics on and off.\n\nUse ");
4929 gms_standout_string ("glk graphics on");
4930 gms_normal_string (" to enable interpreter graphics, and ");
4931 gms_standout_string ("glk graphics off");
4932 gms_normal_string (" to turn graphics off and close the graphics window."
4933 " This control works slightly differently to the"
4934 " 'graphics' command in Magnetic Windows and Magnetic"
4935 " Scrolls games themselves; the game's 'graphics'"
4936 " command may disable new images, but leave old ones"
4937 " displayed. For graphics to be displayed, they"
4938 " must be turned on in both the game and the"
4939 " interpreter.\n");
4940 }
4941
4942 else if (matched->handler == gms_command_gamma)
4943 {
4944 gms_normal_string ("Sets the level of automatic gamma correction applied"
4945 " to game graphics.\n\nUse ");
4946 gms_standout_string ("glk gamma normal");
4947 gms_normal_string (" to set moderate automatic colour contrast"
4948 " correction, ");
4949 gms_standout_string ("glk gamma high");
4950 gms_normal_string (" to set high automatic colour contrast correction,"
4951 " or ");
4952 gms_standout_string ("glk gamma off");
4953 gms_normal_string (" to turn off all automatic gamma correction.\n");
4954 }
4955
4956 else if (matched->handler == gms_command_animations)
4957 {
4958 gms_normal_string ("Turns graphic animations on and off.\n\nUse ");
4959 gms_standout_string ("glk animation on");
4960 gms_normal_string (" to enable animations, or ");
4961 gms_standout_string ("glk animation off");
4962 gms_normal_string (" to turn animations off. Not all game graphics are"
4963 " animated, so this control works only on graphics"
4964 " that are animated. When animation is off, Glk"
4965 " Magnetic displays only the static portions of a"
4966 " game's pictures.\n");
4967 }
4968
4969 else if (matched->handler == gms_command_prompts)
4970 {
4971 gms_normal_string ("Controls extra input prompting.\n\n"
4972 "Glk Magnetic can issue a replacement '>' input"
4973 " prompt if it detects that the game hasn't prompted"
4974 " after, say, an empty input line. Use ");
4975 gms_standout_string ("glk prompts on");
4976 gms_normal_string (" to turn this feature on, and ");
4977 gms_standout_string ("glk prompts off");
4978 gms_normal_string (" to turn it off.\n");
4979 }
4980
4981 else if (matched->handler == gms_command_version)
4982 {
4983 gms_normal_string ("Prints the version numbers of the Glk library"
4984 " and the Glk Magnetic port.\n");
4985 }
4986
4987 else if (matched->handler == gms_command_commands)
4988 {
4989 gms_normal_string ("Turn off Glk commands.\n\nUse ");
4990 gms_standout_string ("glk commands off");
4991 gms_normal_string (" to disable all Glk commands, including this one."
4992 " Once turned off, there is no way to turn Glk"
4993 " commands back on while inside the game.\n");
4994 }
4995
4996 else if (matched->handler == gms_command_license)
4997 {
4998 gms_normal_string ("Prints Glk Magnetic's software license.\n");
4999 }
5000
5001 else if (matched->handler == gms_command_help)
5002 gms_command_help ("");
5003
5004 else
5005 gms_normal_string ("There is no help available on that Glk command."
5006 " Sorry.\n");
5007 }
5008
5009
5010 /*
5011 * gms_command_escape()
5012 *
5013 * This function is handed each input line. If the line contains a specific
5014 * Glk port command, handle it and return TRUE, otherwise return FALSE.
5015 *
5016 * On unambiguous returns, it will also set the value for undo_command to the
5017 * table undo return value.
5018 */
5019 static int
5020 gms_command_escape (const char *string, int *undo_command)
5021 {
5022 int posn;
5023 char *string_copy, *command, *argument;
5024 assert (string && undo_command);
5025
5026 /*
5027 * Return FALSE if the string doesn't begin with the Glk command escape
5028 * introducer.
5029 */
5030 posn = strspn (string, "\t ");
5031 if (gms_strncasecmp (string + posn, "glk", strlen ("glk")) != 0)
5032 return FALSE;
5033
5034 /* Take a copy of the string, without any leading space or introducer. */
5035 string_copy = gms_malloc (strlen (string + posn) + 1 - strlen ("glk"));
5036 strcpy (string_copy, string + posn + strlen ("glk"));
5037
5038 /*
5039 * Find the subcommand; the first word in the string copy. Find its end,
5040 * and ensure it terminates with a NUL.
5041 */
5042 posn = strspn (string_copy, "\t ");
5043 command = string_copy + posn;
5044 posn += strcspn (string_copy + posn, "\t ");
5045 if (string_copy[posn] != '\0')
5046 string_copy[posn++] = '\0';
5047
5048 /*
5049 * Now find any argument data for the command, ensuring it too terminates
5050 * with a NUL.
5051 */
5052 posn += strspn (string_copy + posn, "\t ");
5053 argument = string_copy + posn;
5054 posn += strcspn (string_copy + posn, "\t ");
5055 string_copy[posn] = '\0';
5056
5057 /*
5058 * Try to handle the command and argument as a Glk subcommand. If it
5059 * doesn't run unambiguously, print command usage. Treat an empty command
5060 * as "help".
5061 */
5062 if (strlen (command) > 0)
5063 {
5064 gms_commandref_t entry, matched;
5065 int matches;
5066
5067 /*
5068 * Search for the first unambiguous table command string matching
5069 * the command passed in.
5070 */
5071 matches = 0;
5072 matched = NULL;
5073 for (entry = GMS_COMMAND_TABLE; entry->command; entry++)
5074 {
5075 if (gms_strncasecmp (command, entry->command, strlen (command)) == 0)
5076 {
5077 matches++;
5078 matched = entry;
5079 }
5080 }
5081
5082 /* If the match was unambiguous, call the command handler. */
5083 if (matches == 1)
5084 {
5085 if (!matched->undo_return)
5086 gms_normal_char ('\n');
5087 matched->handler (argument);
5088
5089 if (!matched->takes_argument && strlen (argument) > 0)
5090 {
5091 gms_normal_string ("[The ");
5092 gms_standout_string (matched->command);
5093 gms_normal_string (" command ignores arguments.]\n");
5094 }
5095
5096 *undo_command = matched->undo_return;
5097 }
5098
5099 /* No match, or the command was ambiguous. */
5100 else
5101 {
5102 gms_normal_string ("\nThe Glk command ");
5103 gms_standout_string (command);
5104 gms_normal_string (" is ");
5105 gms_normal_string (matches == 0 ? "not valid" : "ambiguous");
5106 gms_normal_string (". Try ");
5107 gms_standout_string ("glk help");
5108 gms_normal_string (" for more information.\n");
5109 }
5110 }
5111 else
5112 {
5113 gms_normal_char ('\n');
5114 gms_command_help ("");
5115 }
5116
5117 /* The string contained a Glk command; return TRUE. */
5118 free (string_copy);
5119 return TRUE;
5120 }
5121
5122
5123 /*
5124 * gms_command_undo_special()
5125 *
5126 * This function makes a special case of the input line containing the single
5127 * word "undo", treating it as if it is "glk undo". This makes life a bit
5128 * more convenient for the player, since it's the same behavior that most
5129 * other IF systems have. It returns TRUE if "undo" found, FALSE otherwise.
5130 */
5131 static int
5132 gms_command_undo_special (const char *string)
5133 {
5134 int posn, end;
5135 assert (string);
5136
5137 /* Find the start and end of the first string word. */
5138 posn = strspn (string, "\t ");
5139 end = posn + strcspn (string + posn, "\t ");
5140
5141 /* See if string contains an "undo" request, with nothing following. */
5142 if (end - posn == strlen ("undo")
5143 && gms_strncasecmp (string + posn, "undo", end - posn) == 0)
5144 {
5145 posn = end + strspn (string + end, "\t ");
5146 if (string[posn] == '\0')
5147 return TRUE;
5148 }
5149
5150 return FALSE;
5151 }
5152
5153
5154 /*---------------------------------------------------------------------*/
5155 /* Glk port input functions */
5156 /*---------------------------------------------------------------------*/
5157
5158 /*
5159 * Input buffer allocated for reading input lines. The buffer is filled
5160 * from either an input log, if one is currently being read, or from Glk
5161 * line input. We also need an "undo" notification flag.
5162 */
5163 enum { GMS_INPUTBUFFER_LENGTH = 256 };
5164 static char gms_input_buffer[GMS_INPUTBUFFER_LENGTH];
5165 static int gms_input_length = 0,
5166 gms_input_cursor = 0,
5167 gms_undo_notification = FALSE;
5168
5169 /* Table of single-character command abbreviations. */
5170 typedef const struct
5171 {
5172 const char abbreviation; /* Abbreviation character. */
5173 const char * const expansion; /* Expansion string. */
5174 } gms_abbreviation_t;
5175 typedef gms_abbreviation_t *gms_abbreviationref_t;
5176
5177 static gms_abbreviation_t GMS_ABBREVIATIONS[] = {
5178 {'c', "close"}, {'g', "again"}, {'i', "inventory"},
5179 {'k', "attack"}, {'l', "look"}, {'p', "open"},
5180 {'q', "quit"}, {'r', "drop"}, {'t', "take"},
5181 {'x', "examine"}, {'y', "yes"}, {'z', "wait"},
5182 {'\0', NULL}
5183 };
5184
5185
5186 /*
5187 * gms_expand_abbreviations()
5188 *
5189 * Expand a few common one-character abbreviations commonly found in other
5190 * game systems, but not always normal in Magnetic Scrolls games.
5191 */
5192 static void
5193 gms_expand_abbreviations (char *buffer, int size)
5194 {
5195 char *command, abbreviation;
5196 const char *expansion;
5197 gms_abbreviationref_t entry;
5198 assert (buffer);
5199
5200 /* Ignore anything that isn't a single letter command. */
5201 command = buffer + strspn (buffer, "\t ");
5202 if (!(strlen (command) == 1
5203 || (strlen (command) > 1 && isspace (command[1]))))
5204 return;
5205
5206 /* Scan the abbreviations table for a match. */
5207 abbreviation = glk_char_to_lower ((unsigned char) command[0]);
5208 expansion = NULL;
5209 for (entry = GMS_ABBREVIATIONS; entry->expansion; entry++)
5210 {
5211 if (entry->abbreviation == abbreviation)
5212 {
5213 expansion = entry->expansion;
5214 break;
5215 }
5216 }
5217
5218 /*
5219 * If a match found, check for a fit, then replace the character with the
5220 * expansion string.
5221 */
5222 if (expansion)
5223 {
5224 if (strlen (buffer) + strlen (expansion) - 1 >= size)
5225 return;
5226
5227 memmove (command + strlen (expansion) - 1, command, strlen (command) + 1);
5228 memcpy (command, expansion, strlen (expansion));
5229
5230 #ifndef GARGLK
5231 gms_standout_string ("[");
5232 gms_standout_char (abbreviation);
5233 gms_standout_string (" -> ");
5234 gms_standout_string (expansion);
5235 gms_standout_string ("]\n");
5236 #endif
5237 }
5238 }
5239
5240
5241 /*
5242 * gms_buffer_input
5243 *
5244 * Read and buffer a line of input. If there is an input log active, then
5245 * data is taken by reading this first. Otherwise, the function gets a
5246 * line from Glk.
5247 *
5248 * It also makes special cases of some lines read from the user, either
5249 * handling commands inside them directly, or expanding abbreviations as
5250 * appropriate. This is not reflected in the buffer, which is adjusted as
5251 * required before returning.
5252 */
5253 static void
5254 gms_buffer_input (void)
5255 {
5256 event_t event;
5257
5258 /*
5259 * Update the current status line display, and flush any pending buffered
5260 * output.
5261 */
5262 gms_status_notify ();
5263 gms_output_flush ();
5264
5265 /*
5266 * Magnetic Windows games tend not to issue a prompt after reading an empty
5267 * line of input. This can make for a very blank looking screen.
5268 *
5269 * To slightly improve things, if it looks like we didn't get a prompt from
5270 * the game, do our own.
5271 */
5272 if (gms_prompt_enabled && !gms_game_prompted ())
5273 {
5274 gms_normal_char ('\n');
5275 gms_normal_string (GMS_INPUT_PROMPT);
5276 }
5277
5278 /*
5279 * If we have an input log to read from, use that until it is exhausted. On
5280 * end of file, close the stream and resume input from line requests.
5281 */
5282 if (gms_readlog_stream)
5283 {
5284 glui32 chars;
5285
5286 /* Get the next line from the log stream. */
5287 chars = glk_get_line_stream (gms_readlog_stream,
5288 gms_input_buffer, sizeof (gms_input_buffer));
5289 if (chars > 0)
5290 {
5291 /* Echo the line just read in input style. */
5292 glk_set_style (style_Input);
5293 glk_put_buffer (gms_input_buffer, chars);
5294 glk_set_style (style_Normal);
5295
5296 /* Note how many characters buffered, and return. */
5297 gms_input_length = chars;
5298 return;
5299 }
5300
5301 /*
5302 * We're at the end of the log stream. Close it, and then continue
5303 * on to request a line from Glk.
5304 */
5305 glk_stream_close (gms_readlog_stream, NULL);
5306 gms_readlog_stream = NULL;
5307 }
5308
5309 /*
5310 * No input log being read, or we just hit the end of file on one. Revert
5311 * to normal line input; start by getting a new line from Glk.
5312 */
5313 glk_request_line_event (gms_main_window,
5314 gms_input_buffer, sizeof (gms_input_buffer) - 1, 0);
5315 gms_event_wait (evtype_LineInput, &event);
5316
5317 /* Terminate the input line with a NUL. */
5318 assert (event.val1 <= sizeof (gms_input_buffer) - 1);
5319 gms_input_buffer[event.val1] = '\0';
5320
5321 /* Special handling for "undo" commands. */
5322 if (gms_command_undo_special (gms_input_buffer))
5323 {
5324 /* Write the "undo" to any input log. */
5325 if (gms_inputlog_stream)
5326 {
5327 glk_put_string_stream (gms_inputlog_stream, gms_input_buffer);
5328 glk_put_char_stream (gms_inputlog_stream, '\n');
5329 }
5330
5331 /* Overwrite buffer with an empty line if we saw "undo". */
5332 gms_input_buffer[0] = '\n';
5333 gms_input_length = 1;
5334
5335 gms_undo_notification = TRUE;
5336 return;
5337 }
5338
5339 /*
5340 * If neither abbreviations nor local commands are enabled, use the data
5341 * read above without further massaging.
5342 */
5343 if (gms_abbreviations_enabled || gms_commands_enabled)
5344 {
5345 char *command;
5346
5347 /*
5348 * If the first non-space input character is a quote, bypass all
5349 * abbreviation expansion and local command recognition, and use the
5350 * unadulterated input, less introductory quote.
5351 */
5352 command = gms_input_buffer + strspn (gms_input_buffer, "\t ");
5353 if (command[0] == '\'')
5354 {
5355 /* Delete the quote with memmove(). */
5356 memmove (command, command + 1, strlen (command));
5357 }
5358 else
5359 {
5360 /* Check for, and expand, any abbreviated commands. */
5361 if (gms_abbreviations_enabled)
5362 {
5363 gms_expand_abbreviations (gms_input_buffer,
5364 sizeof (gms_input_buffer));
5365 }
5366
5367 /*
5368 * Check for standalone "help", then for Glk port special commands;
5369 * suppress the interpreter's use of this input for Glk commands
5370 * by overwriting the line with a single newline character.
5371 */
5372 if (gms_commands_enabled)
5373 {
5374 int posn;
5375
5376 posn = strspn (gms_input_buffer, "\t ");
5377 if (gms_strncasecmp (gms_input_buffer + posn,
5378 "help", strlen ("help"))== 0)
5379 {
5380 if (strspn (gms_input_buffer + posn + strlen ("help"), "\t ")
5381 == strlen (gms_input_buffer + posn + strlen ("help")))
5382 {
5383 gms_output_register_help_request ();
5384 }
5385 }
5386
5387 if (gms_command_escape (gms_input_buffer,
5388 &gms_undo_notification))
5389 {
5390 gms_output_silence_help_hints ();
5391 gms_input_buffer[0] = '\n';
5392 gms_input_length = 1;
5393 return;
5394 }
5395 }
5396 }
5397 }
5398
5399 /*
5400 * If there is an input log active, log this input string to it. Note that
5401 * by logging here we get any abbreviation expansions but we won't log glk
5402 * special commands, nor any input read from a current open input log.
5403 */
5404 if (gms_inputlog_stream)
5405 {
5406 glk_put_string_stream (gms_inputlog_stream, gms_input_buffer);
5407 glk_put_char_stream (gms_inputlog_stream, '\n');
5408 }
5409
5410 /*
5411 * Now append a newline to the buffer, since Glk line input doesn't provide
5412 * one, and in any case, abbreviation expansion may have edited the buffer
5413 * contents (and in particular, changed the length).
5414 */
5415 gms_input_buffer[strlen (gms_input_buffer) + 1] = '\0';
5416 gms_input_buffer[strlen (gms_input_buffer)] = '\n';
5417
5418 /* Note how many characters are buffered after all of the above. */
5419 gms_input_length = strlen (gms_input_buffer);
5420 }
5421
5422
5423 /*
5424 * ms_getchar()
5425 *
5426 * Return the single next character to the interpreter. This function
5427 * extracts characters from the input buffer until empty, when it then
5428 * tries to buffer more data.
5429 */
5430 type8
5431 ms_getchar (type8 trans)
5432 {
5433 /* See if we are at the end of the input buffer. */
5434 if (gms_input_cursor == gms_input_length)
5435 {
5436 /*
5437 * Try to read in more data, and rewind buffer cursor. As well as
5438 * reading input, this may set an undo notification.
5439 */
5440 gms_buffer_input ();
5441 gms_input_cursor = 0;
5442
5443 if (gms_undo_notification)
5444 {
5445 /*
5446 * Clear the undo notification, and discard buffered input (usually
5447 * just the '\n' placed there when the undo command was recognized).
5448 */
5449 gms_undo_notification = FALSE;
5450 gms_input_length = 0;
5451
5452 /*
5453 * Return the special 0, or a blank line if no undo is allowed at
5454 * this point.
5455 */
5456 return trans ? 0 : '\n';
5457 }
5458 }
5459
5460 /* Return the next character from the input buffer. */
5461 assert (gms_input_cursor < gms_input_length);
5462 return gms_input_buffer[gms_input_cursor++];
5463 }
5464
5465
5466 /*
5467 * gms_confirm()
5468 *
5469 * Print a confirmation prompt, and read a single input character, taking
5470 * only [YyNn] input. If the character is 'Y' or 'y', return TRUE.
5471 */
5472 static int
5473 gms_confirm (const char *prompt)
5474 {
5475 event_t event;
5476 unsigned char response;
5477 assert (prompt);
5478
5479 /*
5480 * Print the confirmation prompt, in a style that hints that it's from the
5481 * interpreter, not the game.
5482 */
5483 gms_standout_string (prompt);
5484
5485 /* Wait for a single 'Y' or 'N' character response. */
5486 response = ' ';
5487 do
5488 {
5489 glk_request_char_event (gms_main_window);
5490 gms_event_wait (evtype_CharInput, &event);
5491
5492 if (event.val1 <= UCHAR_MAX)
5493 response = glk_char_to_upper (event.val1);
5494 }
5495 while (!(response == 'Y' || response == 'N'));
5496
5497 /* Echo the confirmation response, and a blank line. */
5498 glk_set_style (style_Input);
5499 glk_put_string (response == 'Y' ? "Yes" : "No");
5500 glk_set_style (style_Normal);
5501 glk_put_string ("\n\n");
5502
5503 return response == 'Y';
5504 }
5505
5506
5507 /*---------------------------------------------------------------------*/
5508 /* Glk port event functions */
5509 /*---------------------------------------------------------------------*/
5510
5511 /*
5512 * gms_event_wait()
5513 *
5514 * Process Glk events until one of the expected type arrives. Return
5515 * the event of that type.
5516 */
5517 static void
5518 gms_event_wait (glui32 wait_type, event_t * event)
5519 {
5520 assert (event);
5521
5522 do
5523 {
5524 glk_select (event);
5525
5526 switch (event->type)
5527 {
5528 case evtype_Arrange:
5529 case evtype_Redraw:
5530 /* Refresh any sensitive windows on size events. */
5531 gms_status_redraw ();
5532 gms_hint_redraw ();
5533 gms_graphics_paint ();
5534 break;
5535
5536 case evtype_Timer:
5537 /* Do background graphics updates on timeout. */
5538 gms_graphics_timeout ();
5539 break;
5540 }
5541 }
5542 while (event->type != wait_type);
5543 }
5544
5545
5546 /*---------------------------------------------------------------------*/
5547 /* Glk port file functions */
5548 /*---------------------------------------------------------------------*/
5549
5550 /* Success and fail return codes from file functions. */
5551 static const type8 GMS_FILE_SUCCESS = 0,
5552 GMS_FILE_ERROR = 1;
5553
5554
5555 /*
5556 * ms_save_file ()
5557 * ms_load_file ()
5558 *
5559 * Save the current game state to a file, and load a game state.
5560 */
5561 type8
5562 ms_save_file (type8s * name, type8 * ptr, type16 size)
5563 {
5564 assert (ptr);
5565
5566 /* Flush any pending buffered output. */
5567 gms_output_flush ();
5568
5569 /* If there is no name, use Glk to prompt for one, and save. */
5570 if (!name)
5571 {
5572 frefid_t fileref;
5573 strid_t stream;
5574
5575 fileref = glk_fileref_create_by_prompt (fileusage_SavedGame,
5576 filemode_Write, 0);
5577 if (!fileref)
5578 return GMS_FILE_ERROR;
5579
5580 stream = glk_stream_open_file (fileref, filemode_Write, 0);
5581 if (!stream)
5582 {
5583 glk_fileref_destroy (fileref);
5584 return GMS_FILE_ERROR;
5585 }
5586
5587 /* Write game state. */
5588 glk_put_buffer_stream (stream, ptr, size);
5589
5590 glk_stream_close (stream, NULL);
5591 glk_fileref_destroy (fileref);
5592 }
5593
5594 else
5595 {
5596 FILE *stream;
5597
5598 /*
5599 * If openable for read, assume the file already exists and confirm
5600 * overwrite.
5601 */
5602 stream = fopen (name, "r");
5603 if (stream)
5604 {
5605 fclose (stream);
5606
5607 /*
5608 * Confirm overwrite, clearing the game prompted flag beforehand
5609 * so we're sure to issue a new prompt on the next line input.
5610 */
5611 gms_game_prompted ();
5612 if (!gms_confirm ("Overwrite existing file? [y/n] "))
5613 return GMS_FILE_ERROR;
5614 }
5615
5616 /* Open output file directly. There's no Glk way to achieve this. */
5617 stream = fopen (name, "wb");
5618 if (!stream)
5619 return GMS_FILE_ERROR;
5620
5621 /* Write game state. */
5622 if (fwrite (ptr, 1, size, stream) != size)
5623 {
5624 fclose (stream);
5625 return GMS_FILE_ERROR;
5626 }
5627
5628 fclose (stream);
5629 }
5630
5631 return GMS_FILE_SUCCESS;
5632 }
5633
5634 type8
5635 ms_load_file (type8s * name, type8 * ptr, type16 size)
5636 {
5637 assert (ptr);
5638
5639 /* Flush any pending buffered output. */
5640 gms_output_flush ();
5641
5642 /* If there is no name, use Glk to prompt for one, and load. */
5643 if (!name)
5644 {
5645 frefid_t fileref;
5646 strid_t stream;
5647
5648 fileref = glk_fileref_create_by_prompt (fileusage_SavedGame,
5649 filemode_Read, 0);
5650 if (!fileref)
5651 return GMS_FILE_ERROR;
5652
5653 /*
5654 * Reject the file reference if we're expecting to read from it, and
5655 * the referenced file doesn't exist.
5656 */
5657 if (!glk_fileref_does_file_exist (fileref))
5658 {
5659 glk_fileref_destroy (fileref);
5660 return GMS_FILE_ERROR;
5661 }
5662
5663 stream = glk_stream_open_file (fileref, filemode_Read, 0);
5664 if (!stream)
5665 {
5666 glk_fileref_destroy (fileref);
5667 return GMS_FILE_ERROR;
5668 }
5669
5670 /* Restore saved game data. */
5671 glk_get_buffer_stream (stream, ptr, size);
5672
5673 glk_stream_close (stream, NULL);
5674 glk_fileref_destroy (fileref);
5675 }
5676
5677 else
5678 {
5679 FILE *stream;
5680
5681 /*
5682 * Open the input file directly. As above, there's no Glk way to
5683 * achieve this.
5684 */
5685 stream = fopen (name, "rb");
5686 if (!stream)
5687 return GMS_FILE_ERROR;
5688
5689 /* Restore saved game data. */
5690 if (fread (ptr, 1, size, stream) != size)
5691 {
5692 fclose (stream);
5693 return GMS_FILE_ERROR;
5694 }
5695
5696 fclose (stream);
5697 }
5698
5699 return GMS_FILE_SUCCESS;
5700 }
5701
5702
5703 /*---------------------------------------------------------------------*/
5704 /* Functions intercepted by link-time wrappers */
5705 /*---------------------------------------------------------------------*/
5706
5707 /*
5708 * __wrap_toupper()
5709 * __wrap_tolower()
5710 *
5711 * Wrapper functions around toupper() and tolower(). The Linux linker's
5712 * --wrap option will convert calls to mumble() to __wrap_mumble() if we
5713 * give it the right options. We'll use this feature to translate all
5714 * toupper() and tolower() calls in the interpreter code into calls to
5715 * Glk's versions of these functions.
5716 *
5717 * It's not critical that we do this. If a linker, say a non-Linux one,
5718 * won't do --wrap, then just do without it. It's unlikely that there
5719 * will be much noticeable difference.
5720 */
5721 int
5722 __wrap_toupper (int ch)
5723 {
5724 unsigned char uch;
5725
5726 uch = glk_char_to_upper ((unsigned char) ch);
5727 return (int) uch;
5728 }
5729
5730 int
5731 __wrap_tolower (int ch)
5732 {
5733 unsigned char lch;
5734
5735 lch = glk_char_to_lower ((unsigned char) ch);
5736 return (int) lch;
5737 }
5738
5739
5740 /*---------------------------------------------------------------------*/
5741 /* main() and options parsing */
5742 /*---------------------------------------------------------------------*/
5743
5744 /*
5745 * The following values need to be passed between the startup_code and main
5746 * functions.
5747 */
5748 static char *gms_gamefile = NULL, /* Name of game file. */
5749 *gms_game_message = NULL; /* Error message. */
5750
5751
5752 /*
5753 * gms_establish_filenames()
5754 *
5755 * Given a game name, try to establish three filenames from it - the main game
5756 * text file, the (optional) graphics data file, and the (optional) hints
5757 * file. Given an input "file" X, the function looks for X.MAG or X.mag for
5758 * game data, X.GFX or X.gfx for graphics, and X.HNT or X.hnt for hints.
5759 * If the input file already ends with .MAG, .GFX, or .HNT, the extension
5760 * is stripped first.
5761 *
5762 * The function returns NULL for filenames not available. It's not fatal if
5763 * the graphics filename or hints filename is NULL, but it is if the main game
5764 * filename is NULL. Filenames are malloc'ed, and need to be freed by the
5765 * caller.
5766 */
5767 static void
5768 gms_establish_filenames (char *name, char **text, char **graphics, char **hints)
5769 {
5770 char *base, *text_file, *graphics_file, *hints_file;
5771 FILE *stream;
5772 assert (name && text && graphics && hints);
5773
5774 /* Take a destroyable copy of the input filename. */
5775 base = gms_malloc (strlen (name) + 1);
5776 strcpy (base, name);
5777
5778 /* If base has an extension .MAG, .GFX, or .HNT, remove it. */
5779 if (strlen (base) > strlen (".XXX"))
5780 {
5781 if (gms_strcasecmp (base + strlen (base) - strlen (".MAG"), ".MAG") == 0
5782 || gms_strcasecmp (base + strlen (base) - strlen (".GFX"), ".GFX") == 0
5783 || gms_strcasecmp (base + strlen (base) - strlen (".HNT"), ".HNT") == 0)
5784 base[strlen (base) - strlen (".XXX")] = '\0';
5785 }
5786
5787 /* Allocate space for the return text file. */
5788 text_file = gms_malloc (strlen (base) + strlen (".MAG") + 1);
5789
5790 /* Form a candidate text file, by adding a .MAG extension. */
5791 strcpy (text_file, base);
5792 strcat (text_file, ".MAG");
5793 stream = fopen (text_file, "rb");
5794 if (!stream)
5795 {
5796 /* Retry, using a .mag extension instead. */
5797 strcpy (text_file, base);
5798 strcat (text_file, ".mag");
5799 stream = fopen (text_file, "rb");
5800 if (!stream)
5801 {
5802 /*
5803 * No access to a usable game text file. Return immediately,
5804 * without looking for any associated graphics or hints files.
5805 */
5806 *text = NULL;
5807 *graphics = NULL;
5808 *hints = NULL;
5809
5810 free (text_file);
5811 free (base);
5812 return;
5813 }
5814 }
5815 if (stream)
5816 fclose (stream);
5817
5818 /* Now allocate space for the return graphics file. */
5819 graphics_file = gms_malloc (strlen (base) + strlen (".GFX") + 1);
5820
5821 /* As above, form a candidate graphics file, using a .GFX extension. */
5822 strcpy (graphics_file, base);
5823 strcat (graphics_file, ".GFX");
5824 stream = fopen (graphics_file, "rb");
5825 if (!stream)
5826 {
5827 /* Retry, using a .gfx extension instead. */
5828 strcpy (graphics_file, base);
5829 strcat (graphics_file, ".gfx");
5830 stream = fopen (graphics_file, "rb");
5831 if (!stream)
5832 {
5833 /*
5834 * No access to any graphics file. In this case, free memory and
5835 * reset graphics file to NULL.
5836 */
5837 free (graphics_file);
5838 graphics_file = NULL;
5839 }
5840 }
5841 if (stream)
5842 fclose (stream);
5843
5844 /* Now allocate space for the return hints file. */
5845 hints_file = gms_malloc (strlen (base) + strlen (".HNT") + 1);
5846
5847 /* As above, form a candidate graphics file, using a .HNT extension. */
5848 strcpy (hints_file, base);
5849 strcat (hints_file, ".HNT");
5850 stream = fopen (hints_file, "rb");
5851 if (!stream)
5852 {
5853 /* Retry, using a .hnt extension instead. */
5854 strcpy (hints_file, base);
5855 strcat (hints_file, ".hnt");
5856 stream = fopen (hints_file, "rb");
5857 if (!stream)
5858 {
5859 /*
5860 * No access to any hints file. In this case, free memory and
5861 * reset hints file to NULL.
5862 */
5863 free (hints_file);
5864 hints_file = NULL;
5865 }
5866 }
5867 if (stream)
5868 fclose (stream);
5869
5870 /* Return the text file, and graphics and hints, which may be NULL. */
5871 *text = text_file;
5872 *graphics = graphics_file;
5873 *hints = hints_file;
5874
5875 free (base);
5876 }
5877
5878
5879 /*
5880 * gms_startup_code()
5881 * gms_main()
5882 *
5883 * Together, these functions take the place of the original main(). The
5884 * first one is called from glkunix_startup_code(), to parse and generally
5885 * handle options. The second is called from glk_main(), and does the real
5886 * work of running the game.
5887 */
5888 static int
5889 gms_startup_code (int argc, char *argv[])
5890 {
5891 int argv_index;
5892
5893 /* Handle command line arguments. */
5894 for (argv_index = 1;
5895 argv_index < argc && argv[argv_index][0] == '-'; argv_index++)
5896 {
5897 if (strcmp (argv[argv_index], "-nc") == 0)
5898 {
5899 gms_commands_enabled = FALSE;
5900 continue;
5901 }
5902 if (strcmp (argv[argv_index], "-na") == 0)
5903 {
5904 gms_abbreviations_enabled = FALSE;
5905 continue;
5906 }
5907 if (strcmp (argv[argv_index], "-np") == 0)
5908 {
5909 gms_graphics_enabled = FALSE;
5910 continue;
5911 }
5912 if (strcmp (argv[argv_index], "-ng") == 0)
5913 {
5914 gms_gamma_mode = GAMMA_OFF;
5915 continue;
5916 }
5917 if (strcmp (argv[argv_index], "-nx") == 0)
5918 {
5919 gms_animation_enabled = FALSE;
5920 continue;
5921 }
5922 if (strcmp (argv[argv_index], "-ne") == 0)
5923 {
5924 gms_prompt_enabled = FALSE;
5925 continue;
5926 }
5927 if (strcmp (argv[argv_index], "-sc") == 0)
5928 {
5929 char *endptr;
5930 long scale = strtol(argv[++argv_index], &endptr, 10);
5931 if (scale >= 1 && scale <= 8 && *endptr == 0)
5932 {
5933 gms_graphics_pixel = scale;
5934 }
5935 continue;
5936 }
5937 if (strcmp (argv[argv_index], "-gp") == 0)
5938 {
5939 char *endptr;
5940 long proportion = strtol(argv[++argv_index], &endptr, 10);
5941 if (proportion >= 1 && proportion <= 100 && *endptr == 0)
5942 {
5943 gms_graphics_proportion = proportion;
5944 }
5945 continue;
5946 }
5947 if (strcmp (argv[argv_index], "-gx") == 0)
5948 {
5949 char *endptr;
5950 long pixels = strtol(argv[++argv_index], &endptr, 10);
5951 if (pixels > 0 && *endptr == 0)
5952 {
5953 gms_graphics_height_pixels = pixels;
5954 }
5955 continue;
5956 }
5957 return FALSE;
5958 }
5959
5960 /*
5961 * Get the name of the game file. Since we need this in our call from
5962 * glk_main, we need to keep it in a module static variable. If the game
5963 * file name is omitted, then here we'll set the pointer to NULL, and
5964 * complain about it later in main. Passing the message string around
5965 * like this is a nuisance...
5966 */
5967 if (argv_index == argc - 1)
5968 {
5969 gms_gamefile = argv[argv_index];
5970 gms_game_message = NULL;
5971 #ifdef GARGLK
5972 char *s;
5973 s = strrchr(gms_gamefile, '\\');
5974 if (s)
5975 garglk_set_story_name(s+1);
5976 s = strrchr(gms_gamefile, '/');
5977 if (s)
5978 garglk_set_story_name(s+1);
5979 #endif
5980 }
5981 else
5982 {
5983 gms_gamefile = NULL;
5984 if (argv_index < argc - 1)
5985 gms_game_message = "More than one game file was given"
5986 " on the command line.";
5987 else
5988 gms_game_message = "No game file was given on the command line.";
5989 }
5990
5991 /* All startup options were handled successfully. */
5992 return TRUE;
5993 }
5994
5995 static void
5996 gms_main (void)
5997 {
5998 char *text_file = NULL, *graphics_file = NULL, *hints_file = NULL;
5999 int ms_init_status, is_running;
6000
6001 /* Ensure Magnetic Scrolls internal types have the right sizes. */
6002 if (!(sizeof (type8) == 1 && sizeof (type8s) == 1
6003 && sizeof (type16) == 2 && sizeof (type16s) == 2
6004 && sizeof (type32) == 4 && sizeof (type32s) == 4))
6005 {
6006 gms_fatal ("GLK: Types sized incorrectly, recompilation is needed");
6007 glk_exit ();
6008 }
6009
6010 /* Create the main Glk window, and set its stream as current. */
6011 gms_main_window = glk_window_open (0, 0, 0, wintype_TextBuffer, 0);
6012 if (!gms_main_window)
6013 {
6014 gms_fatal ("GLK: Can't open main window");
6015 glk_exit ();
6016 }
6017 glk_window_clear (gms_main_window);
6018 glk_set_window (gms_main_window);
6019 glk_set_style (style_Normal);
6020
6021 /* If there's a problem with the game file, complain now. */
6022 if (!gms_gamefile)
6023 {
6024 assert (gms_game_message);
6025 gms_header_string ("Glk Magnetic Error\n\n");
6026 gms_normal_string (gms_game_message);
6027 gms_normal_char ('\n');
6028 glk_exit ();
6029 }
6030
6031 /*
6032 * Given the basic game name, try to come up with usable text, graphics,
6033 * and hints filenames. The graphics and hints files may be null, but the
6034 * text file may not.
6035 */
6036 errno = 0;
6037 gms_establish_filenames (gms_gamefile,
6038 &text_file, &graphics_file, &hints_file);
6039 if (!text_file)
6040 {
6041 assert (!graphics_file && !hints_file);
6042 gms_header_string ("Glk Magnetic Error\n\n");
6043 gms_normal_string ("Can't find or open game '");
6044 gms_normal_string (gms_gamefile);
6045 gms_normal_string ("[.mag|.MAG]'");
6046 if (errno != 0)
6047 {
6048 gms_normal_string (": ");
6049 gms_normal_string (strerror (errno));
6050 }
6051 gms_normal_char ('\n');
6052 glk_exit ();
6053 }
6054
6055 /* Set the possibility of pictures depending on graphics file. */
6056 if (graphics_file)
6057 {
6058 /*
6059 * Check Glk library capabilities, and note pictures are impossible if
6060 * the library can't offer both graphics and timers. We need timers to
6061 * create the background "thread" for picture updates.
6062 */
6063 gms_graphics_possible = glk_gestalt (gestalt_Graphics, 0)
6064 && glk_gestalt (gestalt_Timer, 0);
6065 }
6066 else
6067 gms_graphics_possible = FALSE;
6068
6069
6070 /*
6071 * If pictures are impossible, clear pictures enabled flag. That is, act
6072 * as if -np was given on the command line, even though it may not have
6073 * been. If pictures are impossible, they can never be enabled.
6074 */
6075 if (!gms_graphics_possible)
6076 gms_graphics_enabled = FALSE;
6077
6078 /* Try to create a one-line status window. We can live without it. */
6079 #ifdef GARGLK
6080 glk_stylehint_set (wintype_TextGrid, style_User1, stylehint_ReverseColor, 1);
6081 #endif
6082 gms_status_window = glk_window_open (gms_main_window,
6083 winmethod_Above | winmethod_Fixed,
6084 1, wintype_TextGrid, 0);
6085
6086 /* Seed the random number generator. */
6087 ms_seed (time (NULL));
6088
6089 /*
6090 * Load the game. If no graphics are possible, then passing the NULL to
6091 * ms_init() runs a game without graphics.
6092 */
6093 errno = 0;
6094 if (gms_graphics_possible)
6095 {
6096 assert (graphics_file);
6097 ms_init_status = ms_init (text_file, graphics_file, hints_file, NULL);
6098 }
6099 else
6100 ms_init_status = ms_init (text_file, NULL, hints_file, NULL);
6101
6102 /* Look for a complete failure to load the game. */
6103 if (ms_init_status == 0)
6104 {
6105 if (gms_status_window)
6106 glk_window_close (gms_status_window, NULL);
6107 gms_header_string ("Glk Magnetic Error\n\n");
6108 gms_normal_string ("Can't load game '");
6109 gms_normal_string (gms_gamefile);
6110 gms_normal_char ('\'');
6111 if (errno != 0)
6112 {
6113 gms_normal_string (": ");
6114 gms_normal_string (strerror (errno));
6115 }
6116 gms_normal_char ('\n');
6117
6118 /*
6119 * Free the text file path, any graphics/hints file path, and
6120 * interpreter allocated memory.
6121 */
6122 free (text_file);
6123 free (graphics_file);
6124 free (hints_file);
6125 ms_freemem ();
6126 glk_exit ();
6127 }
6128
6129 /* Try to identify the game from its text file header. */
6130 gms_gameid_identify_game (text_file);
6131
6132 /* Print out a short banner. */
6133 gms_header_string ("\nMagnetic Scrolls Interpreter, version 2.3\n");
6134 gms_banner_string ("Written by Niclas Karlsson\n"
6135 "Glk interface by Simon Baldwin\n\n");
6136
6137 /* Look for failure to load just game graphics. */
6138 if (gms_graphics_possible && ms_init_status == 1)
6139 {
6140 /*
6141 * Output a warning if graphics failed, but the main game text
6142 * initialized okay.
6143 */
6144 gms_standout_string ("Error: Unable to open graphics file\n"
6145 "Continuing without pictures...\n\n");
6146
6147 gms_graphics_possible = FALSE;
6148 }
6149
6150 /* Run the game opcodes -- ms_rungame() returns FALSE on game end. */
6151 do
6152 {
6153 is_running = ms_rungame ();
6154 glk_tick ();
6155 }
6156 while (is_running);
6157
6158 /* Handle any updated status and pending buffered output. */
6159 gms_status_notify ();
6160 gms_output_flush ();
6161
6162 /* Turn off any background graphics "thread". */
6163 gms_graphics_stop ();
6164
6165 /* Free interpreter allocated memory. */
6166 ms_freemem ();
6167
6168 /*
6169 * Free any temporary memory that may have been used by graphics and hints.
6170 */
6171 gms_graphics_cleanup ();
6172 gms_hints_cleanup ();
6173
6174 /* Close any open transcript, input log, and/or read log. */
6175 if (gms_transcript_stream)
6176 {
6177 glk_stream_close (gms_transcript_stream, NULL);
6178 gms_transcript_stream = NULL;
6179 }
6180 if (gms_inputlog_stream)
6181 {
6182 glk_stream_close (gms_inputlog_stream, NULL);
6183 gms_inputlog_stream = NULL;
6184 }
6185 if (gms_readlog_stream)
6186 {
6187 glk_stream_close (gms_readlog_stream, NULL);
6188 gms_readlog_stream = NULL;
6189 }
6190
6191 /* Free the text file path, and any graphics/hints file path. */
6192 free (text_file);
6193 free (graphics_file);
6194 free (hints_file);
6195 }
6196
6197
6198 /*---------------------------------------------------------------------*/
6199 /* Linkage between Glk entry/exit calls and the Magnetic interpreter */
6200 /*---------------------------------------------------------------------*/
6201
6202 /*
6203 * Safety flags, to ensure we always get startup before main, and that
6204 * we only get a call to main once.
6205 */
6206 static int gms_startup_called = FALSE,
6207 gms_main_called = FALSE;
6208
6209 /*
6210 * glk_main()
6211 *
6212 * Main entry point for Glk. Here, all startup is done, and we call our
6213 * function to run the game.
6214 */
6215 void
6216 glk_main (void)
6217 {
6218 assert (gms_startup_called && !gms_main_called);
6219 gms_main_called = TRUE;
6220
6221 /* Call the interpreter main function. */
6222 gms_main ();
6223 }
6224
6225
6226 /*---------------------------------------------------------------------*/
6227 /* Glk linkage relevant only to the UNIX platform */
6228 /*---------------------------------------------------------------------*/
6229 #ifdef MAGNETIC_GLKUNIX
6230
6231 #include "glkstart.h"
6232
6233 /*
6234 * Glk arguments for UNIX versions of the Glk interpreter.
6235 */
6236 glkunix_argumentlist_t glkunix_arguments[] = {
6237 {(char *) "-nc", glkunix_arg_NoValue,
6238 (char *) "-nc No local handling for Glk special commands"},
6239 {(char *) "-na", glkunix_arg_NoValue,
6240 (char *) "-na Turn off abbreviation expansions"},
6241 {(char *) "-np", glkunix_arg_NoValue,
6242 (char *) "-np Turn off pictures"},
6243 {(char *) "-ng", glkunix_arg_NoValue,
6244 (char *) "-ng Turn off automatic gamma correction on pictures"},
6245 {(char *) "-nx", glkunix_arg_NoValue,
6246 (char *) "-nx Turn off picture animations"},
6247 {(char *) "-ne", glkunix_arg_NoValue,
6248 (char *) "-ne Turn off additional interpreter prompt"},
6249 {(char *) "-sc", glkunix_arg_ValueFollows,
6250 (char *) "-sc Scale pictures by integer value (1-8)"},
6251 {(char *) "", glkunix_arg_ValueCanFollow,
6252 (char *) "filename game to run"},
6253 {NULL, glkunix_arg_End, NULL}
6254 };
6255
6256
6257 /*
6258 * glkunix_startup_code()
6259 *
6260 * Startup entry point for UNIX versions of Glk interpreter. Glk will
6261 * call glkunix_startup_code() to pass in arguments. On startup, we call
6262 * our function to parse arguments and generally set stuff up.
6263 */
6264 int
6265 glkunix_startup_code (glkunix_startup_t * data)
6266 {
6267 assert (!gms_startup_called);
6268 gms_startup_called = TRUE;
6269
6270 #ifdef GARGLK
6271 garglk_set_program_name ("Magnetic 2.3");
6272 garglk_set_program_info (
6273 "Magnetic 2.3 by Niclas Karlsson, David Kinder,\n"
6274 "Stefan Meier, and Paul David Doherty.\n"
6275 "Glk port by Simon Baldwin.\n"
6276 "Gargoyle tweaks by Tor Andersson.\n");
6277 #endif
6278
6279 return gms_startup_code (data->argc, data->argv);
6280 }
6281 #endif /* MAGNETIC_GLKUNIX */
6282
6283
6284 /*---------------------------------------------------------------------*/
6285 /* Glk linkage relevant only to the Mac platform */
6286 /*---------------------------------------------------------------------*/
6287 #ifndef GARGLK
6288 #if TARGET_OS_MAC
6289
6290 #include "macglk_startup.h"
6291
6292 static strid_t gms_mac_gamefile = NULL;
6293 static short gms_savedVRefNum = 0;
6294 static long gms_savedDirID = 0;
6295
6296
6297 /*
6298 * gms_mac_whenselected()
6299 * gms_mac_whenbuiltin()
6300 * macglk_startup_code()
6301 *
6302 * Startup entry points for Mac versions of Glk interpreter. Glk will call
6303 * macglk_startup_code() for details on what to do when the application is
6304 * selected. On selection, an argv[] vector is built, and passed to the
6305 * normal interpreter startup code, after which, Glk will call glk_main().
6306 */
6307 static Boolean
6308 gms_mac_whenselected (FSSpec * file, OSType filetype)
6309 {
6310 static char *argv[2];
6311 assert (!gms_startup_called);
6312 gms_startup_called = TRUE;
6313
6314 /* Set the WD to where the file is, so later fopens work. */
6315 if (HGetVol (0, &gms_savedVRefNum, &gms_savedDirID) != 0)
6316 {
6317 gms_fatal ("GLK: HGetVol failed");
6318 return FALSE;
6319 }
6320 if (HSetVol (0, file->vRefNum, file->parID) != 0);
6321 {
6322 gms_fatal ("GLK: HSetVol failed");
6323 return FALSE;
6324 }
6325
6326 /* Put a CString version of the PString name into argv[1]. */
6327 argv[1] = gms_malloc (file->name[0] + 1);
6328 BlockMoveData (file->name + 1, argv[1], file->name[0]);
6329 argv[1][file->name[0]] = '\0';
6330 argv[2] = NULL;
6331
6332 return gms_startup_code (2, argv);
6333 }
6334
6335 static Boolean
6336 gms_mac_whenbuiltin (void)
6337 {
6338 /* Not implemented yet. */
6339 return TRUE;
6340 }
6341
6342 Boolean
6343 macglk_startup_code (macglk_startup_t * data)
6344 {
6345 static OSType gms_mac_gamefile_types[] = { 'MaSc' };
6346
6347 data->startup_model = macglk_model_ChooseOrBuiltIn;
6348 data->app_creator = 'cAGL';
6349 data->gamefile_types = gms_mac_gamefile_types;
6350 data->num_gamefile_types = sizeof (gms_mac_gamefile_types)
6351 / sizeof (*gms_mac_gamefile_types);
6352 data->savefile_type = 'BINA';
6353 data->datafile_type = 0x3f3f3f3f;
6354 data->gamefile = &gms_mac_gamefile;
6355 data->when_selected = gms_mac_whenselected;
6356 data->when_builtin = gms_mac_whenbuiltin;
6357 /* macglk_setprefs(); */
6358 return TRUE;
6359 }
6360 #endif /* TARGET_OS_MAC */
6361 #endif