summaryrefslogtreecommitdiff
path: root/apps/plugins/puzzles/src/devel.but
diff options
context:
space:
mode:
Diffstat (limited to 'apps/plugins/puzzles/src/devel.but')
-rw-r--r--apps/plugins/puzzles/src/devel.but1607
1 files changed, 1334 insertions, 273 deletions
diff --git a/apps/plugins/puzzles/src/devel.but b/apps/plugins/puzzles/src/devel.but
index 7521596df9..c201a3e6c9 100644
--- a/apps/plugins/puzzles/src/devel.but
+++ b/apps/plugins/puzzles/src/devel.but
@@ -32,10 +32,11 @@ Puzzle Collection (henceforth referred to simply as \q{Puzzles}),
32for use by anyone attempting to implement a new puzzle or port to a 32for use by anyone attempting to implement a new puzzle or port to a
33new platform. 33new platform.
34 34
35This guide is believed correct as of r6190. Hopefully it will be 35This guide is believed correct as of \cw{git} commit
36updated along with the code in future, but if not, I've at least 36\cw{a2212e82aa2f4b9a4ee22783d6fed2761c213432}. Hopefully it will be
37left this version number in here so you can figure out what's 37updated along with the code in future, but if not, I've at least left
38changed by tracking commit comments from there onwards. 38this version number in here so you can figure out what's changed by
39tracking commit comments from there onwards.
39 40
40\C{intro} Introduction 41\C{intro} Introduction
41 42
@@ -52,25 +53,21 @@ that you replace completely when you port to a different platform.
52So it's responsible for all system calls, all GUI interaction, and 53So it's responsible for all system calls, all GUI interaction, and
53anything else platform-specific. 54anything else platform-specific.
54 55
55The current front ends in the main code base are for Windows, GTK
56and MacOS X; I also know of a third-party front end for PalmOS.
57
58The front end contains \cw{main()} or the local platform's 56The front end contains \cw{main()} or the local platform's
59equivalent. Top-level control over the application's execution flow 57equivalent. Top-level control over the application's execution flow
60belongs to the front end (it isn't, for example, a set of functions 58belongs to the front end (it isn't, for example, a set of functions
61called by a universal \cw{main()} somewhere else). 59called by a universal \cw{main()} somewhere else).
62 60
63The front end has complete freedom to design the GUI for any given 61The front end has complete freedom to design the GUI for any given
64port of Puzzles. There is no centralised mechanism for maintaining 62port of Puzzles. There is no centralised mechanism for maintaining the
65the menu layout, for example. This has a cost in consistency (when I 63menu layout, for example. This has a cost in consistency (when I
66\e{do} want the same menu layout on more than one platform, I have 64\e{do} want the same menu layout on more than one platform, I have to
67to edit two pieces of code in parallel every time I make a change), 65edit N pieces of code in parallel every time I make a change), but the
68but the advantage is that local GUI conventions can be conformed to 66advantage is that local GUI conventions can be conformed to and local
69and local constraints adapted to. For example, MacOS X has strict 67constraints adapted to. For example, MacOS has strict human interface
70human interface guidelines which specify a different menu layout 68guidelines which specify a different menu layout from the one I've
71from the one I've used on Windows and GTK; there's nothing stopping 69used on Windows and GTK; there's nothing stopping the MacOS front end
72the OS X front end from providing a menu layout consistent with 70from providing a menu layout consistent with those guidelines.
73those guidelines.
74 71
75Although the front end is mostly caller rather than the callee in 72Although the front end is mostly caller rather than the callee in
76its interactions with other parts of the code, it is required to 73its interactions with other parts of the code, it is required to
@@ -143,9 +140,10 @@ etc).
143\b Handling the dialog boxes which ask the user for a game ID. 140\b Handling the dialog boxes which ask the user for a game ID.
144 141
145\b Handling serialisation of entire games (for loading and saving a 142\b Handling serialisation of entire games (for loading and saving a
146half-finished game to a disk file, or for handling application 143half-finished game to a disk file; for handling application shutdown
147shutdown and restart on platforms such as PalmOS where state is 144and restart on platforms such as PalmOS where state is expected to be
148expected to be saved). 145saved; for storing the previous game in order to undo and redo across
146a New Game event).
149 147
150Thus, there's a lot of work done once by the mid-end so that 148Thus, there's a lot of work done once by the mid-end so that
151individual back ends don't have to worry about it. All the back end 149individual back ends don't have to worry about it. All the back end
@@ -193,9 +191,8 @@ end module builds a different puzzle.
193\b On platforms such as MacOS X and PalmOS, which build all the 191\b On platforms such as MacOS X and PalmOS, which build all the
194puzzles into a single monolithic binary, the game structure in each 192puzzles into a single monolithic binary, the game structure in each
195back end must have a different name, and there's a helper module 193back end must have a different name, and there's a helper module
196\c{list.c} (constructed automatically by the same Perl script that 194\c{list.c} which constructs a complete list of those game structures
197builds the \cw{Makefile}s) which contains a complete list of those 195from a header file generated by CMake.
198game structures.
199 196
200On the latter type of platform, source files may assume that the 197On the latter type of platform, source files may assume that the
201preprocessor symbol \c{COMBINED} has been defined. Thus, the usual 198preprocessor symbol \c{COMBINED} has been defined. Thus, the usual
@@ -249,14 +246,15 @@ yet been necessary to do this in any puzzle so far, but the
249capability is there just in case.) 246capability is there just in case.)
250 247
251\c{game_params} is also the only structure which the game's 248\c{game_params} is also the only structure which the game's
252\cw{compute_size()} function may refer to; this means that any 249\cw{compute_size()} function may refer to; this means that any aspect
253aspect of the game which affects the size of the window it needs to 250of the game which affects the size of the window it needs to be drawn
254be drawn in must be stored in \c{game_params}. In particular, this 251in (other than the magnification level) must be stored in
255imposes the fundamental limitation that random game generation may 252\c{game_params}. In particular, this imposes the fundamental
256not have a random effect on the window size: game generation 253limitation that random game generation may not have a random effect on
257algorithms are constrained to work by starting from the grid size 254the window size: game generation algorithms are constrained to work by
258rather than generating it as an emergent phenomenon. (Although this 255starting from the grid size rather than generating it as an emergent
259is a restriction in theory, it has not yet seemed to be a problem.) 256phenomenon. (Although this is a restriction in theory, it has not yet
257seemed to be a problem.)
260 258
261\S{backend-game-state} \c{game_state} 259\S{backend-game-state} \c{game_state}
262 260
@@ -268,14 +266,25 @@ The mid-end keeps \c{game_state}s in a list, and adds to the list
268every time the player makes a move; the Undo and Redo functions step 266every time the player makes a move; the Undo and Redo functions step
269back and forth through that list. 267back and forth through that list.
270 268
271Therefore, a good means of deciding whether a data item needs to go 269Therefore, a good means of deciding whether a data item needs to go in
272in \c{game_state} is: would a player expect that data item to be 270\c{game_state} is: would a player expect that data item to be restored
273restored on undo? If so, put it in \c{game_state}, and this will 271on undo? If so, put it in \c{game_state}, and this will automatically
274automatically happen without you having to lift a finger. If not 272happen without you having to lift a finger. If not, then you might
275\dash for example, the deaths counter in Mines is precisely 273have found a data item that needs to go in \c{game_ui} instead.
276something that does \e{not} want to be reset to its previous state 274
277on an undo \dash then you might have found a data item that needs to 275Two quite different examples of this:
278go in \c{game_ui} instead. 276
277\b if the game provides an interface for making moves by moving a
278cursor around the grid with the keyboard and pressing some other key
279when you get to a square you want to change, then the location of that
280cursor belongs in \c{game_ui}, because the player will want to undo
281one \e{square change} at a time, not one \e{cursor movement} at a
282time.
283
284\b Mines tracks the number of times you opened a mine square and died.
285Every time you do that, you can only continue the game by pressing
286Undo. So the deaths counter belongs in \c{game_ui}, because otherwise,
287it would revert to 0 every time you undid your mistaken move.
279 288
280During play, \c{game_state}s are often passed around without an 289During play, \c{game_state}s are often passed around without an
281accompanying \c{game_params} structure. Therefore, any information 290accompanying \c{game_params} structure. Therefore, any information
@@ -293,12 +302,12 @@ is passed to every call to the game redraw function, so that it can
293remember what it has already drawn and what needs redrawing. 302remember what it has already drawn and what needs redrawing.
294 303
295A typical use for a \c{game_drawstate} is to have an array mirroring 304A typical use for a \c{game_drawstate} is to have an array mirroring
296the array of grid squares in the \c{game_state}; then every time the 305the array of grid squares in the \c{game_state}, but describing what
297redraw function was passed a \c{game_state}, it would loop over all 306was drawn in the window on the most recent redraw. This is used to
298the squares, and physically redraw any whose description in the 307identify the squares that need redrawing next time, by deciding what
299\c{game_state} (i.e. what the square needs to look like when the 308the new value in that array should be, and comparing it to what was
300redraw is completed) did not match its description in the 309drawn last time. See \k{writing-howto-redraw} for more on this
301\c{game_drawstate} (i.e. what the square currently looks like). 310subject.
302 311
303\c{game_drawstate} is occasionally completely torn down and 312\c{game_drawstate} is occasionally completely torn down and
304reconstructed by the mid-end, if the user somehow forces a full 313reconstructed by the mid-end, if the user somehow forces a full
@@ -323,23 +332,49 @@ game ID etc). It persists until the user finishes playing that game
323and begins another one (or closes the window); in particular, 332and begins another one (or closes the window); in particular,
324\q{Restart Game} does \e{not} destroy the \c{game_ui}. 333\q{Restart Game} does \e{not} destroy the \c{game_ui}.
325 334
326\c{game_ui} is useful for implementing user-interface state which is 335There are various things that you might store in \c{game_ui}, which
327not part of \c{game_state}. Common examples are keyboard control 336are conceptually different from each other, but I haven't yet found a
328(you wouldn't want to have to separately Undo through every cursor 337need to split them out into smaller sub-structures for different
329motion) and mouse dragging. See \k{writing-keyboard-cursor} and 338purposes:
330\k{writing-howto-dragging}, respectively, for more details. 339
340\dt Transient UI state:
341
342\dd Storing a piece of UI state in \c{game_state} means that you can
343only update it by appending a move to the undo chain. Some UI state
344shouldn't really be treated this way. For example, if your puzzle has
345a keyboard-controlled cursor, you probably don't want every cursor
346movement to be an undoable action, because the history of where the
347cursor went just isn't interesting. More likely the cursor should just
348move freely, and the only undoable actions are the ones where you
349modify the element under the cursor. So you'd store the cursor
350position in \c{game_ui} rather than \c{game_state}. See
351\k{writing-keyboard-cursor} for more details.
352
353\lcont{ Another example of this is the state of an ongoing mouse drag.
354If there's an undoable action involved, it will probably occur when
355the drag is released. In between, you still need to store state that
356the redraw function will use to update the display \dash and that can
357live in \c{game_ui}. See \k{writing-howto-dragging} for more details
358of this. }
359
360\dt Persistent UI state:
361
362\dd An example of this is the counter of deaths in Mines or Inertia.
363This shouldn't be reverted by pressing Undo, for the opposite reason
364to the cursor position: the cursor position is too boring to store the
365history of, but the deaths counter is too \e{important}!
366
367\dt Information about recent changes to the game state:
331 368
332Another use for \c{game_ui} is to store highly persistent data such 369\dd This is used in Mines, for example, to indicate whether a
333as the Mines death counter. This is conceptually rather different: 370requested \q{flash} should be a white flash for victory or a red flash
334where the Net cursor position was \e{not important enough} to 371for defeat; see \k{writing-flash-types}.
335preserve for the player to restore by Undo, the Mines death counter
336is \e{too important} to permit the player to revert by Undo!
337 372
338A final use for \c{game_ui} is to pass information to the redraw 373\dt User preferences:
339function about recent changes to the game state. This is used in 374
340Mines, for example, to indicate whether a requested \q{flash} should 375\dd Any user preference about display or UI handled by
341be a white flash for victory or a red flash for defeat; see 376\cw{get_prefs()} and \cw{set_prefs()} will need to live in
342\k{writing-flash-types}. 377\c{game_ui}, because that's the structure that those functions access.
343 378
344\H{backend-simple} Simple data in the back end 379\H{backend-simple} Simple data in the back end
345 380
@@ -356,24 +391,41 @@ name will be used in window titles, in game selection menus on
356monolithic platforms, and anywhere else that the front end needs to 391monolithic platforms, and anywhere else that the front end needs to
357know the name of a game. 392know the name of a game.
358 393
359\S{backend-winhelp} \c{winhelp_topic} 394\S{backend-winhelp} \c{winhelp_topic} and \c{htmlhelp_topic}
360 395
361\c const char *winhelp_topic; 396\c const char *winhelp_topic, *htmlhelp_topic;
362 397
363This member is used on Windows only, to provide online help. 398These members are used on Windows only, to provide online help.
364Although the Windows front end provides a separate binary for each 399Although the Windows front end provides a separate binary for each
365puzzle, it has a single monolithic help file; so when a user selects 400puzzle, it has a single monolithic help file; so when a user selects
366\q{Help} from the menu, the program needs to open the help file and 401\q{Help} from the menu, the program needs to open the help file and
367jump to the chapter describing that particular puzzle. 402jump to the chapter describing that particular puzzle.
368 403
369Therefore, each chapter in \c{puzzles.but} is labelled with a 404This code base still supports the legacy \cw{.HLP} Windows Help format
370\e{help topic} name, similar to this: 405as well as the less old \cw{.CHM} HTML Help format. The two use
406different methods of identifying topics, so you have to specify both.
407
408Each chapter about a puzzle in \c{puzzles.but} is labelled with a
409\e{help topic} name for Windows Help, which typically appears just
410after the \cw{\\C} chapter title paragraph, similar to this:
371 411
412\c \C{net} \i{Net}
413\c
372\c \cfg{winhelp-topic}{games.net} 414\c \cfg{winhelp-topic}{games.net}
373 415
374And then the corresponding game back end encodes the topic string 416But HTML Help is able to use the Halibut identifier for the chapter
375(here \cq{games.net}) in the \c{winhelp_topic} element of the game 417itself, i.e. the keyword that appears in braces immediatey after the
376structure. 418\cw{\\C}.
419
420So the corresponding game back end encodes the \c{winhelp-topic}
421string (here \cq{games.net}) in the \c{winhelp_topic} element of the
422game structure, and puts the chapter identifier (here \cq{net}) in the
423\c{htmlhelp_topic} element. For example:
424
425\c const struct game thegame = {
426\c "Net", "games.net", "net",
427\c // ...
428\c };
377 429
378\H{backend-params} Handling game parameter sets 430\H{backend-params} Handling game parameter sets
379 431
@@ -439,8 +491,8 @@ from the game, and before passing it on to the front end.
439\c char *(*encode_params)(const game_params *params, bool full); 491\c char *(*encode_params)(const game_params *params, bool full);
440 492
441The job of this function is to take a \c{game_params}, and encode it 493The job of this function is to take a \c{game_params}, and encode it
442in a string form for use in game IDs. The return value must be a 494in a printable ASCII string form for use in game IDs. The return value must
443newly allocated C string, and \e{must} not contain a colon or a hash 495be a newly allocated C string, and \e{must} not contain a colon or a hash
444(since those characters are used to mark the end of the parameter 496(since those characters are used to mark the end of the parameter
445section in a game ID). 497section in a game ID).
446 498
@@ -454,7 +506,7 @@ away with commas, periods or underscores without causing anybody any
454major inconvenience. If you venture far beyond that, you're likely 506major inconvenience. If you venture far beyond that, you're likely
455to irritate \e{somebody}. 507to irritate \e{somebody}.
456 508
457(At the time of writing this, all existing games have purely 509(At the time of writing this, most existing games have purely
458alphanumeric string parameter formats. Usually these involve a 510alphanumeric string parameter formats. Usually these involve a
459letter denoting a parameter, followed optionally by a number giving 511letter denoting a parameter, followed optionally by a number giving
460the value of that parameter, with a few mandatory parts at the 512the value of that parameter, with a few mandatory parts at the
@@ -466,15 +518,17 @@ call to \cw{decode_params()} (\k{backend-decode-params}) will yield
466an identical structure. If \c{full} is \cw{false}, however, you 518an identical structure. If \c{full} is \cw{false}, however, you
467should leave out anything which is not necessary to describe a 519should leave out anything which is not necessary to describe a
468\e{specific puzzle instance}, i.e. anything which only takes effect 520\e{specific puzzle instance}, i.e. anything which only takes effect
469when a new puzzle is \e{generated}. For example, the Solo 521when a new puzzle is \e{generated}.
470\c{game_params} includes a difficulty rating used when constructing 522
471new puzzles; but a Solo game ID need not explicitly include the 523For example, the Solo \c{game_params} includes a difficulty rating
472difficulty, since to describe a puzzle once generated it's 524used when constructing new puzzles; but a Solo game ID need not
473sufficient to give the grid dimensions and the location and contents 525explicitly include the difficulty, since to describe a puzzle once
474of the clue squares. (Indeed, one might very easily type in a puzzle 526generated it's sufficient to give the grid dimensions and the location
475out of a newspaper without \e{knowing} what its difficulty level is 527and contents of the clue squares. (Indeed, one might very easily type
476in Solo's terminology.) Therefore, Solo's \cw{encode_params()} only 528in a puzzle out of a newspaper without \e{knowing} what its difficulty
477encodes the difficulty level if \c{full} is set. 529level is in Solo's terminology.) Therefore, Solo's
530\cw{encode_params()} only encodes the difficulty level if \c{full} is
531set.
478 532
479\S{backend-decode-params} \cw{decode_params()} 533\S{backend-decode-params} \cw{decode_params()}
480 534
@@ -489,7 +543,7 @@ to create a \e{new} \c{game_params}, but to modify an existing one.
489This function can receive a string which only encodes a subset of 543This function can receive a string which only encodes a subset of
490the parameters. The most obvious way in which this can happen is if 544the parameters. The most obvious way in which this can happen is if
491the string was constructed by \cw{encode_params()} with its \c{full} 545the string was constructed by \cw{encode_params()} with its \c{full}
492parameter set to \cw{FALSE}; however, it could also happen if the 546parameter set to \cw{false}; however, it could also happen if the
493user typed in a parameter set manually and missed something out. Be 547user typed in a parameter set manually and missed something out. Be
494prepared to deal with a wide range of possibilities. 548prepared to deal with a wide range of possibilities.
495 549
@@ -551,9 +605,10 @@ its initial value; the front end will modify the value fields and
551return the updated array to \cw{custom_params()} (see 605return the updated array to \cw{custom_params()} (see
552\k{backend-custom-params}). 606\k{backend-custom-params}).
553 607
554The \cw{config_item} structure contains the following elements: 608The \cw{config_item} structure contains the following elements used by
609this function:
555 610
556\c char *name; 611\c const char *name;
557\c int type; 612\c int type;
558\c union { /* type-specific fields */ } u; 613\c union { /* type-specific fields */ } u;
559\e iiiiiiiiiiiiiiiiiiiiiiiiii 614\e iiiiiiiiiiiiiiiiiiiiiiiiii
@@ -592,9 +647,7 @@ of the input box.
592 647
593For controls of this type, \c{u.boolean} contains a single field 648For controls of this type, \c{u.boolean} contains a single field
594 649
595\c int bval; 650\c bool bval;
596
597which is either \cw{TRUE} or \cw{FALSE}.
598 651
599} 652}
600 653
@@ -634,8 +687,8 @@ The array returned from this function is expected to have filled in
634the initial values of all the controls according to the input 687the initial values of all the controls according to the input
635\c{game_params} structure. 688\c{game_params} structure.
636 689
637If the game's \c{can_configure} flag is set to \cw{FALSE}, this 690If the game's \c{can_configure} flag is set to \cw{false}, this
638function is never called and need not do anything at all. 691function is never called and can be \cw{NULL}.
639 692
640\S{backend-custom-params} \cw{custom_params()} 693\S{backend-custom-params} \cw{custom_params()}
641 694
@@ -659,8 +712,63 @@ This function is not expected to (and indeed \e{must not}) free the
659input \c{config_item} array. (If the parameters fail to validate, 712input \c{config_item} array. (If the parameters fail to validate,
660the dialog box will stay open.) 713the dialog box will stay open.)
661 714
662If the game's \c{can_configure} flag is set to \cw{FALSE}, this 715If the game's \c{can_configure} flag is set to \cw{false}, this
663function is never called and need not do anything at all. 716function is never called and can be \cw{NULL}.
717
718\S{backend-get-prefs} \cw{get_prefs()}
719
720\c config_item *(*get_prefs)(game_ui *ui);
721
722This function works very like \cw{configure()}, but instead of
723receiving a \c{game_params} and returning GUI elements describing the
724data in it, this function receives a \c{game_ui} and returns GUI
725elements describing any user preferences stored in that.
726
727This function should only deal with fields of \c{game_ui} that are
728user-settable preferences. In-game state like cursor position and
729mouse drags, or per-game state like death counters, are nothing to do
730with this function.
731
732If there are no user preferences, you can set both this function
733pointer and \c{set_prefs} to \cw{NULL}.
734
735If you implement these functions, you must also ensure that your
736game's \cw{new_ui()} function can be called with a null \c{game_state}
737pointer. (See \k{backend-new-ui}.)
738
739In every \c{config_item} returned from this function, you must set an
740additional field beyond the ones described in \k{backend-configure}:
741
742\c const char *kw;
743
744This should be an identifying keyword for the user preference in
745question, suitable for use in configuration files. That means it
746should remain stable, even if the user-facing wording in the \c{name}
747field is reworded for clarity. If it doesn't stay stable, old
748configuration files will not be read correctly.
749
750For \c{config_item}s of type \cw{C_CHOICES}, you must also set an
751extra field in \c{u.choices}:
752
753\c const char *choicekws;
754
755This has the same structure as the \c{choicenames} field (a list of
756values delimited by the first character in the whole string), and it
757provides an identifying keyword for each individual choice in the
758list, in the same order as the entries of \c{choicenames}.
759
760\S{backend-set-prefs} \cw{set_prefs()}
761
762\c void (*set_prefs)(game_ui *ui, const config_item *cfg);
763
764This function is the counterpart to \cw{set_prefs()}, as
765\cw{custom_params()} is to \cw{configure()}. It receives an array of
766\c{config_item}s which was originally created by \cw{get_prefs()},
767with the controls' values updated from user input, and it should
768transcribe the new settings into the provided \c{game_ui}.
769
770If there are no user preferences, you can set both this function
771pointer and \c{get_prefs} to \cw{NULL}.
664 772
665\S{backend-validate-params} \cw{validate_params()} 773\S{backend-validate-params} \cw{validate_params()}
666 774
@@ -718,8 +826,8 @@ ensuring solubility and uniqueness as appropriate.
718 826
719As input it is given a \c{game_params} structure and a random state 827As input it is given a \c{game_params} structure and a random state
720(see \k{utils-random} for the random number API). It must invent a 828(see \k{utils-random} for the random number API). It must invent a
721puzzle instance, encode it in string form, and return a dynamically 829puzzle instance, encode it in printable ASCII string form, and
722allocated C string containing that encoding. 830return a dynamically allocated C string containing that encoding.
723 831
724Additionally, it may return a second dynamically allocated string in 832Additionally, it may return a second dynamically allocated string in
725\c{*aux}. (If it doesn't want to, then it can leave that parameter 833\c{*aux}. (If it doesn't want to, then it can leave that parameter
@@ -824,9 +932,17 @@ allocations contained within it.
824\c game_ui *(*new_ui)(const game_state *state); 932\c game_ui *(*new_ui)(const game_state *state);
825 933
826This function allocates and returns a new \c{game_ui} structure for 934This function allocates and returns a new \c{game_ui} structure for
827playing a particular puzzle. It is passed a pointer to the initial 935playing a particular puzzle.
828\c{game_state}, in case it needs to refer to that when setting up 936
829the initial values for the new game. 937Usually, this function is passed a pointer to the initial
938\c{game_state}, in case it needs to refer to that when setting up the
939initial values for the new game.
940
941However, if the puzzle defines \c{get_prefs()} and \c{set_prefs()}
942functions, then this function may also be called with
943\cw{state==NULL}. In this situation it must still allocate a
944\c{game_ui} which can be used by \c{get_prefs()} and \c{set_prefs()},
945although it need not be usable for actually playing a game.
830 946
831\S{backend-free-ui} \cw{free_ui()} 947\S{backend-free-ui} \cw{free_ui()}
832 948
@@ -840,8 +956,8 @@ allocations contained within it.
840\c char *(*encode_ui)(const game_ui *ui); 956\c char *(*encode_ui)(const game_ui *ui);
841 957
842This function encodes any \e{important} data in a \c{game_ui} 958This function encodes any \e{important} data in a \c{game_ui}
843structure in string form. It is only called when saving a 959structure in printable ASCII string form. It is only called when
844half-finished game to a file. 960saving a half-finished game to a file.
845 961
846It should be used sparingly. Almost all data in a \c{game_ui} is not 962It should be used sparingly. Almost all data in a \c{game_ui} is not
847important enough to save. The location of the keyboard-controlled 963important enough to save. The location of the keyboard-controlled
@@ -859,13 +975,25 @@ user could edit the save file by hand... But if the user is \e{that}
859determined to cheat, they could just as easily modify the game's 975determined to cheat, they could just as easily modify the game's
860source.) 976source.)
861 977
978The \cw{encode_ui()} function is optional. If a back-end doesn't need
979this function it can just set the pointer to \cw{NULL}.
980
862\S{backend-decode-ui} \cw{decode_ui()} 981\S{backend-decode-ui} \cw{decode_ui()}
863 982
864\c void (*decode_ui)(game_ui *ui, const char *encoding); 983\c void (*decode_ui)(game_ui *ui, const char *encoding,
984\c const game_state *state);
865 985
866This function parses a string previously output by \cw{encode_ui()}, 986This function parses a string previously output by \cw{encode_ui()},
867and writes the decoded data back into the provided \c{game_ui} 987and writes the decoded data back into the freshly-created \c{game_ui}
868structure. 988structure provided. If the string is invalid, the function should do
989the best it can, which might just mean not changing the \c{game_ui}
990structure at all. This might happen if a save file is corrupted, or
991simply from a newer version that encodes more \c{game_ui} data. The
992current \c{game_state} is provided in case the function needs to
993refer to it for validation.
994
995Like \cw{encode_ui()}, \cw{decode_ui()} is optional. If a back-end
996doesn't need this function it can just set the pointer to \cw{NULL}.
869 997
870\S{backend-changed-state} \cw{changed_state()} 998\S{backend-changed-state} \cw{changed_state()}
871 999
@@ -928,13 +1056,18 @@ puzzle's drawing area.
928pointer will be to read the game's tile size parameter in order to 1056pointer will be to read the game's tile size parameter in order to
929divide mouse coordinates by it.) 1057divide mouse coordinates by it.)
930 1058
931\cw{interpret_move()} may return in three different ways: 1059\cw{interpret_move()} may return in four different ways:
932 1060
933\b Returning \cw{NULL} indicates that no action whatsoever occurred 1061\b Returning \cw{MOVE_UNUSED} or \cw{MOVE_NO_EFFECT} indicates that no
934in response to the input event; the puzzle was not interested in it 1062action whatsoever occurred in response to the input event; the puzzle
935at all. 1063was not interested in it at all. The distinction between this is that
1064\cw{MOVE_NO_EFFECT} implies that the state of the game is what makes
1065the event uninteresting, while \cw{MOVE_NO_EFFECT} means that the
1066event is intrinsically uninteresting. For example, a mouse click on
1067an already-revealed square in Mines might return \cw{MOVE_NO_EFFECT}
1068while a click outside the board would return \cw{MOVE_UNUSED}.
936 1069
937\b Returning the special value \cw{UI_UPDATE} indicates that the input 1070\b Returning the special value \cw{MOVE_UI_UPDATE} indicates that the input
938event has resulted in a change being made to the \c{game_ui} which 1071event has resulted in a change being made to the \c{game_ui} which
939will require a redraw of the game window, but that no actual \e{move} 1072will require a redraw of the game window, but that no actual \e{move}
940was made (i.e. no new \c{game_state} needs to be created). 1073was made (i.e. no new \c{game_state} needs to be created).
@@ -942,8 +1075,8 @@ was made (i.e. no new \c{game_state} needs to be created).
942\b Returning anything else indicates that a move was made and that a 1075\b Returning anything else indicates that a move was made and that a
943new \c{game_state} must be created. However, instead of actually 1076new \c{game_state} must be created. However, instead of actually
944constructing a new \c{game_state} itself, this function is required 1077constructing a new \c{game_state} itself, this function is required
945to return a string description of the details of the move. This 1078to return a printable ASCII string description of the details of the
946string will be passed to \cw{execute_move()} 1079move. This string will be passed to \cw{execute_move()}
947(\k{backend-execute-move}) to actually create the new 1080(\k{backend-execute-move}) to actually create the new
948\c{game_state}. (Encoding moves as strings in this way means that 1081\c{game_state}. (Encoding moves as strings in this way means that
949the mid-end can keep the strings as well as the game states, and the 1082the mid-end can keep the strings as well as the game states, and the
@@ -952,7 +1085,8 @@ strings can be written to disk when saving the game and fed to
952 1085
953The return value from \cw{interpret_move()} is expected to be 1086The return value from \cw{interpret_move()} is expected to be
954dynamically allocated if and only if it is not either \cw{NULL} 1087dynamically allocated if and only if it is not either \cw{NULL}
955\e{or} the special string constant \c{UI_UPDATE}. 1088\e{or} one of the special string constants \cw{MOVE_UNUSED},
1089\cw{MOVE_NO_EFFECT}, or \cw{MOVE_UI_UPDATE}.
956 1090
957After this function is called, the back end is permitted to rely on 1091After this function is called, the back end is permitted to rely on
958some subsequent operations happening in sequence: 1092some subsequent operations happening in sequence:
@@ -999,19 +1133,21 @@ mouse button will have appeared in between.
999 1133
1000\dd Indicate that an arrow key was pressed. 1134\dd Indicate that an arrow key was pressed.
1001 1135
1002\dt \cw{CURSOR_SELECT} 1136\dt \cw{CURSOR_SELECT}, \cw{CURSOR_SELECT2}
1003 1137
1004\dd On platforms which have a prominent \q{select} button alongside 1138\dd On platforms which have one or two prominent \q{select} button
1005their cursor keys, indicates that that button was pressed. 1139alongside their cursor keys, indicates that one of those buttons was
1140pressed. On other platforms, these represent the Enter (or Return)
1141and Space keys respectively.
1006 1142
1007In addition, there are some modifiers which can be bitwise-ORed into 1143In addition, there are some modifiers which can be bitwise-ORed into
1008the \c{button} parameter: 1144the \c{button} parameter:
1009 1145
1010\dt \cw{MOD_CTRL}, \cw{MOD_SHFT} 1146\dt \cw{MOD_CTRL}, \cw{MOD_SHFT}
1011 1147
1012\dd These indicate that the Control or Shift key was pressed 1148\dd These indicate that the Control or Shift key was pressed alongside
1013alongside the key. They only apply to the cursor keys, not to mouse 1149the key. They only apply to the cursor keys and the ASCII horizontal
1014buttons or anything else. 1150tab character \cw{\\t}, not to mouse buttons or anything else.
1015 1151
1016\dt \cw{MOD_NUM_KEYPAD} 1152\dt \cw{MOD_NUM_KEYPAD}
1017 1153
@@ -1025,8 +1161,10 @@ input probably just wants to treat the numeric keypad as numbers).
1025\dt \cw{MOD_MASK} 1161\dt \cw{MOD_MASK}
1026 1162
1027\dd This mask is the bitwise OR of all the available modifiers; you 1163\dd This mask is the bitwise OR of all the available modifiers; you
1028can bitwise-AND with \cw{~MOD_MASK} to strip all the modifiers off 1164can bitwise-AND with \cw{~MOD_MASK} to strip all the modifiers off any
1029any input value. 1165input value; as this is a common operation, the
1166\cw{STRIP_BUTTON_MODIFIERS()} macro can do this for you (see
1167\k{utils-strip-button-modifiers}).
1030 1168
1031\S{backend-execute-move} \cw{execute_move()} 1169\S{backend-execute-move} \cw{execute_move()}
1032 1170
@@ -1058,7 +1196,8 @@ offer the \q{Solve} menu option.
1058\c const char *aux, const char **error); 1196\c const char *aux, const char **error);
1059 1197
1060This function is called when the user selects the \q{Solve} option 1198This function is called when the user selects the \q{Solve} option
1061from the menu. 1199from the menu. If \cw{can_solve} is \cw{false} then it will never
1200be called and can be \cw{NULL}.
1062 1201
1063It is passed two input game states: \c{orig} is the game state from 1202It is passed two input game states: \c{orig} is the game state from
1064the very start of the puzzle, and \c{curr} is the current one. 1203the very start of the puzzle, and \c{curr} is the current one.
@@ -1075,8 +1214,8 @@ it may return \cw{NULL}. If it does this, it must also set
1075\q{Solution not known for this puzzle}); that error message is not 1214\q{Solution not known for this puzzle}); that error message is not
1076expected to be dynamically allocated. 1215expected to be dynamically allocated.
1077 1216
1078If this function \e{does} produce a solution, it returns a move string 1217If this function \e{does} produce a solution, it returns a printable
1079suitable for feeding to \cw{execute_move()} 1218ASCII move string suitable for feeding to \cw{execute_move()}
1080(\k{backend-execute-move}). Like a (non-empty) string returned from 1219(\k{backend-execute-move}). Like a (non-empty) string returned from
1081\cw{interpret_move()}, the returned string should be dynamically 1220\cw{interpret_move()}, the returned string should be dynamically
1082allocated. 1221allocated.
@@ -1132,15 +1271,15 @@ requirement that the \q{tile size} be proportional to the game
1132window size. Window size is required to increase monotonically with 1271window size. Window size is required to increase monotonically with
1133\q{tile size}, however. 1272\q{tile size}, however.
1134 1273
1135The data element \c{preferred_tilesize} indicates the tile size 1274The data element \c{preferred_tilesize} indicates the tile size which
1136which should be used in the absence of a good reason to do otherwise 1275should be used in the absence of a good reason to do otherwise (such
1137(such as the screen being too small, or the user explicitly 1276as the screen being too small to fit the whole puzzle, or the user
1138requesting a resize if that ever gets implemented). 1277explicitly requesting a resize).
1139 1278
1140\S{backend-compute-size} \cw{compute_size()} 1279\S{backend-compute-size} \cw{compute_size()}
1141 1280
1142\c void (*compute_size)(const game_params *params, int tilesize, 1281\c void (*compute_size)(const game_params *params, int tilesize,
1143\c int *x, int *y); 1282\c const game_ui *ui, int *x, int *y);
1144 1283
1145This function is passed a \c{game_params} structure and a tile size. 1284This function is passed a \c{game_params} structure and a tile size.
1146It returns, in \c{*x} and \c{*y}, the size in pixels of the drawing 1285It returns, in \c{*x} and \c{*y}, the size in pixels of the drawing
@@ -1193,6 +1332,12 @@ end's default colour as their background, apart from a few which
1193depend on drawing relief highlights so they adjust the background 1332depend on drawing relief highlights so they adjust the background
1194colour if it's too light for highlights to show up against it. 1333colour if it's too light for highlights to show up against it.
1195 1334
1335The first colour in the list is slightly special. The mid-end fills
1336the drawing area with it before the first call to \cw{redraw()} (see
1337\k{backend-redraw}). Some front ends also use it fill the part of the
1338puzzle window outside the puzzle. This means that it is usually
1339sensible to make colour 0 the background colour for the puzzle.
1340
1196Note that the colours returned from this function are for 1341Note that the colours returned from this function are for
1197\e{drawing}, not for printing. Printing has an entirely different 1342\e{drawing}, not for printing. Printing has an entirely different
1198colour allocation policy. 1343colour allocation policy.
@@ -1275,7 +1420,7 @@ activity, so that the victory flash in Net is not cancelled by that
1275final locking move. 1420final locking move.
1276 1421
1277The input parameters to \cw{flash_length()} are exactly the same as 1422The input parameters to \cw{flash_length()} are exactly the same as
1278the ones to \cw{anim_length()}. 1423the ones to \cw{anim_length()}: see \k{backend-anim-length}.
1279 1424
1280Just like \cw{anim_length()}, when this function is called, it may 1425Just like \cw{anim_length()}, when this function is called, it may
1281rely on \cw{changed_state()} having been called previously, so if it 1426rely on \cw{changed_state()} having been called previously, so if it
@@ -1303,7 +1448,7 @@ containing the cursor (in games that have one), or other region of
1303interest. 1448interest.
1304 1449
1305This function is called by only 1450This function is called by only
1306\cw{midend_get_cursor_location()}(\k{midend-get-cursor-location}). Its 1451\cw{midend_get_cursor_location()} (\k{midend-get-cursor-location}). Its
1307purpose is to allow front ends to query the location of the backend's 1452purpose is to allow front ends to query the location of the backend's
1308cursor. With knowledge of this location, a front end can, for example, 1453cursor. With knowledge of this location, a front end can, for example,
1309ensure that the region of interest remains visible if the puzzle is 1454ensure that the region of interest remains visible if the puzzle is
@@ -1392,6 +1537,14 @@ that the animation has already been running. If \c{oldstate} is
1392\cw{NULL}, then \c{anim_time} is unused (and will hopefully be set 1537\cw{NULL}, then \c{anim_time} is unused (and will hopefully be set
1393to zero to avoid confusion). 1538to zero to avoid confusion).
1394 1539
1540\c{dir} specifies the chronological order of those states: if it is
1541positive, then the transition is the result of a move or a redo (and
1542so \c{newstate} is the later of the two moves), whereas if it is
1543negative then the transition is the result of an undo (so that
1544\c{newstate} is the \e{earlier} move). This allows move animations
1545that are not time-symmetric (such as Inertia, where gems are consumed
1546during the animation) to be drawn the right way round.
1547
1395\c{flash_time}, if it is is non-zero, denotes that the game is in 1548\c{flash_time}, if it is is non-zero, denotes that the game is in
1396the middle of a flash, and gives the time since the start of the 1549the middle of a flash, and gives the time since the start of the
1397flash. See \k{backend-flash-length} for general discussion of 1550flash. See \k{backend-flash-length} for general discussion of
@@ -1402,7 +1555,9 @@ The very first time this function is called for a new
1402area. Since this often involves drawing visual furniture which is 1555area. Since this often involves drawing visual furniture which is
1403never subsequently altered, it is often simplest to arrange this by 1556never subsequently altered, it is often simplest to arrange this by
1404having a special \q{first time} flag in the draw state, and 1557having a special \q{first time} flag in the draw state, and
1405resetting it after the first redraw. 1558resetting it after the first redraw. This function can assume that
1559the mid-end has filled the drawing area with colour 0 before the first
1560call.
1406 1561
1407When this function (or any subfunction) calls the drawing API, it is 1562When this function (or any subfunction) calls the drawing API, it is
1408expected to pass colour indices which were previously defined by the 1563expected to pass colour indices which were previously defined by the
@@ -1424,7 +1579,7 @@ Twiddle, inherently involve moving things around and so would not
1424make sense to print.) 1579make sense to print.)
1425 1580
1426If this flag is \cw{false}, then the functions \cw{print_size()} 1581If this flag is \cw{false}, then the functions \cw{print_size()}
1427and \cw{print()} will never be called. 1582and \cw{print()} will never be called and can be \cw{NULL}.
1428 1583
1429\S{backend-can-print-in-colour} \c{can_print_in_colour} 1584\S{backend-can-print-in-colour} \c{can_print_in_colour}
1430 1585
@@ -1440,18 +1595,20 @@ ignored.
1440 1595
1441\S{backend-print-size} \cw{print_size()} 1596\S{backend-print-size} \cw{print_size()}
1442 1597
1443\c void (*print_size)(const game_params *params, float *x, float *y); 1598\c void (*print_size)(const game_params *params, const game_ui *ui,
1599\c float *x, float *y);
1444 1600
1445This function is passed a \c{game_params} structure and a tile size. 1601This function is passed a \c{game_params} structure and a tile size.
1446It returns, in \c{*x} and \c{*y}, the preferred size in 1602It returns, in \c{*x} and \c{*y}, the preferred size in
1447\e{millimetres} of that puzzle if it were to be printed out on paper. 1603\e{millimetres} of that puzzle if it were to be printed out on paper.
1448 1604
1449If the \c{can_print} flag is \cw{FALSE}, this function will never be 1605If the \c{can_print} flag is \cw{false}, this function will never be
1450called. 1606called.
1451 1607
1452\S{backend-print} \cw{print()} 1608\S{backend-print} \cw{print()}
1453 1609
1454\c void (*print)(drawing *dr, const game_state *state, int tilesize); 1610\c void (*print)(drawing *dr, const game_state *state,
1611\c const game_ui *ui, int tilesize);
1455 1612
1456This function is called when a puzzle is to be printed out on paper. 1613This function is called when a puzzle is to be printed out on paper.
1457It should use the drawing API functions (see \k{drawing}) to print 1614It should use the drawing API functions (see \k{drawing}) to print
@@ -1500,7 +1657,7 @@ write
1500\c c = print_mono_colour(dr, 0); assert(c == COL_THIS); 1657\c c = print_mono_colour(dr, 0); assert(c == COL_THIS);
1501\c c = print_mono_colour(dr, 0); assert(c == COL_THAT); 1658\c c = print_mono_colour(dr, 0); assert(c == COL_THAT);
1502 1659
1503If the \c{can_print} flag is \cw{FALSE}, this function will never be 1660If the \c{can_print} flag is \cw{false}, this function will never be
1504called. 1661called.
1505 1662
1506\H{backend-misc} Miscellaneous 1663\H{backend-misc} Miscellaneous
@@ -1522,7 +1679,8 @@ just too difficult.
1522 1679
1523If this field is \cw{false}, the functions 1680If this field is \cw{false}, the functions
1524\cw{can_format_as_text_now()} (\k{backend-can-format-as-text-now}) 1681\cw{can_format_as_text_now()} (\k{backend-can-format-as-text-now})
1525and \cw{text_format()} (\k{backend-text-format}) are never called. 1682and \cw{text_format()} (\k{backend-text-format}) are never called
1683and can be \cw{NULL}.
1526 1684
1527\S{backend-can-format-as-text-now} \c{can_format_as_text_now()} 1685\S{backend-can-format-as-text-now} \c{can_format_as_text_now()}
1528 1686
@@ -1544,7 +1702,7 @@ game of exactly the same type is generated.
1544This function should not take into account aspects of the game 1702This function should not take into account aspects of the game
1545parameters which are not encoded by \cw{encode_params()} 1703parameters which are not encoded by \cw{encode_params()}
1546(\k{backend-encode-params}) when the \c{full} parameter is set to 1704(\k{backend-encode-params}) when the \c{full} parameter is set to
1547\cw{FALSE}. Such parameters will not necessarily match up between a 1705\cw{false}. Such parameters will not necessarily match up between a
1548call to this function and a subsequent call to \cw{text_format()} 1706call to this function and a subsequent call to \cw{text_format()}
1549itself. (For instance, game \e{difficulty} should not affect whether 1707itself. (For instance, game \e{difficulty} should not affect whether
1550the game can be copied to the clipboard. Only the actual visible 1708the game can be copied to the clipboard. Only the actual visible
@@ -1561,8 +1719,8 @@ ends.
1561 1719
1562This function will only ever be called if the back end field 1720This function will only ever be called if the back end field
1563\c{can_format_as_text_ever} (\k{backend-can-format-as-text-ever}) is 1721\c{can_format_as_text_ever} (\k{backend-can-format-as-text-ever}) is
1564\cw{TRUE} \e{and} the function \cw{can_format_as_text_now()} 1722\cw{true} \e{and} the function \cw{can_format_as_text_now()}
1565(\k{backend-can-format-as-text-now}) has returned \cw{TRUE} for the 1723(\k{backend-can-format-as-text-now}) has returned \cw{true} for the
1566currently selected game parameters. 1724currently selected game parameters.
1567 1725
1568The returned string may contain line endings (and will probably want 1726The returned string may contain line endings (and will probably want
@@ -1579,7 +1737,9 @@ whether that should come with a newline or not.)
1579 1737
1580This field is set to \cw{true} if the puzzle has a use for a textual 1738This field is set to \cw{true} if the puzzle has a use for a textual
1581status line (to display score, completion status, currently active 1739status line (to display score, completion status, currently active
1582tiles, etc). 1740tiles, etc). If the \c{redraw()} function ever intends to call
1741\c{status_bar()} in the drawing API (\k{drawing-status-bar}), then it
1742should set this flag to \c{true}.
1583 1743
1584\S{backend-is-timed} \c{is_timed} 1744\S{backend-is-timed} \c{is_timed}
1585 1745
@@ -1589,7 +1749,7 @@ This field is \cw{true} if the puzzle is time-critical. If
1589so, the mid-end will maintain a game timer while the user plays. 1749so, the mid-end will maintain a game timer while the user plays.
1590 1750
1591If this field is \cw{false}, then \cw{timing_state()} will never be 1751If this field is \cw{false}, then \cw{timing_state()} will never be
1592called and need not do anything. 1752called and can be \cw{NULL}.
1593 1753
1594\S{backend-timing-state} \cw{timing_state()} 1754\S{backend-timing-state} \cw{timing_state()}
1595 1755
@@ -1618,7 +1778,7 @@ the game size and the backspace character, \cw{\\b}, even though it
1618play the game. Each \cw{key_label} item contains the following fields: 1778play the game. Each \cw{key_label} item contains the following fields:
1619 1779
1620\c struct key_label { 1780\c struct key_label {
1621\c const char *label; /* label for frontend use */ 1781\c char *label; /* label for frontend use */
1622\c int button; /* button to pass to midend */ 1782\c int button; /* button to pass to midend */
1623\c } key_label; 1783\c } key_label;
1624 1784
@@ -1628,6 +1788,12 @@ the backend to \cw{NULL}, in which case the midend will instead call
1628label. The \cw{button} field is the associated code that can be passed 1788label. The \cw{button} field is the associated code that can be passed
1629to the midend when the frontend deems appropriate. 1789to the midend when the frontend deems appropriate.
1630 1790
1791If \cw{label} is not \cw{NULL}, then it's a dynamically allocated
1792string. Therefore, freeing an array of these structures needs more
1793than just a single free operatio. The function \c{free_keys()}
1794(\k{utils-free-keys}) can be used to free a whole array of these
1795structures conveniently.
1796
1631The backend should set \cw{*nkeys} to the number of elements in the 1797The backend should set \cw{*nkeys} to the number of elements in the
1632returned array. 1798returned array.
1633 1799
@@ -1640,6 +1806,44 @@ This function should not be called directly by frontends. Instead,
1640frontends should use \cw{midend_request_keys()} 1806frontends should use \cw{midend_request_keys()}
1641(\k{midend-request-keys}). 1807(\k{midend-request-keys}).
1642 1808
1809\S{backend-current-key-label} \cw{current_key_label()}
1810
1811\c const char *(*current_key_label)(const game_ui *ui,
1812\c const game_state *state,
1813\c int button);
1814
1815This function is called to ask the back-end how certain keys should be
1816labelled on platforms (such a feature phones) where this is
1817conventional.
1818These labels are expected to reflect what the keys will do right now,
1819so they can change depending on the game and UI state.
1820
1821The \c{ui} and \c{state} arguments describe the state of the game for
1822which key labels are required.
1823The \c{button} argument is the same as the one passed to
1824\cw{interpret_move()}.
1825At present, the only values of \c{button} that can be passed to
1826\cw{current_key_label()} are \cw{CURSOR_SELECT} and \cw{CURSOR_SELECT2}.
1827The return value is a short string describing what the requested key
1828will do if pressed.
1829Usually the string should be a static string constant.
1830If it's really necessary to use a dynamically-allocated string, it
1831should remain valid until the next call to \cw{current_key_label()} or
1832\cw{free_ui()} with the same \cw{game_ui} (so it can be referenced from
1833the \cw{game_ui} and freed at the next one of those calls).
1834
1835There's no fixed upper limit on the length of string that this
1836function can return, but more than about 12 characters is likely to
1837cause problems for front-ends. If two buttons have the same effect,
1838their labels should be identical so that the front end can detect
1839this. Similarly, keys that do different things should have different
1840labels. The label should be an empty string (\cw{""}) if the key does
1841nothing.
1842
1843Like \cw{request_keys()}, the \cw{current_key_label} pointer in the
1844\c{game} structure is allowed to be \cw{NULL}, in which case the
1845mid-end will treat it as though it always returned \cw{""}.
1846
1643\S{backend-flags} \c{flags} 1847\S{backend-flags} \c{flags}
1644 1848
1645\c int flags; 1849\c int flags;
@@ -1754,12 +1958,13 @@ whatever it was you needed to do.
1754\C{drawing} The drawing API 1958\C{drawing} The drawing API
1755 1959
1756The back end function \cw{redraw()} (\k{backend-redraw}) is required 1960The back end function \cw{redraw()} (\k{backend-redraw}) is required
1757to draw the puzzle's graphics on the window's drawing area, or on 1961to draw the puzzle's graphics on the window's drawing area. The back
1758paper if the puzzle is printable. To do this portably, it is 1962end function \cw{print()} similarly draws the puzzle on paper, if the
1759provided with a drawing API allowing it to talk directly to the 1963puzzle is printable. To do this portably, the back end is provided
1760front end. In this chapter I document that API, both for the benefit 1964with a drawing API allowing it to talk directly to the front end. In
1761of back end authors trying to use it and for front end authors 1965this chapter I document that API, both for the benefit of back end
1762trying to implement it. 1966authors trying to use it and for front end authors trying to implement
1967it.
1763 1968
1764The drawing API as seen by the back end is a collection of global 1969The drawing API as seen by the back end is a collection of global
1765functions, each of which takes a pointer to a \c{drawing} structure 1970functions, each of which takes a pointer to a \c{drawing} structure
@@ -1911,6 +2116,22 @@ implement it, since it is actually implemented centrally (in
1911 2116
1912This function may be used for both drawing and printing. 2117This function may be used for both drawing and printing.
1913 2118
2119\S{drawing-draw-rect-corner} \cw{draw_rect_corners()}
2120
2121\c void draw_rect_corners(drawing *dr, int cx, int cy, int r, int col);
2122
2123Draws four L-shapes at the corners of a square, in the manner of a
2124target reticule. This is a convenience function for back ends to use
2125to display a keyboard cursor (if they want one in that style).
2126
2127\c{cx} and \c{cy} give the coordinates of the centre of the square.
2128\c{r} is half the side length of the square, so that the corners are
2129at \cw{(cx-r,cy-r)}, \cw{(cx+r,cy-r)}, \cw{(cx-r,cy+r)} and
2130\cw{(cx+r,cy+r)}.
2131
2132\c{colour} is an integer index into the colours array returned by
2133the back end function \cw{colours()} (\k{backend-colours}).
2134
1914\S{drawing-draw-line} \cw{draw_line()} 2135\S{drawing-draw-line} \cw{draw_line()}
1915 2136
1916\c void draw_line(drawing *dr, int x1, int y1, int x2, int y2, 2137\c void draw_line(drawing *dr, int x1, int y1, int x2, int y2,
@@ -1935,7 +2156,7 @@ This function may be used for both drawing and printing.
1935 2156
1936\S{drawing-draw-polygon} \cw{draw_polygon()} 2157\S{drawing-draw-polygon} \cw{draw_polygon()}
1937 2158
1938\c void draw_polygon(drawing *dr, int *coords, int npoints, 2159\c void draw_polygon(drawing *dr, const int *coords, int npoints,
1939\c int fillcolour, int outlinecolour); 2160\c int fillcolour, int outlinecolour);
1940 2161
1941Draws an outlined or filled polygon in the puzzle window. 2162Draws an outlined or filled polygon in the puzzle window.
@@ -2133,6 +2354,7 @@ multiplication sign (U+00D7 in Unicode, represented by the bytes C3
2133\c static const char *const times_signs[] = { "\xC3\x97", "x" }; 2354\c static const char *const times_signs[] = { "\xC3\x97", "x" };
2134\c char *times_sign = text_fallback(dr, times_signs, 2); 2355\c char *times_sign = text_fallback(dr, times_signs, 2);
2135\c sprintf(buffer, "%d%s%d", width, times_sign, height); 2356\c sprintf(buffer, "%d%s%d", width, times_sign, height);
2357\c sfree(times_sign);
2136\c draw_text(dr, x, y, font, size, align, colour, buffer); 2358\c draw_text(dr, x, y, font, size, align, colour, buffer);
2137\c sfree(buffer); 2359\c sfree(buffer);
2138 2360
@@ -2211,8 +2433,9 @@ modify the buffer after use.
2211 2433
2212(This function is not exactly a \e{drawing} function, but it shares 2434(This function is not exactly a \e{drawing} function, but it shares
2213with the drawing API the property that it may only be called from 2435with the drawing API the property that it may only be called from
2214within the back end redraw function, so this is as good a place as 2436within the back end redraw function. And it's implemented by front
2215any to document it.) 2437ends via the \c{drawing_api} function pointer table. So this is the
2438best place to document it.)
2216 2439
2217The supplied text is filtered through the mid-end for optional 2440The supplied text is filtered through the mid-end for optional
2218rewriting before being passed on to the front end; the mid-end will 2441rewriting before being passed on to the front end; the mid-end will
@@ -2497,7 +2720,7 @@ function; see \k{drawing-draw-line}.
2497 2720
2498\S{drawingapi-draw-polygon} \cw{draw_polygon()} 2721\S{drawingapi-draw-polygon} \cw{draw_polygon()}
2499 2722
2500\c void (*draw_polygon)(void *handle, int *coords, int npoints, 2723\c void (*draw_polygon)(void *handle, const int *coords, int npoints,
2501\c int fillcolour, int outlinecolour); 2724\c int fillcolour, int outlinecolour);
2502 2725
2503This function behaves exactly like the back end \cw{draw_polygon()} 2726This function behaves exactly like the back end \cw{draw_polygon()}
@@ -2750,6 +2973,17 @@ Implementations of this API which do not provide printing services
2750may define this function pointer to be \cw{NULL}; it will never be 2973may define this function pointer to be \cw{NULL}; it will never be
2751called unless printing is attempted. 2974called unless printing is attempted.
2752 2975
2976\S{drawingapi-line-dotted} \cw{line_dotted()}
2977
2978\c void (*line_dotted)(void *handle, bool dotted);
2979
2980This function is called to toggle drawing of dotted lines, during
2981printing only.
2982
2983Implementations of this API which do not provide printing services
2984may define this function pointer to be \cw{NULL}; it will never be
2985called unless printing is attempted.
2986
2753\S{drawingapi-text-fallback} \cw{text_fallback()} 2987\S{drawingapi-text-fallback} \cw{text_fallback()}
2754 2988
2755\c char *(*text_fallback)(void *handle, const char *const *strings, 2989\c char *(*text_fallback)(void *handle, const char *const *strings,
@@ -2796,16 +3030,17 @@ the front end.
2796 3030
2797\S{drawing-print-get-colour} \cw{print_get_colour()} 3031\S{drawing-print-get-colour} \cw{print_get_colour()}
2798 3032
2799\c void print_get_colour(drawing *dr, int colour, int printincolour, 3033\c void print_get_colour(drawing *dr, int colour,
2800\c int *hatch, float *r, float *g, float *b) 3034\c bool printing_in_colour,
3035\c int *hatch, float *r, float *g, float *b);
2801 3036
2802This function is called by the implementations of the drawing API 3037This function is called by the implementations of the drawing API
2803functions when they are called in a printing context. It takes a 3038functions when they are called in a printing context. It takes a
2804colour index as input, and returns the description of the colour as 3039colour index as input, and returns the description of the colour as
2805requested by the back end. 3040requested by the back end.
2806 3041
2807\c{printincolour} is \cw{TRUE} iff the implementation is printing in 3042\c{printing_in_colour} is \cw{true} iff the implementation is printing
2808colour. This will alter the results returned if the colour in 3043in colour. This will alter the results returned if the colour in
2809question was specified with a black-and-white fallback value. 3044question was specified with a black-and-white fallback value.
2810 3045
2811If the colour should be rendered by hatching, \c{*hatch} is filled 3046If the colour should be rendered by hatching, \c{*hatch} is filled
@@ -2835,7 +3070,7 @@ puzzle window.
2835\H{midend-new} \cw{midend_new()} 3070\H{midend-new} \cw{midend_new()}
2836 3071
2837\c midend *midend_new(frontend *fe, const game *ourgame, 3072\c midend *midend_new(frontend *fe, const game *ourgame,
2838\c const drawing_api *drapi, void *drhandle) 3073\c const drawing_api *drapi, void *drhandle);
2839 3074
2840Allocates and returns a new mid-end structure. 3075Allocates and returns a new mid-end structure.
2841 3076
@@ -2898,7 +3133,8 @@ when finished with by passing it to the game's own
2898 3133
2899\H{midend-size} \cw{midend_size()} 3134\H{midend-size} \cw{midend_size()}
2900 3135
2901\c void midend_size(midend *me, int *x, int *y, bool user_size); 3136\c void midend_size(midend *me, int *x, int *y,
3137\c bool user_size, double device_pixel_ratio);
2902 3138
2903Tells the mid-end to figure out its window size. 3139Tells the mid-end to figure out its window size.
2904 3140
@@ -2926,7 +3162,7 @@ by the user. Use this option if you want your front end to support
2926dynamic resizing of the puzzle window with automatic scaling of the 3162dynamic resizing of the puzzle window with automatic scaling of the
2927puzzle to fit. 3163puzzle to fit.
2928 3164
2929If \c{user_size} is set to \cw{FALSE}, then the game's tile size 3165If \c{user_size} is set to \cw{false}, then the game's tile size
2930will never go over its preferred one, although it may go under in 3166will never go over its preferred one, although it may go under in
2931order to fit within the maximum bounds specified by \c{*x} and 3167order to fit within the maximum bounds specified by \c{*x} and
2932\c{*y}. This is the recommended approach when opening a new window 3168\c{*y}. This is the recommended approach when opening a new window
@@ -2955,6 +3191,24 @@ to use scroll bars for large puzzles), you can pass dimensions of
2955\cw{INT_MAX} as input to this function. You should probably not do 3191\cw{INT_MAX} as input to this function. You should probably not do
2956that \e{and} set the \c{user_size} flag, though! 3192that \e{and} set the \c{user_size} flag, though!
2957 3193
3194The \cw{device_pixel_ratio} allows the front end to specify that its
3195pixels are unusually large or small (or should be treated as such).
3196The mid-end uses this to adjust the tile size, both at startup (if the
3197ratio is not 1) and if the ratio changes.
3198
3199A \cw{device_pixel_ratio} of 1 indicates normal-sized pixels.
3200\q{Normal} is not precisely defined, but it's about 4 pixels per
3201millimetre on a screen designed to be viewed from a metre away, or a
3202size such that text 15 pixels high is comfortably readable. Some
3203platforms have a concept of a logical pixel that this can be mapped
3204onto. For instance, Cascading Style Sheets (CSS) has a unit called
3205\cq{px} that only matches physical pixels at a \cw{device_pixel_ratio}
3206of 1.
3207
3208The \cw{device_pixel_ratio} indicates the number of physical pixels in
3209a normal-sized pixel, so values less than 1 indicate unusually large
3210pixels and values greater than 1 indicate unusually small pixels.
3211
2958The midend relies on the frontend calling \cw{midend_new_game()} 3212The midend relies on the frontend calling \cw{midend_new_game()}
2959(\k{midend-new-game}) before calling \cw{midend_size()}. 3213(\k{midend-new-game}) before calling \cw{midend_size()}.
2960 3214
@@ -2972,7 +3226,7 @@ the puzzle configuration changes. If you \e{don't} want that, e.g. if
2972you want to provide a command to explicitly reset the puzzle size back 3226you want to provide a command to explicitly reset the puzzle size back
2973to its default, then you can call this just before calling 3227to its default, then you can call this just before calling
2974\cw{midend_size()} (which, in turn, you would probably call with 3228\cw{midend_size()} (which, in turn, you would probably call with
2975\c{user_size} set to \cw{FALSE}). 3229\c{user_size} set to \cw{false}).
2976 3230
2977\H{midend-new-game} \cw{midend_new_game()} 3231\H{midend-new-game} \cw{midend_new_game()}
2978 3232
@@ -3039,14 +3293,19 @@ call to this function. Some back ends require that \cw{midend_size()}
3039 3293
3040\H{midend-process-key} \cw{midend_process_key()} 3294\H{midend-process-key} \cw{midend_process_key()}
3041 3295
3042\c bool midend_process_key(midend *me, int x, int y, int button); 3296\c int midend_process_key(midend *me, int x, int y, int button)
3297
3298The front end calls this function to report a mouse or keyboard event.
3299The parameters \c{x} and \c{y} are identical to the ones passed to the
3300back end function \cw{interpret_move()} (\k{backend-interpret-move}).
3043 3301
3044The front end calls this function to report a mouse or keyboard 3302\c{button} is similar to the parameter passed to
3045event. The parameters \c{x}, \c{y} and \c{button} are almost 3303\cw{interpret_move()}. However, the midend is more relaxed about
3046identical to the ones passed to the back end function 3304values passed to in, and some additional special button values
3047\cw{interpret_move()} (\k{backend-interpret-move}), except that the 3305are defined for the front end to pass to the midend (see below).
3048front end is \e{not} required to provide the guarantees about mouse 3306
3049event ordering. The mid-end will sort out multiple simultaneous 3307Also, the front end is \e{not} required to provide guarantees about
3308mouse event ordering. The mid-end will sort out multiple simultaneous
3050button presses and changes of button; the front end's responsibility 3309button presses and changes of button; the front end's responsibility
3051is simply to pass on the mouse events it receives as accurately as 3310is simply to pass on the mouse events it receives as accurately as
3052possible. 3311possible.
@@ -3072,10 +3331,71 @@ Calling this function is very likely to result in calls back to the
3072front end's drawing API and/or \cw{activate_timer()} 3331front end's drawing API and/or \cw{activate_timer()}
3073(\k{frontend-activate-timer}). 3332(\k{frontend-activate-timer}).
3074 3333
3075The return value from \cw{midend_process_key()} is \cw{true} unless 3334The return value from \cw{midend_process_key()} is one of the
3076the effect of the keypress was to request termination of the program. 3335following constants:
3077A front end should shut down the puzzle in response to a \cw{false} 3336
3078return. 3337\dt \cw{PKR_QUIT}
3338
3339\dd Means that the effect of the keypress was to request termination
3340of the program. A front end should shut down the puzzle in response
3341to a \cw{PKR_QUIT} return.
3342
3343\dt \cw{PKR_SOME_EFFECT}
3344
3345\dd The keypress had some other effect, either in the mid-end or in
3346the puzzle itself.
3347
3348\dt \cw{PKR_NO_EFFECT}
3349
3350\dd The keypress had no effect, but might have had an effect in
3351slightly different circumstances. For instance it requested a move
3352that wasn't possible.
3353
3354\dt \cw{PKR_UNUSED}
3355
3356\dd The key was one that neither the mid-end nor the back-end has any
3357use for at all.
3358
3359A front end might respond to the last value by passing the key on to
3360something else that might be interested in it.
3361
3362The following additional values of \c{button} are permitted to be
3363passed to this function by the front end, but are never passed on to
3364the back end. They indicate front-end specific UI operations, such as
3365selecting an option from a drop-down menu. (Otherwise the front end
3366would have to translate the \q{New Game} menu item into an \cq{n}
3367keypress, for example.)
3368
3369\dt \cw{UI_NEWGAME}
3370
3371\dd Indicates that the user requested a new game, similar to pressing
3372\cq{n}.
3373
3374\dt \cw{UI_SOLVE}
3375
3376\dd Indicates that the user requested the solution of the current game.
3377
3378\dt \cw{UI_UNDO}
3379
3380\dd Indicates that the user attempted to undo a move.
3381
3382\dt \cw{UI_REDO}
3383
3384\dd Indicates that the user attempted to redo an undone move.
3385
3386\dt \cw{UI_QUIT}
3387
3388\dd Indicates that the user asked to quit the game. (Of course, a
3389front end might perfectly well handle this on its own. But including
3390it in this enumeration allows the front end to treat all these menu
3391items the same, by translating each of them into a button code passed
3392to the midend, and handle quitting by noticing the \c{false} return
3393value from \cw{midend_process_key()}.)
3394
3395The midend tolerates any modifier being set on any key and removes
3396them as necessary before passing the key on to the backend. It will
3397also handle translating printable characters combined with
3398\cw{MOD_CTRL} into control characters.
3079 3399
3080\H{midend-request-keys} \cw{midend_request_keys()} 3400\H{midend-request-keys} \cw{midend_request_keys()}
3081 3401
@@ -3089,6 +3409,20 @@ labels (i.e. the \cw{key_label} items that have their \cw{label}
3089fields set to \cw{NULL}) by using \cw{button2label()} 3409fields set to \cw{NULL}) by using \cw{button2label()}
3090(\k{utils-button2label}). 3410(\k{utils-button2label}).
3091 3411
3412\H{midend-current-key-label} \cw{midend_current_key_label()}
3413
3414\c const char *midend_current_key_label(midend *me, int button);
3415
3416This is a thin wrapper around the backend's \cw{current_key_label()}
3417function (\k{backend-current-key-label}). Front ends that need to
3418label \cw{CURSOR_SELECT} or \cw{CURSOR_SELECT2} should call this
3419function after each move (at least after each call to
3420\cw{midend_process_key()}) to get the current labels. The front end
3421should arrange to copy the returned string somewhere before the next
3422call to the mid-end, just in case it's dynamically allocated. If the
3423button supplied does nothing, the label returned will be an empty
3424string.
3425
3092\H{midend-colours} \cw{midend_colours()} 3426\H{midend-colours} \cw{midend_colours()}
3093 3427
3094\c float *midend_colours(midend *me, int *ncolours); 3428\c float *midend_colours(midend *me, int *ncolours);
@@ -3232,6 +3566,17 @@ viewing the existing one). The mid-end generates this dialog box
3232description itself. This should be used when the user selects 3566description itself. This should be used when the user selects
3233\q{Random Seed} from the game menu (or equivalent). 3567\q{Random Seed} from the game menu (or equivalent).
3234 3568
3569\dt \cw{CFG_PREFS}
3570
3571\dd Requests a box suitable for configuring user preferences.
3572
3573(An additional value \cw{CFG_FRONTEND_SPECIFIC} is provided in this
3574enumeration, so that frontends can extend it for their own internal
3575use. For example, you might wrap this function with a
3576\cw{frontend_get_config} which handles some values of \c{which} itself
3577and hands others on to the midend, depending on whether \cw{which <
3578CFG_FRONTEND_SPECIFIC}.)
3579
3235The returned value is an array of \cw{config_item}s, exactly as 3580The returned value is an array of \cw{config_item}s, exactly as
3236described in \k{backend-configure}. Another returned value is an 3581described in \k{backend-configure}. Another returned value is an
3237ASCII string giving a suitable title for the configuration window, 3582ASCII string giving a suitable title for the configuration window,
@@ -3292,7 +3637,7 @@ using \cw{midend_size()} and eventually case a refresh using
3292 3637
3293\H{midend-get-game-id} \cw{midend_get_game_id()} 3638\H{midend-get-game-id} \cw{midend_get_game_id()}
3294 3639
3295\c char *midend_get_game_id(midend *me) 3640\c char *midend_get_game_id(midend *me);
3296 3641
3297Returns a descriptive game ID (i.e. one in the form 3642Returns a descriptive game ID (i.e. one in the form
3298\cq{params:description}) describing the game currently active in the 3643\cq{params:description}) describing the game currently active in the
@@ -3300,7 +3645,7 @@ mid-end. The returned string is dynamically allocated.
3300 3645
3301\H{midend-get-random-seed} \cw{midend_get_random_seed()} 3646\H{midend-get-random-seed} \cw{midend_get_random_seed()}
3302 3647
3303\c char *midend_get_random_seed(midend *me) 3648\c char *midend_get_random_seed(midend *me);
3304 3649
3305Returns a random game ID (i.e. one in the form \cq{params#seedstring}) 3650Returns a random game ID (i.e. one in the form \cq{params#seedstring})
3306describing the game currently active in the mid-end, if there is one. 3651describing the game currently active in the mid-end, if there is one.
@@ -3309,6 +3654,9 @@ currently exist and this function will return \cw{NULL}.
3309 3654
3310The returned string, if it is non-\cw{NULL}, is dynamically allocated. 3655The returned string, if it is non-\cw{NULL}, is dynamically allocated.
3311 3656
3657Unlike the descriptive game ID, the random seed can contain characters
3658outside the printable ASCII set.
3659
3312\H{midend-can-format-as-text-now} \cw{midend_can_format_as_text_now()} 3660\H{midend-can-format-as-text-now} \cw{midend_can_format_as_text_now()}
3313 3661
3314\c bool midend_can_format_as_text_now(midend *me); 3662\c bool midend_can_format_as_text_now(midend *me);
@@ -3327,8 +3675,8 @@ Formats the current game's current state as ASCII text suitable for
3327copying to the clipboard. The returned string is dynamically 3675copying to the clipboard. The returned string is dynamically
3328allocated. 3676allocated.
3329 3677
3330If the game's \c{can_format_as_text_ever} flag is \cw{FALSE}, or if 3678If the game's \c{can_format_as_text_ever} flag is \cw{false}, or if
3331its \cw{can_format_as_text_now()} function returns \cw{FALSE}, then 3679its \cw{can_format_as_text_now()} function returns \cw{false}, then
3332this function will return \cw{NULL}. 3680this function will return \cw{NULL}.
3333 3681
3334If the returned string contains multiple lines (which is likely), it 3682If the returned string contains multiple lines (which is likely), it
@@ -3420,6 +3768,8 @@ visually activate and deactivate a redo button.
3420Calling this function causes the mid-end to convert its entire 3768Calling this function causes the mid-end to convert its entire
3421internal state into a long ASCII text string, and to pass that 3769internal state into a long ASCII text string, and to pass that
3422string (piece by piece) to the supplied \c{write} function. 3770string (piece by piece) to the supplied \c{write} function.
3771The string will consist of printable ASCII characters and line
3772feeds.
3423 3773
3424Desktop implementations can use this function to save a game in any 3774Desktop implementations can use this function to save a game in any
3425state (including half-finished) to a disk file, by supplying a 3775state (including half-finished) to a disk file, by supplying a
@@ -3474,6 +3824,32 @@ application is a monolithic one containing all the puzzles. See
3474identify a save file before you instantiate your mid-end in the first 3824identify a save file before you instantiate your mid-end in the first
3475place. 3825place.
3476 3826
3827\H{midend-save-prefs} \cw{midend_save_prefs()}
3828
3829\c void midend_save_prefs(
3830\c midend *me, void (*write)(void *ctx, const void *buf, int len),
3831\c void *wctx);
3832
3833Calling this function causes the mid-end to write out the states of
3834all user-settable preference options, including its own cross-platform
3835preferences and ones exported by a particular game via
3836\cw{get_prefs()} and \cw{set_prefs()} (\k{backend-get-prefs},
3837\k{backend-set-prefs}). The output is a textual format suitable for
3838writing into a configuration file on disk.
3839
3840The \c{write} and \c{wctx} parameters have the same semantics as for
3841\cw{midend_serialise()} (\k{midend-serialise}).
3842
3843\H{midend-load-prefs} \cw{midend_load_prefs()}
3844
3845\c const char *midend_load_prefs(
3846\c midend *me, bool (*read)(void *ctx, void *buf, int len),
3847\c void *rctx);
3848
3849This function is used to load a configuration file in the same format
3850emitted by \cw{midend_save_prefs()}, and import all the preferences
3851described in the file into the current mid-end.
3852
3477\H{identify-game} \cw{identify_game()} 3853\H{identify-game} \cw{identify_game()}
3478 3854
3479\c const char *identify_game(char **name, 3855\c const char *identify_game(char **name,
@@ -3524,6 +3900,13 @@ so I make it a callback rather than a static function in order to
3524relieve most front ends of the need to provide an empty 3900relieve most front ends of the need to provide an empty
3525implementation. 3901implementation.
3526 3902
3903\H{midend-which-game} \cw{midend_which_game()}
3904
3905\c const game *midend_which_preset(midend *me);
3906
3907This function returns the \c{game} structure for the puzzle type this
3908midend is committed to.
3909
3527\H{frontend-backend} Direct reference to the back end structure by 3910\H{frontend-backend} Direct reference to the back end structure by
3528the front end 3911the front end
3529 3912
@@ -3685,7 +4068,7 @@ printable ASCII, or NUL-terminated strings, or anything like that.
3685 4068
3686Allocates a new \c{random_state}, copies the contents of another 4069Allocates a new \c{random_state}, copies the contents of another
3687\c{random_state} into it, and returns the new state. If exactly the 4070\c{random_state} into it, and returns the new state. If exactly the
3688same sequence of functions is subseqently called on both the copy and 4071same sequence of functions is subsequently called on both the copy and
3689the original, the results will be identical. This may be useful for 4072the original, the results will be identical. This may be useful for
3690speculatively performing some operation using a given random state, 4073speculatively performing some operation using a given random state,
3691and later replaying that operation precisely. 4074and later replaying that operation precisely.
@@ -3707,7 +4090,8 @@ should be between 1 and 32 inclusive.
3707 4090
3708\c unsigned long random_upto(random_state *state, unsigned long limit); 4091\c unsigned long random_upto(random_state *state, unsigned long limit);
3709 4092
3710Returns a random number from 0 to \cw{limit-1} inclusive. 4093Returns a random number from 0 to \cw{limit-1} inclusive. \c{limit}
4094may not be zero.
3711 4095
3712\S{utils-random-state-encode} \cw{random_state_encode()} 4096\S{utils-random-state-encode} \cw{random_state_encode()}
3713 4097
@@ -3890,6 +4274,16 @@ dynamically allocated.
3890(See \k{backend-configure} for details of the \c{config_item} 4274(See \k{backend-configure} for details of the \c{config_item}
3891structure.) 4275structure.)
3892 4276
4277\S{utils-free-keys} \cw{free_keys()}
4278
4279\c void free_keys(key_label *keys, int nkeys);
4280
4281This function correctly frees an array of \c{key_label}s, including
4282the dynamically allocated label string for each key.
4283
4284(See \k{backend-request-keys} for details of the \c{key_label}
4285structure.)
4286
3893\H{utils-tree234} Sorted and counted tree functions 4287\H{utils-tree234} Sorted and counted tree functions
3894 4288
3895Many games require complex algorithms for generating random puzzles, 4289Many games require complex algorithms for generating random puzzles,
@@ -4206,19 +4600,422 @@ element. That function has the prototype
4206and every time it is called, the \c{state} parameter will be set to 4600and every time it is called, the \c{state} parameter will be set to
4207the value you passed in as \c{copyfnstate}. 4601the value you passed in as \c{copyfnstate}.
4208 4602
4603\H{utils-dsf} Disjoint set forests
4604
4605This section describes a set of functions implementing the data
4606structure variously known as \q{union-find} or \q{Tarjan's disjoint
4607set forest}. In this code base, it's universally abbreviated as a
4608\q{dsf}.
4609
4610A dsf represents a collection of elements partitioned into
4611\q{equivalence classes}, in circumstances where equivalences are added
4612incrementally. That is, all elements start off considered to be
4613different, and you gradually declare more and more of them to be equal
4614via the \cw{dsf_merge()} operation, which says that two particular
4615elements should be regarded as equal from now on.
4616
4617For example, if I start off with A,B,U,V all distinct, and I merge A
4618with B and merge U with V, then the structure will tell me that A and
4619U are not equivalent. But if I then merge B with V, then after that,
4620the structure will tell me that A and U \e{are} equivalent, by
4621following the transitive chain of equivalences it knows about.
4622
4623The dsf data structure is therefore ideal for tracking incremental
4624connectivity in an undirected graph (again, \q{incremental} meaning
4625that you only ever add edges, never delete them), and other
4626applications in which you gradually acquire knowledge you didn't
4627previously have about what things are the same as each other. It's
4628used extensively in puzzle solver and generator algorithms, and
4629sometimes during gameplay as well.
4630
4631The time complexity of dsf operations is not \e{quite} constant time,
4632in theory, but it's so close to it as to make no difference in
4633practice. In particular, any time a dsf has to do non-trivial work, it
4634updates the structure so that that work won't be needed a second time.
4635Use dsf operations without worrying about how long they take!
4636
4637For some puzzle-game applications, it's useful to augment this data
4638structure with extra information about how the elements of an
4639equivalence class relate to each other. There's more than one way you
4640might do this; the one supported here is useful in cases where the
4641objects you're tracking are going to end up in one of two states (say,
4642black/white, or on/off), and for any two objects you either know that
4643they're in the same one of those states, or you know they're in
4644opposite states, or you don't know which yet. Puzzles calls this a
4645\q{flip dsf}: it tracks whether objects in the same equivalence class
4646are flipped relative to each other.
4647
4648As well as querying whether two elements are equivalent, this dsf
4649implementation also allows you to ask for the number of elements in a
4650given equivalence class, and the smallest element in the class. (The
4651latter is used, for example, to decide which square to print the clue
4652in each region of a Keen puzzle.)
4653
4654\S{utils-dsf-new} \cw{dsf_new()}, \cw{dsf_new_flip()}, \cw{dsf_new_min()}
4655
4656\c DSF *dsf_new(int size);
4657\c DSF *dsf_new_flip(int size);
4658\c DSF *dsf_new_min(int size);
4659
4660Each of these functions allocates space for a dsf describing \c{size}
4661elements, and initialises it so that every element is in an
4662equivalence class by itself.
4663
4664The elements described by the dsf are represented by the integers from
4665\cw{0} to \cw{size-1} inclusive.
4666
4667\cw{dsf_new_flip()} will create a dsf which has the extra ability to
4668track whether objects in the same equivalence class are flipped
4669relative to each other.
4670
4671\cw{dsf_new_min()} will create a dsf which has the extra ability to
4672track the smallest element of each equivalence class.
4673
4674The returned object from any of these functions must be freed using
4675\cw{dsf_free()}.
4676
4677\S{utils-dsf-free} \cw{dsf_free()}
4678
4679\c void dsf_free(DSF *dsf);
4680
4681Frees a dsf allocated by any of the \cw{dsf_new()} functions.
4682
4683\S{utils-dsf-reinit} \cw{dsf_reinit()}
4684
4685\c void dsf_reinit(DSF *dsf);
4686
4687Reinitialises an existing dsf to the state in which all elements are
4688distinct, without having to free and reallocate it.
4689
4690\S{utils-dsf-copy} \cw{dsf_copy()}
4691
4692\c void dsf_copy(DSF *to, DSF *from);
4693
4694Copies the contents of one dsf over the top of another. Everything
4695previously stored in \c{to} is overwritten.
4696
4697The two dsfs must have been created with the same size, and the
4698destination dsf may not have any extra information that the source dsf
4699does not have.
4700
4701\S{utils-dsf-merge} \cw{dsf_merge()}
4702
4703\c void dsf_merge(DSF *dsf, int v1, int v2);
4704
4705Updates a dsf so that elements \c{v1} and \c{v2} will now be
4706considered to be in the same equivalence class. If they were already
4707in the same class, this function will safely do nothing.
4708
4709This function may not be called on a flip dsf. Use \cw{dsf_merge_flip}
4710instead.
4711
4712\S{utils-dsf-canonify} \cw{dsf_canonify()}
4713
4714\c int dsf_canonify(DSF *dsf, int val);
4715
4716Returns the \q{canonical} element of the equivalence class in the dsf
4717containing \c{val}. This will be some element of the same equivalence
4718class. So in order to determine whether two elements are in the same
4719equivalence class, you can call \cw{dsf_canonify} on both of them, and
4720compare the results.
4721
4722Canonical elements don't necessarily stay the same if the dsf is
4723mutated via \c{dsf_merge}. But between two calls to \c{dsf_merge},
4724they stay the same.
4725
4726\S{utils-dsf-size} \cw{dsf_size()}
4727
4728\c int dsf_size(DSF *dsf, int val);
4729
4730Returns the number of elements currently in the equivalence class
4731containing \c{val}.
4732
4733\c{val} itself counts, so in a newly created dsf, the return value
4734will be 1.
4735
4736\S{utils-dsf-merge-flip} \cw{dsf_merge_flip()}
4737
4738\c void edsf_merge(DSF *dsf, int v1, int v2, bool flip);
4739
4740Updates a flip dsf so that elements \c{v1} and \c{v2} are in the same
4741equivalence class. If \c{flip} is \cw{false}, they will be regarded as
4742in the same state as each other; if \c{flip} is \cw{true} then they
4743will be regarded as being in opposite states.
4744
4745If \c{v1} and \c{v2} were already in the same equivalence class, then
4746the new value of \c{flip} will be checked against what the edsf
4747previously believed, and an assertion failure will occur if you
4748contradict that.
4749
4750For example, if you start from a blank flip dsf and do this:
4751
4752\c dsf_merge_flip(dsf, 0, 1, false);
4753\c dsf_merge_flip(dsf, 1, 2, true);
4754
4755then it will create a dsf in which elements 0,1,2 are all in the same
4756class, with 0,1 in the same state as each other and 2 in the opposite
4757state from both. And then this call will do nothing, because it agrees
4758with what the dsf already knew:
4759
4760\c dsf_merge_flip(dsf, 0, 2, true);
4761
4762But this call will fail an assertion:
4763
4764\c dsf_merge_flip(dsf, 0, 2, false);
4765
4766\S{utils-dsf-canonify-flip} \cw{dsf_canonify_flip()}
4767
4768\c int dsf_canonify_flip(DSF *dsf, int val, bool *inverse);
4769
4770Like \c{dsf_canonify()}, this returns the canonical element of the
4771equivalence class of a dsf containing \c{val}.
4772
4773However, it may only be called on a flip dsf, and it also fills in
4774\c{*flip} with a flag indicating whether \c{val} and the canonical
4775element are in opposite states: \cw{true} if they are in opposite
4776states, or \cw{false} if they're in the same state.
4777
4778So if you want to know the relationship between \c{v1} and \c{v2}, you
4779can do this:
4780
4781\c bool inv1, inv2;
4782\c int canon1 = dsf_canonify_flip(dsf, v1, &inv1);
4783\c int canon2 = dsf_canonify_flip(dsf, v2, &inv2);
4784\c if (canon1 != canon2) {
4785\c // v1 and v2 have no known relation
4786\c } else if (inv1 == inv2) {
4787\c // v1 and v2 are known to be in the same state as each other
4788\c } else {
4789\c // v1 and v2 are known to be in opposite states
4790\c }
4791
4792\S{utils-dsf-minimal} \cw{dsf_minimal()}
4793
4794\c int dsf_minimal(DSF *dsf, int val);
4795
4796Returns the smallest element of the equivalence class in the dsf
4797containing \c{val}.
4798
4799For this function to work, the dsf must have been created using
4800\cw{dsf_new_min()}.
4801
4802\H{utils-tdq} To-do queues
4803
4804This section describes a set of functions implementing a \q{to-do
4805queue}, a simple de-duplicating to-do list mechanism. The code calls
4806this a \q{tdq}.
4807
4808A tdq can store integers up to a given size (specified at creation
4809time). But it can't store the same integer more than once. So you can
4810quickly \e{make sure} an integer is in the queue (which will do
4811nothing if it's already there), and you can quickly pop an integer
4812from the queue and return it, both in constant time.
4813
4814The idea is that you might use this in a game solver, in the kind of
4815game where updating your knowledge about one square of a grid means
4816there's a specific other set of squares (such as its neighbours) where
4817it's now worth attempting further deductions. So you keep a tdq of all
4818the grid squares you plan to look at next, and every time you make a
4819deduction in one square, you add the neighbouring squares to the tdq
4820to make sure they get looked at again after that.
4821
4822In solvers where deductions are mostly localised, this avoids the
4823slowdown of having to find the next thing to do every time by looping
4824over the whole grid: instead, you can keep checking the tdq for
4825\e{specific} squares to look at, until you run out.
4826
4827However, it's common to have games in which \e{most} deductions are
4828localised, but not all. In that situation, when your tdq is empty, you
4829can re-fill it with every square in the grid using \cw{tdq_fill()},
4830which will force an iteration over everything again. And then if the
4831tdq becomes empty \e{again} without you having made any progress, give
4832up.
4833
4834\S{utils-tdq-new} \cw{tdq_new()}
4835
4836\c tdq *tdq_new(int n);
4837
4838Allocates space for a tdq that tracks items from \cw{0} to \cw{size-1}
4839inclusive.
4840
4841\S{utils-tdq-free} \cw{tdq_free()}
4842
4843\c void tdq_free(tdq *tdq);
4844
4845Frees a tdq.
4846
4847\S{utils-tdq-add} \cw{tdq_add()}
4848
4849\c void tdq_add(tdq *tdq, int k);
4850
4851Adds the value \c{k} to a tdq. If \c{k} was already in the to-do list,
4852does nothing.
4853
4854\S{utils-tdq-remove} \cw{tdq_remove()}
4855
4856\c int tdq_remove(tdq *tdq);
4857
4858Removes one item from the tdq, and returns it. If the tdq is empty,
4859returns \cw{-1}.
4860
4861\S{utils-tdq-fill} \cw{tdq_fill()}
4862
4863\c void tdq_fill(tdq *tdq);
4864
4865Fills a tdq with every element it can possibly keep track of.
4866
4867\H{utils-findloop} Finding loops in graphs and grids
4868
4869Many puzzles played on grids or graphs have a common gameplay element
4870of connecting things together into paths in such a way that you need
4871to avoid making loops (or, perhaps, making the \e{wrong} kind of
4872loop).
4873
4874Just determining \e{whether} a loop exists in a graph is easy, using a
4875dsf tracking connectivity between the vertices. Simply iterate over
4876each edge of the graph, merging the two vertices at each end of the
4877edge \dash but before you do that, check whether those vertices are
4878\e{already} known to be connected to each other, and if they are, then
4879the new edge is about to complete a loop.
4880
4881But if you also want to identify \e{exactly} the set of edges that are
4882part of any loop, e.g. to highlight the whole loop red during
4883gameplay, then that's a harder problem. This API is provided here for
4884all puzzles to use for that purpose.
4885
4886\S{utils-findloop-new-state} \cw{findloop_new_state()}
4887
4888\c struct findloopstate *findloop_new_state(int nvertices);
4889
4890Allocates a new state structure for the findloop algorithm, capable of
4891handling a graph with up to \c{nvertices} vertices. The vertices will
4892be represented by integers between \c{0} and \c{nvertices-1} inclusive.
4893
4894\S{utils-findloop-free-state} \cw{findloop_free_state()}
4895
4896\c void findloop_free_state(struct findloopstate *state);
4897
4898Frees a state structure allocated by \cw{findloop_new_state()}.
4899
4900\S{utils-findloop-run} \cw{findloop_run()}
4901
4902\c bool findloop_run(struct findloopstate *state, int nvertices,
4903\c neighbour_fn_t neighbour, void *ctx);
4904
4905Runs the loop-finding algorithm, which will explore the graph and
4906identify whether each edge is or is not part of any loop.
4907
4908The algorithm will call the provided function \c{neighbour} to list
4909the neighbouring vertices of each vertex. It should have this
4910prototype:
4911
4912\c int neighbour(int vertex, void *ctx);
4913
4914In this callback, \c{vertex} will be the index of a vertex when the
4915algorithm \e{first} calls it for a given vertex. The function should
4916return the index of one of that vertex's neighbours, or a negative
4917number if there are none.
4918
4919If the function returned a vertex, the algorithm will then call
4920\c{neighbour} again with a \e{negative} number as the \c{vertex}
4921parameter, which means \q{please give me another neighbour of the same
4922vertex as last time}. Again, the function should return a vertex
4923index, or a negative number to indicate that there are no more
4924vertices.
4925
4926The \c{ctx} parameter passed to \cw{findloop_run()} is passed on
4927unchanged to \c{neighbour}, so you can point that at your game state
4928or solver state or whatever.
4929
4930The return value is \cw{true} if at least one loop exists in the
4931graph, and \cw{false} if no loop exists. Also, the algorithm state
4932will have been filled in with information that the following query
4933functions can use to ask about individual graph edges.
4934
4935\S{utils-findloop-is-loop-edge} \cw{findloop_is_loop_edge()}
4936
4937\c bool findloop_is_loop_edge(struct findloopstate *state,
4938\c int u, int v);
4939
4940Queries whether the graph edge between vertices \c{u} and \c{v} is
4941part of a loop. If so, the return value is \cw{true}, otherwise
4942\cw{false}.
4943
4944\S{utils-findloop-is-bridge} \cw{findloop_is_bridge()}
4945
4946\c bool findloop_is_bridge(struct findloopstate *pv,
4947\c int u, int v, int *u_vertices, int *v_vertices);
4948
4949Queries whether the graph edge between vertices \c{u} and \c{v} is a
4950\q{bridge}, i.e. an edge which would break the graph into (more)
4951disconnected components if it were removed.
4952
4953This is the exact inverse of the \q{loop edge} criterion: a vertex
4954returns \cw{true} from \cw{findloop_is_loop_edge()} if and only if it
4955returns \cw{false} from \cw{findloop_is_bridge()}, and vice versa.
4956
4957However, \cw{findloop_is_bridge()} returns more information. If it
4958returns \cw{true}, then it also fills in \c{*u_vertices} and
4959\c{*v_vertices} with the number of vertices connected to the \c{u} and
4960\c{v} sides of the bridge respectively.
4961
4962For example, if you have three vertices A,B,C all connected to each
4963other, and four vertices U,V,W,X all connected to each other, and a
4964single edge between A and V, then calling \cw{findloop_is_bridge()} on
4965the pair A,V will return true (removing that edge would separate the
4966two sets from each other), and will report that there are three
4967vertices on the A side and four on the V side.
4968
4969\H{utils-combi} Choosing r things out of n
4970
4971This section describes a small API for iterating over all combinations
4972of r things out of n.
4973
4974For example, if you asked for all combinations of 3 things out of 5,
4975you'd get back the sets \{0,1,2\}, \{0,1,3\}, \{0,1,4\}, \{0,2,3\},
4976\{0,2,4\}, \{0,3,4\}, \{1,2,3\}, \{1,2,4\}, \{1,3,4\}, and \{2,3,4\}.
4977
4978These functions use a structure called a \c{combi_ctx}, which contains
4979an element \c{int *a} holding each returned combination, plus other
4980fields for implementation use only.
4981
4982\S{utils-combi-new} \cw{new_combi()}
4983
4984\c combi_ctx *new_combi(int r, int n);
4985
4986Allocates a new \c{combi_ctx} structure for enumerating r things out
4987of n.
4988
4989\S{utils-combi-free} \cw{free_combi()}
4990
4991\c void free_combi(combi_ctx *combi);
4992
4993Frees a \c{combi_ctx} structure.
4994
4995\S{utils-combi-reset} \cw{reset_combi()}
4996
4997\c void reset_combi(combi_ctx *combi);
4998
4999Resets an existing \c{combi_ctx} structure to the start of its
5000iteration
5001
5002\S{utils-combi-next} \cw{next_combi()}
5003
5004\c combi_ctx *next_combi(combi_ctx *combi);
5005
5006Requests a combination from a \c{combi_ctx}.
5007
5008If there are none left to return, the return value is \cw{NULL}.
5009Otherwise, it returns the input structure \c{combi}, indicating that
5010it has filled in \cw{combi->a[0]}, \cw{combi->a[1]}, ...,
5011\cw{combi->a[r-1]} with an increasing sequence of distinct integers
5012from \cw{0} to \cw{n-1} inclusive.
5013
4209\H{utils-misc} Miscellaneous utility functions and macros 5014\H{utils-misc} Miscellaneous utility functions and macros
4210 5015
4211This section contains all the utility functions which didn't 5016This section contains all the utility functions which didn't
4212sensibly fit anywhere else. 5017sensibly fit anywhere else.
4213 5018
4214\S{utils-truefalse} \cw{TRUE} and \cw{FALSE}
4215
4216The main Puzzles header file defines the macros \cw{TRUE} and
4217\cw{FALSE}, which are used throughout the code in place of 1 and 0
4218(respectively) to indicate that the values are in a boolean context.
4219For code base consistency, I'd prefer it if submissions of new code
4220followed this convention as well.
4221
4222\S{utils-maxmin} \cw{max()} and \cw{min()} 5019\S{utils-maxmin} \cw{max()} and \cw{min()}
4223 5020
4224The main Puzzles header file defines the pretty standard macros 5021The main Puzzles header file defines the pretty standard macros
@@ -4228,6 +5025,17 @@ returns the one which compares greater or less respectively.
4228These macros may evaluate their arguments multiple times. Avoid side 5025These macros may evaluate their arguments multiple times. Avoid side
4229effects. 5026effects.
4230 5027
5028\S{utils-max-digits} \cw{MAX_DIGITS()}
5029
5030The \cw{MAX_DIGITS()} macro, defined in the main Puzzles header file,
5031takes a type (or a variable of that type) and expands to an integer
5032constant representing a reasonable upper bound on the number of
5033characters that a number of that type could expand to when formatted
5034as a decimal number using the \c{%u} or \c{%d} format of
5035\cw{printf()}. This is useful for allocating a fixed-size buffer
5036that's guaranteed to be big enough to \cw{sprintf()} a value into.
5037Don't forget to add one for the trailing \cw{'\\0'}!
5038
4231\S{utils-pi} \cw{PI} 5039\S{utils-pi} \cw{PI}
4232 5040
4233The main Puzzles header file defines a macro \cw{PI} which expands 5041The main Puzzles header file defines a macro \cw{PI} which expands
@@ -4238,7 +5046,7 @@ It'd be so useful!)
4238 5046
4239\S{utils-obfuscate-bitmap} \cw{obfuscate_bitmap()} 5047\S{utils-obfuscate-bitmap} \cw{obfuscate_bitmap()}
4240 5048
4241\c void obfuscate_bitmap(unsigned char *bmp, int bits, int decode); 5049\c void obfuscate_bitmap(unsigned char *bmp, int bits, bool decode);
4242 5050
4243This function obscures the contents of a piece of data, by 5051This function obscures the contents of a piece of data, by
4244cryptographic methods. It is useful for games of hidden information 5052cryptographic methods. It is useful for games of hidden information
@@ -4269,8 +5077,8 @@ considered to be used from the top down: thus, for example, setting
4269two} bits of \cw{bmp[1]}. The remainder of a partially used byte is 5077two} bits of \cw{bmp[1]}. The remainder of a partially used byte is
4270undefined (i.e. it may be corrupted by the function). 5078undefined (i.e. it may be corrupted by the function).
4271 5079
4272The parameter \c{decode} is \cw{FALSE} for an encoding operation, 5080The parameter \c{decode} is \cw{false} for an encoding operation,
4273and \cw{TRUE} for a decoding operation. Each is the inverse of the 5081and \cw{true} for a decoding operation. Each is the inverse of the
4274other. (There's no particular reason you shouldn't obfuscate by 5082other. (There's no particular reason you shouldn't obfuscate by
4275decoding and restore cleartext by encoding, if you really wanted to; 5083decoding and restore cleartext by encoding, if you really wanted to;
4276it should still work.) 5084it should still work.)
@@ -4299,6 +5107,67 @@ resulting array will be undefined.
4299 5107
4300This function is the inverse of \cw{bin2hex()}. 5108This function is the inverse of \cw{bin2hex()}.
4301 5109
5110\S{utils-fgetline} \cw{fgetline()}
5111
5112\c char *fgetline(FILE *fp);
5113
5114This function reads a single line of text from a standard C input
5115stream, and returns it as a dynamically allocated string. The returned
5116string still has a newline on the end.
5117
5118\S{utils-arraysort} \cw{arraysort()}
5119
5120Sorts an array, with slightly more flexibility than the standard C
5121\cw{qsort()}.
5122
5123This function is really implemented as a macro, so it doesn't have a
5124prototype as such. But you could imagine it having a prototype like
5125this:
5126
5127\c void arraysort(element_t *array, size_t nmemb,
5128\c arraysort_cmpfn_t cmp, void *ctx);
5129
5130in which \c{element_t} is an unspecified type.
5131
5132(Really, there's an underlying function that takes an extra parameter
5133giving the size of each array element. But callers are encouraged to
5134use this macro version, which fills that in automatically using
5135\c{sizeof}.)
5136
5137This function behaves essentially like \cw{qsort()}: it expects
5138\c{array} to point to an array of \c{nmemb} elements, and it will sort
5139them in place into the order specified by the comparison function
5140\c{cmp}.
5141
5142The comparison function should have this prototype:
5143
5144\c int cmp(const void *a, const void *b, void *ctx);
5145
5146in which \c{a} and \c{b} point at the two elements to be compared, and
5147the return value is negative if \cw{a<b} (that is, \c{a} should appear
5148before \c{b} in the output array), positive if \cw{a>b}, or zero if
5149\c{a=b}.
5150
5151The \c{ctx} parameter to \cw{arraysort()} is passed directly to the
5152comparison function. This is the feature that makes \cw{arraysort()}
5153more flexible than standard \cw{qsort()}: it lets you vary the sorting
5154criterion in a dynamic manner without having to write global variables
5155in the caller for the compare function to read.
5156
5157\S{utils-colour-mix} \cw{colour_mix()}
5158
5159\c void colour_mix(const float src1[3], const float src2[3], float p,
5160\c float dst[3]);
5161
5162This function mixes the colours \c{src1} and \c{src2} in specified
5163proportions, producing \c{dst}. \c{p} is the proportion of \c{src2}
5164in the result. So if \c{p} is \cw{1.0}, \cw{dst} will be the same as
5165\c{src2}. If \c{p} is \cw{0.0}, \cw{dst} will be the same as
5166\c{src1}. And if \c{p} is somewhere in between, so will \c{dst} be.
5167\c{p} is not restricted to the range \cw{0.0} to \cw{1.0}. Values
5168outside that range will produce extrapolated colours, which may be
5169useful for some purposes, but may also produce impossible colours.
5170
4302\S{utils-game-mkhighlight} \cw{game_mkhighlight()} 5171\S{utils-game-mkhighlight} \cw{game_mkhighlight()}
4303 5172
4304\c void game_mkhighlight(frontend *fe, float *ret, 5173\c void game_mkhighlight(frontend *fe, float *ret,
@@ -4310,7 +5179,7 @@ sections. Fifteen, Sixteen and Twiddle are good examples of this.
4310 5179
4311Puzzles using this graphical style are running a risk if they just 5180Puzzles using this graphical style are running a risk if they just
4312use whatever background colour is supplied to them by the front end, 5181use whatever background colour is supplied to them by the front end,
4313because that background colour might be too light to see any 5182because that background colour might be too light or dark to see any
4314highlights on at all. (In particular, it's not unheard of for the 5183highlights on at all. (In particular, it's not unheard of for the
4315front end to specify a default background colour of white.) 5184front end to specify a default background colour of white.)
4316 5185
@@ -4334,6 +5203,24 @@ Thus, \cw{ret[background*3]} to \cw{ret[background*3+2]} will be set
4334to RGB values defining a sensible background colour, and similary 5203to RGB values defining a sensible background colour, and similary
4335\c{highlight} and \c{lowlight} will be set to sensible colours. 5204\c{highlight} and \c{lowlight} will be set to sensible colours.
4336 5205
5206Either \c{highlight} or \c{lowlight} may be passed in as \cw{-1} to
5207indicate that the back-end does not require a highlight or lowlight
5208colour, respectively.
5209
5210\S{utils-game-mkhighlight-specific} \cw{game_mkhighlight_specific()}
5211
5212\c void game_mkhighlight_specific(frontend *fe, float *ret,
5213\c int background, int highlight, int lowlight);
5214
5215This function behaves exactly like \cw{game_mkhighlight()}, except
5216that it expects the background colour to have been filled in
5217\e{already} in the elements \cw{ret[background*3]} to
5218\cw{ret[background*3+2]}. It will fill in the other two colours as
5219brighter and darker versions of that.
5220
5221This is useful if you want to show relief sections of a puzzle in more
5222than one base colour.
5223
4337\S{utils-button2label} \cw{button2label()} 5224\S{utils-button2label} \cw{button2label()}
4338 5225
4339\c char *button2label(int button); 5226\c char *button2label(int button);
@@ -4352,6 +5239,104 @@ the corresponding \cw{button} field.
4352The returned string is dynamically allocated and should be 5239The returned string is dynamically allocated and should be
4353\cw{sfree}'d by the caller. 5240\cw{sfree}'d by the caller.
4354 5241
5242\S{utils-move-cursor} \cw{move_cursor()}
5243
5244\c char *move_cursor(int button, int *x, int *y, int w, int h,
5245\c bool wrap, bool *visible);
5246
5247This function can be called by \cw{interpret_move()} to implement the
5248default keyboard API for moving a cursor around a grid.
5249
5250\c{button} is the same value passed in to \cw{interpret_move()}. If
5251it's not any of \cw{CURSOR_UP}, \cw{CURSOR_DOWN}, \cw{CURSOR_LEFT} or
5252\cw{CURSOR_RIGHT}, the function will do nothing.
5253
5254\c{x} and \c{y} point to two integers which on input give the current
5255location of a cursor in a square grid. \c{w} and \c{h} give the
5256dimensions of the grid. On return, \c{x} and \c{y} are updated to give
5257the cursor's new position according to which arrow key was pressed.
5258
5259This function assumes that the grid coordinates run from \cw{0} to
5260\cw{w-1} inclusive (left to right), and from \cw{0} to \cw{h-1}
5261inclusive (top to bottom).
5262
5263If \c{wrap} is \cw{true}, then trying to move the cursor off any edge
5264of the grid will result in it wrapping round to the corresponding
5265square on the opposite edge. If \c{wrap} is \cw{false}, such a move
5266will have no effect.
5267
5268If \c{visible} is not \cw{NULL}, it points to a flag indicating
5269whether the cursor is visible. This will be set to \cw{true} if
5270\c{button} represents a cursor-movement key.
5271
5272The function returns one of the special constants that can be returned
5273by \cw{interpret_move()}. The return value is \cw{MOVE_UNUSED} if
5274\c{button} is unrecognised, \cw{MOVE_UI_UPDATE} if \c{x}, \c{y}, or
5275\c{visible} was updated, and \cw{MOVE_NO EFFECT} otherwise.
5276
5277\S{utils-divvy-rectangle} \cw{divvy_rectangle()}
5278
5279\c int *divvy_rectangle(int w, int h, int k, random_state *rs);
5280
5281Invents a random division of a rectangle into same-sized polyominoes,
5282such as is found in the block layout of a Solo puzzle in jigsaw mode,
5283or the solution to a Palisade puzzle.
5284
5285\c{w} and \c{h} are the dimensions of the rectangle. \c{k} is the size
5286of polyomino desired. It must be a factor of \c{w*h}.
5287
5288\c{rs} is a \cw{random_state} used to supply the random numbers to
5289select a random division of the rectangle.
5290
5291The return value is a dsf (see \k{utils-dsf}) whose equivalence
5292classes correspond to the polyominoes that the rectangle is divided
5293into. The indices of the dsf are of the form \c{y*w+x}, for the cell
5294with coordinates \cw{x,y}.
5295
5296\S{utils-domino-layout} \cw{domino_layout()}
5297
5298\c int *domino_layout(int w, int h, random_state *rs);
5299
5300Invents a random tiling of a rectangle with dominoes.
5301
5302\c{w} and \c{h} are the dimensions of the rectangle. If they are both
5303odd, then one square will be left untiled.
5304
5305\c{rs} is a \cw{random_state} used to supply the random numbers to
5306select a random division of the rectangle.
5307
5308The return value is an array in which element \c{y*w+x} represents the
5309cell with coordinates \cw{x,y}. Each element of the array gives the
5310index (in the same representation) of the other end of its domino. If
5311there's a left-over square, then that element contains its own index.
5312
5313\S{utils-domino-layout-prealloc} \cw{domino_layout_prealloc()}
5314
5315\c void domino_layout_prealloc(int w, int h, random_state *rs,
5316\c int *grid, int *grid2, int *list);
5317
5318Just like \cw{domino_layout()}, but does no memory allocation. You can
5319use this to save allocator overhead if you expect to need to generate
5320many domino tilings of the same grid.
5321
5322\c{grid} and \c{grid2} should each have space for \cw{w*h} ints.
5323\c{list} should have space for \c{2*w*h} ints.
5324
5325The returned array is delivered in \c{grid}.
5326
5327\S{utils-strip-button-modifiers} \cw{STRIP_BUTTON_MODIFIERS()}
5328
5329This macro, defined in the main Puzzles header file, strips the
5330modifier flags from the key code passed as an argument. It is
5331equivalent to a bitwise-AND with \cw{~MOD_MASK}.
5332
5333\S{utils-swap-regions} \cw{swap_regions()}
5334
5335\c void swap_regions(void *av, void *bv, size_t size);
5336
5337Swap two regions of memory of \cw{size} bytes. The two regions must
5338not overlap.
5339
4355\C{writing} How to write a new puzzle 5340\C{writing} How to write a new puzzle
4356 5341
4357This chapter gives a guide to how to actually write a new puzzle: 5342This chapter gives a guide to how to actually write a new puzzle:
@@ -4370,42 +5355,48 @@ official Puzzles distribution, then there's a criterion it has to
4370meet. 5355meet.
4371 5356
4372The current Puzzles editorial policy is that all games should be 5357The current Puzzles editorial policy is that all games should be
4373\e{fair}. A fair game is one which a player can only fail to 5358\e{fair}. A fair game is one which a player can only fail to complete
4374complete through demonstrable lack of skill \dash that is, such that 5359through demonstrable lack of skill \dash that is, such that a better
4375a better player in the same situation would have \e{known} to do 5360player presented with the same game state would have \e{known} to do
4376something different. 5361something different.
4377 5362
4378For a start, that means every game presented to the user must have 5363For a start, that means every game presented to the user must have
4379\e{at least one solution}. Giving the unsuspecting user a puzzle 5364\e{at least one solution}. Giving the unsuspecting user a puzzle which
4380which is actually impossible is not acceptable. (There is an 5365is actually impossible is not acceptable.
4381exception: if the user has selected some non-default option which is 5366
4382clearly labelled as potentially unfair, \e{then} you're allowed to 5367(An exception to this: if the user has selected some non-default
4383generate possibly insoluble puzzles, because the user isn't 5368option which is clearly labelled as potentially unfair, \e{then}
4384unsuspecting any more. Same Game and Mines both have options of this 5369you're allowed to generate possibly insoluble puzzles, because the
4385type.) 5370user isn't unsuspecting any more. Same Game and Mines both have
4386 5371options of this type.)
4387Also, this actually \e{rules out} games such as Klondike, or the 5372
4388normal form of Mahjong Solitaire. Those games have the property that 5373Secondly, if the game includes hidden information, then it must be
4389even if there is a solution (i.e. some sequence of moves which will 5374possible to deduce a correct move at every stage from the currently
4390get from the start state to the solved state), the player doesn't 5375available information. It's not enough that there should exist some
4391necessarily have enough information to \e{find} that solution. In 5376sequence of moves which will get from the start state to the solved
4392both games, it is possible to reach a dead end because you had an 5377state, if the player doesn't necessarily have enough information to
4393arbitrary choice to make and made it the wrong way. This violates 5378\e{find} that solution. For example, in the card solitaire game
4394the fairness criterion, because a better player couldn't have known 5379Klondike, it's possible to reach a dead end because you had an
4395they needed to make the other choice. 5380arbitrary choice to make on no information, and made it the wrong way,
4396 5381which violates the fairness criterion, because a better player
4397(GNOME has a variant on Mahjong Solitaire which makes it fair: there 5382couldn't have known they needed to make the other choice.
4398is a Shuffle operation which randomly permutes all the remaining 5383
4399tiles without changing their positions, which allows you to get out 5384(Of course, games in this collection always have an Undo function, so
4400of a sticky situation. Using this operation adds a 60-second penalty 5385if you did take the wrong route through a Klondike game, you could use
4401to your solution time, so it's to the player's advantage to try to 5386Undo to back up and try a different choice. This doesn't count. In a
4402minimise the chance of having to use it. It's still possible to 5387fair game, you should be able to determine a correct move from the
4403render the game uncompletable if you end up with only two tiles 5388information visible \e{now}, without having to make moves to get more
4404vertically stacked, but that's easy to foresee and avoid using a 5389information that you can then back up and use.)
4405shuffle operation. This form of the game \e{is} fair. Implementing 5390
4406it in Puzzles would require an infrastructure change so that the 5391Sometimes you can adjust the rules of an unfair puzzle to make it meet
4407back end could communicate time penalties to the mid-end, but that 5392this definition of fairness. For example, more than one implementation
4408would be easy enough.) 5393of solitaire-style games (including card solitaires and Mahjong
5394Solitaire) include a UI action to shuffle the remaining cards or tiles
5395without changing their position; this action might be available at any
5396time with a time or points penalty, or it might be illegal to use
5397unless you have no other possible move. Adding an option like this
5398would make a game \e{technically} fair, but it's better to avoid even
5399that if you can.
4409 5400
4410Providing a \e{unique} solution is a little more negotiable; it 5401Providing a \e{unique} solution is a little more negotiable; it
4411depends on the puzzle. Solo would have been of unacceptably low 5402depends on the puzzle. Solo would have been of unacceptably low
@@ -4441,15 +5432,11 @@ So start by copying \c{nullgame.c} into your new source file. Then
4441you'll gradually add functionality until the very boring Null Game 5432you'll gradually add functionality until the very boring Null Game
4442turns into your real game. 5433turns into your real game.
4443 5434
4444Next you'll need to add your puzzle to the Makefiles, in order to 5435Next you'll need to add your puzzle to the build scripts, in order to
4445compile it conveniently. \e{Do not edit the Makefiles}: they are 5436compile it conveniently. Puzzles is a CMake project, so you do this by
4446created automatically by the script \c{mkfiles.pl}, from the file 5437adding a \cw{puzzle()} statement to CMakeLists.txt. Look at the
4447called \c{Recipe}. Edit \c{Recipe}, and then re-run \c{mkfiles.pl}. 5438existing ones to see what those look like, and add one that looks
4448 5439similar.
4449Also, don't forget to add your puzzle to \c{list.c}: if you don't,
4450then it will still run fine on platforms which build each puzzle
4451separately, but Mac OS X and other monolithic platforms will not
4452include your new puzzle in their single binary.
4453 5440
4454Once your source file is building, you can move on to the fun bit. 5441Once your source file is building, you can move on to the fun bit.
4455 5442
@@ -4726,7 +5713,102 @@ This section lists some common things people want to do when writing
4726a puzzle, and describes how to achieve them within the Puzzles 5713a puzzle, and describes how to achieve them within the Puzzles
4727framework. 5714framework.
4728 5715
4729\S{writing-howto-cursor} Drawing objects at only one position 5716\S{writing-howto-redraw} Redrawing just the changed parts of the window
5717
5718Redrawing the entire window on every move is wasteful. If the user
5719makes a move changing only one square of a grid, it's better to redraw
5720just that square.
5721
5722(Yes, computers are fast these days, but these puzzles still try to be
5723portable to devices at the less fast end of the spectrum, so it's
5724still worth saving effort where it's easy. On the other hand, some
5725puzzles just \e{can't} do this easily \dash Untangle is an example
5726that really does have no better option than to redraw everything.)
5727
5728For a typical grid-oriented puzzle, a robust way to do this is:
5729
5730\b Invent a data representation that describes everything about the
5731appearance of a grid cell in the puzzle window.
5732
5733\b Have \c{game_drawstate} contain an array of those, describing the
5734current appearance of each cell, as it was last drawn in the window.
5735
5736\b In \cw{redraw()}, loop over each cell deciding what the new
5737appearance should be. If it's not the same as the value stored in
5738\c{game_drawstate}, then redraw that cell, and update the entry in the
5739\c{game_drawstate} array.
5740
5741Where possible, I generally make my data representation an integer
5742full of bit flags, to save space, and to make it easy to compare the
5743old and new versions. If yours needs to be bigger than that, you may
5744have to define a small \cw{struct} and write an equality-checking
5745function.
5746
5747The data representation of the \e{appearance} of a square in
5748\c{game_drawstate} will not generally be identical to the
5749representation of the \e{logical state} of a square in \c{game_state},
5750because many things contribute to a square's appearance other than its
5751logical state. For example:
5752
5753\b Extra information overlaid on the square by the user interface,
5754such as a keyboard-controlled cursor, or highlighting of squares
5755currently involved in a mouse drag action.
5756
5757\b Error highlights marking violations of the puzzle constraints.
5758
5759\b Visual intrusions into one square because of things in nearby
5760squares. For example, if you draw thick lines along the edges between
5761grid squares, then the corners of those lines will be visible in
5762logically unrelated squares. An entry in the \c{game_drawstate} array
5763should describe a specific \e{rectangular area of the screen}, so that
5764those areas can be erased and redrawn independently \dash so it must
5765represent anything that appears in that area, even if it's sticking
5766out from a graphic that logically lives in some other square.
5767
5768\b Temporary changes to the appearance of a square because of an
5769ongoing completion flash.
5770
5771\b The current display mode, if a game provides more than one. (For
5772example, the optional letters distinguishing the different coloured
5773pegs in Guess.)
5774
5775All of this must be included in the \c{game_drawstate} representation,
5776but should not be in the \c{game_state} at all. \cw{redraw()} will
5777pull it all together from the \c{game_state}, the \c{game_ui}, and the
5778animation and flash parameters.
5779
5780To make sure that \e{everything} affecting a square's appearance is
5781included in this representation, it's a good idea to have a separate
5782function for drawing a grid square, and deliberately \e{not} pass it a
5783copy of the \c{game_state} or the \c{game_ui} at all. That way, if you
5784want that function to draw anything differently, you \e{have} to do it
5785by including that information in the representation of a square's
5786appearance.
5787
5788But of course there are a couple of exceptions to this rule. A few
5789things \e{don't} have to go in the \c{game_drawstate} array, and can
5790safely be passed separately to the redraw-square function:
5791
5792\b Anything that remains completely fixed throughout the whole of a
5793game, such as the clues provided by the puzzle. This is safe because a
5794\c{game_drawstate} is never reused between puzzle instances: when you
5795press New Game, a new \c{game_drawstate} will always be created from
5796scratch. So the \c{game_drawstate} only needs to describe everything
5797that might \e{change} during gameplay. If you have a sub-\cw{struct}
5798in your \c{game_state} that describes immutable properties of the
5799current game, as suggested in \k{writing-ref-counting}, then it's safe
5800to pass \e{that substructure} to the redraw-square function, and have
5801it retrieve that information directly.
5802
5803\b How far through a move animation the last redraw was. When
5804\cw{redraw()} is called multiple times during an animated move, it's
5805much easier to just assume that any square involved in the animation
5806will \e{always} need redrawing. So \c{anim_length} can safely be
5807passed separately to the redraw-square function \dash but you also
5808have to remember to redraw a square if \e{either} its appearance is
5809different from the last redraw \e{or} it's involved in an animation.
5810
5811\S{writing-howto-cursor} Drawing an object at only one position
4730 5812
4731A common phenomenon is to have an object described in the 5813A common phenomenon is to have an object described in the
4732\c{game_state} or the \c{game_ui} which can only be at one position. 5814\c{game_state} or the \c{game_ui} which can only be at one position.
@@ -4742,41 +5824,19 @@ which you ended up with two cursors or none. The obviously sensible
4742way to store a cursor in the \c{game_ui} is to have fields directly 5824way to store a cursor in the \c{game_ui} is to have fields directly
4743encoding the cursor's coordinates. 5825encoding the cursor's coordinates.
4744 5826
4745However, it is a mistake to assume that the same logic applies to 5827However, it is a mistake to assume that the same logic applies to the
4746the \c{game_drawstate}. If you replicate the cursor position fields 5828\c{game_drawstate}. If you replicate the cursor position fields in the
4747in the draw state, the redraw code will get very complicated. In the 5829draw state, the redraw code will get very complicated. In the draw
4748draw state, in fact, it \e{is} probably the right thing to have a 5830state, in fact, it \e{is} probably the right thing to have a cursor
4749cursor flag for every position in the grid. You probably have an 5831flag for every position in the grid, and make it part of the
4750array for the whole grid in the drawstate already (stating what is 5832representation of each square's appearance, as described in
4751currently displayed in the window at each position); the sensible 5833\k{writing-howto-redraw}. So when you iterate over each square in
4752approach is to add a \q{cursor} flag to each element of that array. 5834\c{redraw()} working out its position, you set the \q{cursor here}
4753Then the main redraw loop will look something like this 5835flag in the representation of the square's appearance, if its
4754(pseudo-code): 5836coordinates match the cursor coordinates stored in the \c{game_ui}.
4755 5837This will automatically ensure that when the cursor moves, the redraw
4756\c for (y = 0; y < h; y++) { 5838loop will redraw the square that \e{previously} contained the cursor
4757\c for (x = 0; x < w; x++) { 5839and doesn't any more, and the one that now contains the cursor.
4758\c int value = state->symbol_at_position[y][x];
4759\c if (x == ui->cursor_x && y == ui->cursor_y)
4760\c value |= CURSOR;
4761\c if (ds->symbol_at_position[y][x] != value) {
4762\c symbol_drawing_subroutine(dr, ds, x, y, value);
4763\c ds->symbol_at_position[y][x] = value;
4764\c }
4765\c }
4766\c }
4767
4768This loop is very simple, pretty hard to get wrong, and
4769\e{automatically} deals both with erasing the previous cursor and
4770drawing the new one, with no special case code required.
4771
4772This type of loop is generally a sensible way to write a redraw
4773function, in fact. The best thing is to ensure that the information
4774stored in the draw state for each position tells you \e{everything}
4775about what was drawn there. A good way to ensure that is to pass
4776precisely the same information, and \e{only} that information, to a
4777subroutine that does the actual drawing; then you know there's no
4778additional information which affects the drawing but which you don't
4779notice changes in.
4780 5840
4781\S{writing-keyboard-cursor} Implementing a keyboard-controlled cursor 5841\S{writing-keyboard-cursor} Implementing a keyboard-controlled cursor
4782 5842
@@ -4790,10 +5850,11 @@ be:
4790\b Put cursor position fields in the \c{game_ui}. 5850\b Put cursor position fields in the \c{game_ui}.
4791 5851
4792\b \cw{interpret_move()} responds to arrow keys by modifying the 5852\b \cw{interpret_move()} responds to arrow keys by modifying the
4793cursor position fields and returning \cw{""}. 5853cursor position fields and returning \cw{MOVE_UI_UPDATE}.
4794 5854
4795\b \cw{interpret_move()} responds to some sort of fire button by 5855\b \cw{interpret_move()} responds to some other button \dash either
4796actually performing a move based on the current cursor location. 5856\cw{CURSOR_SELECT} or some more specific thing like a number key \dash
5857by actually performing a move based on the current cursor location.
4797 5858
4798\b You might want an additional \c{game_ui} field stating whether 5859\b You might want an additional \c{game_ui} field stating whether
4799the cursor is currently visible, and having it disappear when a 5860the cursor is currently visible, and having it disappear when a
@@ -4983,21 +6044,21 @@ The solution is to have \e{two} flags in a queue.
4983\b Define two flags in \c{game_ui}; let's call them \q{current} and 6044\b Define two flags in \c{game_ui}; let's call them \q{current} and
4984\q{next}. 6045\q{next}.
4985 6046
4986\b Set both to \cw{FALSE} in \c{new_ui()}. 6047\b Set both to \cw{false} in \c{new_ui()}.
4987 6048
4988\b When a drag operation completes in \cw{interpret_move()}, set the 6049\b When a drag operation completes in \cw{interpret_move()}, set the
4989\q{next} flag to \cw{TRUE}. 6050\q{next} flag to \cw{true}.
4990 6051
4991\b Every time \cw{changed_state()} is called, set the value of 6052\b Every time \cw{changed_state()} is called, set the value of
4992\q{current} to the value in \q{next}, and then set the value of 6053\q{current} to the value in \q{next}, and then set the value of
4993\q{next} to \cw{FALSE}. 6054\q{next} to \cw{false}.
4994 6055
4995\b That way, \q{current} will be \cw{TRUE} \e{after} a call to 6056\b That way, \q{current} will be \cw{true} \e{after} a call to
4996\cw{changed_state()} if and only if that call to 6057\cw{changed_state()} if and only if that call to
4997\cw{changed_state()} was the result of a drag operation processed by 6058\cw{changed_state()} was the result of a drag operation processed by
4998\cw{interpret_move()}. Any other call to \cw{changed_state()}, due 6059\cw{interpret_move()}. Any other call to \cw{changed_state()}, due
4999to an Undo or a Redo or a Restart or a Solve, will leave \q{current} 6060to an Undo or a Redo or a Restart or a Solve, will leave \q{current}
5000\cw{FALSE}. 6061\cw{false}.
5001 6062
5002\b So now \cw{anim_length()} can request a move animation if and 6063\b So now \cw{anim_length()} can request a move animation if and
5003only if the \q{current} flag is \e{not} set. 6064only if the \q{current} flag is \e{not} set.
@@ -5013,7 +6074,7 @@ This is easily done:
5013 6074
5014\b Add a \q{cheated} flag to the \c{game_state}. 6075\b Add a \q{cheated} flag to the \c{game_state}.
5015 6076
5016\b Set this flag to \cw{FALSE} in \cw{new_game()}. 6077\b Set this flag to \cw{false} in \cw{new_game()}.
5017 6078
5018\b Have \cw{solve()} return a move description string which clearly 6079\b Have \cw{solve()} return a move description string which clearly
5019identifies the move as a solve operation. 6080identifies the move as a solve operation.