chiark / gitweb /
Replace my brute-force algorithm in face_text_pos with a more complex
[sgt-puzzles.git] / loopy.c
1 /*
2  * loopy.c:
3  *
4  * An implementation of the Nikoli game 'Loop the loop'.
5  * (c) Mike Pinna, 2005, 2006
6  * Substantially rewritten to allowing for more general types of grid.
7  * (c) Lambros Lambrou 2008
8  *
9  * vim: set shiftwidth=4 :set textwidth=80:
10  */
11
12 /*
13  * Possible future solver enhancements:
14  * 
15  *  - There's an interesting deductive technique which makes use
16  *    of topology rather than just graph theory. Each _face_ in
17  *    the grid is either inside or outside the loop; you can tell
18  *    that two faces are on the same side of the loop if they're
19  *    separated by a LINE_NO (or, more generally, by a path
20  *    crossing no LINE_UNKNOWNs and an even number of LINE_YESes),
21  *    and on the opposite side of the loop if they're separated by
22  *    a LINE_YES (or an odd number of LINE_YESes and no
23  *    LINE_UNKNOWNs). Oh, and any face separated from the outside
24  *    of the grid by a LINE_YES or a LINE_NO is on the inside or
25  *    outside respectively. So if you can track this for all
26  *    faces, you figure out the state of the line between a pair
27  *    once their relative insideness is known.
28  *     + The way I envisage this working is simply to keep an edsf
29  *       of all _faces_, which indicates whether they're on
30  *       opposite sides of the loop from one another. We also
31  *       include a special entry in the edsf for the infinite
32  *       exterior "face".
33  *     + So, the simple way to do this is to just go through the
34  *       edges: every time we see an edge in a state other than
35  *       LINE_UNKNOWN which separates two faces that aren't in the
36  *       same edsf class, we can rectify that by merging the
37  *       classes. Then, conversely, an edge in LINE_UNKNOWN state
38  *       which separates two faces that _are_ in the same edsf
39  *       class can immediately have its state determined.
40  *     + But you can go one better, if you're prepared to loop
41  *       over all _pairs_ of edges. Suppose we have edges A and B,
42  *       which respectively separate faces A1,A2 and B1,B2.
43  *       Suppose that A,B are in the same edge-edsf class and that
44  *       A1,B1 (wlog) are in the same face-edsf class; then we can
45  *       immediately place A2,B2 into the same face-edsf class (as
46  *       each other, not as A1 and A2) one way round or the other.
47  *       And conversely again, if A1,B1 are in the same face-edsf
48  *       class and so are A2,B2, then we can put A,B into the same
49  *       face-edsf class.
50  *        * Of course, this deduction requires a quadratic-time
51  *          loop over all pairs of edges in the grid, so it should
52  *          be reserved until there's nothing easier left to be
53  *          done.
54  * 
55  *  - The generalised grid support has made me (SGT) notice a
56  *    possible extension to the loop-avoidance code. When you have
57  *    a path of connected edges such that no other edges at all
58  *    are incident on any vertex in the middle of the path - or,
59  *    alternatively, such that any such edges are already known to
60  *    be LINE_NO - then you know those edges are either all
61  *    LINE_YES or all LINE_NO. Hence you can mentally merge the
62  *    entire path into a single long curly edge for the purposes
63  *    of loop avoidance, and look directly at whether or not the
64  *    extreme endpoints of the path are connected by some other
65  *    route. I find this coming up fairly often when I play on the
66  *    octagonal grid setting, so it might be worth implementing in
67  *    the solver.
68  *
69  *  - (Just a speed optimisation.)  Consider some todo list queue where every
70  *    time we modify something we mark it for consideration by other bits of
71  *    the solver, to save iteration over things that have already been done.
72  */
73
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <stddef.h>
77 #include <string.h>
78 #include <assert.h>
79 #include <ctype.h>
80 #include <math.h>
81
82 #include "puzzles.h"
83 #include "tree234.h"
84 #include "grid.h"
85
86 /* Debugging options */
87
88 /*
89 #define DEBUG_CACHES
90 #define SHOW_WORKING
91 #define DEBUG_DLINES
92 */
93
94 /* ----------------------------------------------------------------------
95  * Struct, enum and function declarations
96  */
97
98 enum {
99     COL_BACKGROUND,
100     COL_FOREGROUND,
101     COL_LINEUNKNOWN,
102     COL_HIGHLIGHT,
103     COL_MISTAKE,
104     COL_SATISFIED,
105     COL_FAINT,
106     NCOLOURS
107 };
108
109 struct game_state {
110     grid *game_grid;
111
112     /* Put -1 in a face that doesn't get a clue */
113     signed char *clues;
114
115     /* Array of line states, to store whether each line is
116      * YES, NO or UNKNOWN */
117     char *lines;
118
119     unsigned char *line_errors;
120
121     int solved;
122     int cheated;
123
124     /* Used in game_text_format(), so that it knows what type of
125      * grid it's trying to render as ASCII text. */
126     int grid_type;
127 };
128
129 enum solver_status {
130     SOLVER_SOLVED,    /* This is the only solution the solver could find */
131     SOLVER_MISTAKE,   /* This is definitely not a solution */
132     SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
133     SOLVER_INCOMPLETE /* This may be a partial solution */
134 };
135
136 /* ------ Solver state ------ */
137 typedef struct solver_state {
138     game_state *state;
139     enum solver_status solver_status;
140     /* NB looplen is the number of dots that are joined together at a point, ie a
141      * looplen of 1 means there are no lines to a particular dot */
142     int *looplen;
143
144     /* Difficulty level of solver.  Used by solver functions that want to
145      * vary their behaviour depending on the requested difficulty level. */
146     int diff;
147
148     /* caches */
149     char *dot_yes_count;
150     char *dot_no_count;
151     char *face_yes_count;
152     char *face_no_count;
153     char *dot_solved, *face_solved;
154     int *dotdsf;
155
156     /* Information for Normal level deductions:
157      * For each dline, store a bitmask for whether we know:
158      * (bit 0) at least one is YES
159      * (bit 1) at most one is YES */
160     char *dlines;
161
162     /* Hard level information */
163     int *linedsf;
164 } solver_state;
165
166 /*
167  * Difficulty levels. I do some macro ickery here to ensure that my
168  * enum and the various forms of my name list always match up.
169  */
170
171 #define DIFFLIST(A) \
172     A(EASY,Easy,e) \
173     A(NORMAL,Normal,n) \
174     A(TRICKY,Tricky,t) \
175     A(HARD,Hard,h)
176 #define ENUM(upper,title,lower) DIFF_ ## upper,
177 #define TITLE(upper,title,lower) #title,
178 #define ENCODE(upper,title,lower) #lower
179 #define CONFIG(upper,title,lower) ":" #title
180 enum { DIFFLIST(ENUM) DIFF_MAX };
181 static char const *const diffnames[] = { DIFFLIST(TITLE) };
182 static char const diffchars[] = DIFFLIST(ENCODE);
183 #define DIFFCONFIG DIFFLIST(CONFIG)
184
185 /*
186  * Solver routines, sorted roughly in order of computational cost.
187  * The solver will run the faster deductions first, and slower deductions are
188  * only invoked when the faster deductions are unable to make progress.
189  * Each function is associated with a difficulty level, so that the generated
190  * puzzles are solvable by applying only the functions with the chosen
191  * difficulty level or lower.
192  */
193 #define SOLVERLIST(A) \
194     A(trivial_deductions, DIFF_EASY) \
195     A(dline_deductions, DIFF_NORMAL) \
196     A(linedsf_deductions, DIFF_HARD) \
197     A(loop_deductions, DIFF_EASY)
198 #define SOLVER_FN_DECL(fn,diff) static int fn(solver_state *);
199 #define SOLVER_FN(fn,diff) &fn,
200 #define SOLVER_DIFF(fn,diff) diff,
201 SOLVERLIST(SOLVER_FN_DECL)
202 static int (*(solver_fns[]))(solver_state *) = { SOLVERLIST(SOLVER_FN) };
203 static int const solver_diffs[] = { SOLVERLIST(SOLVER_DIFF) };
204 const int NUM_SOLVERS = sizeof(solver_diffs)/sizeof(*solver_diffs);
205
206 struct game_params {
207     int w, h;
208     int diff;
209     int type;
210
211     /* Grid generation is expensive, so keep a (ref-counted) reference to the
212      * grid for these parameters, and only generate when required. */
213     grid *game_grid;
214 };
215
216 /* line_drawstate is the same as line_state, but with the extra ERROR
217  * possibility.  The drawing code copies line_state to line_drawstate,
218  * except in the case that the line is an error. */
219 enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
220 enum line_drawstate { DS_LINE_YES, DS_LINE_UNKNOWN,
221                       DS_LINE_NO, DS_LINE_ERROR };
222
223 #define OPP(line_state) \
224     (2 - line_state)
225
226
227 struct game_drawstate {
228     int started;
229     int tilesize;
230     int flashing;
231     int *textx, *texty;
232     char *lines;
233     char *clue_error;
234     char *clue_satisfied;
235 };
236
237 static char *validate_desc(game_params *params, char *desc);
238 static int dot_order(const game_state* state, int i, char line_type);
239 static int face_order(const game_state* state, int i, char line_type);
240 static solver_state *solve_game_rec(const solver_state *sstate);
241
242 #ifdef DEBUG_CACHES
243 static void check_caches(const solver_state* sstate);
244 #else
245 #define check_caches(s)
246 #endif
247
248 /* ------- List of grid generators ------- */
249 #define GRIDLIST(A) \
250     A(Squares,grid_new_square,3,3) \
251     A(Triangular,grid_new_triangular,3,3) \
252     A(Honeycomb,grid_new_honeycomb,3,3) \
253     A(Snub-Square,grid_new_snubsquare,3,3) \
254     A(Cairo,grid_new_cairo,3,4) \
255     A(Great-Hexagonal,grid_new_greathexagonal,3,3) \
256     A(Octagonal,grid_new_octagonal,3,3) \
257     A(Kites,grid_new_kites,3,3) \
258     A(Floret,grid_new_floret,1,2) \
259     A(Dodecagonal,grid_new_dodecagonal,2,2) \
260     A(Great-Dodecagonal,grid_new_greatdodecagonal,2,2)
261
262 #define GRID_NAME(title,fn,amin,omin) #title,
263 #define GRID_CONFIG(title,fn,amin,omin) ":" #title
264 #define GRID_FN(title,fn,amin,omin) &fn,
265 #define GRID_SIZES(title,fn,amin,omin) \
266     {amin, omin, \
267      "Width and height for this grid type must both be at least " #amin, \
268      "At least one of width and height for this grid type must be at least " #omin,},
269 static char const *const gridnames[] = { GRIDLIST(GRID_NAME) };
270 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
271 static grid * (*(grid_fns[]))(int w, int h) = { GRIDLIST(GRID_FN) };
272 #define NUM_GRID_TYPES (sizeof(grid_fns) / sizeof(grid_fns[0]))
273 static const struct {
274     int amin, omin;
275     char *aerr, *oerr;
276 } grid_size_limits[] = { GRIDLIST(GRID_SIZES) };
277
278 /* Generates a (dynamically allocated) new grid, according to the
279  * type and size requested in params.  Does nothing if the grid is already
280  * generated.  The allocated grid is owned by the params object, and will be
281  * freed in free_params(). */
282 static void params_generate_grid(game_params *params)
283 {
284     if (!params->game_grid) {
285         params->game_grid = grid_fns[params->type](params->w, params->h);
286     }
287 }
288
289 /* ----------------------------------------------------------------------
290  * Preprocessor magic
291  */
292
293 /* General constants */
294 #define PREFERRED_TILE_SIZE 32
295 #define BORDER(tilesize) ((tilesize) / 2)
296 #define FLASH_TIME 0.5F
297
298 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
299
300 #define SET_BIT(field, bit)  (BIT_SET(field, bit) ? FALSE : \
301                               ((field) |= (1<<(bit)), TRUE))
302
303 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
304                                ((field) &= ~(1<<(bit)), TRUE) : FALSE)
305
306 #define CLUE2CHAR(c) \
307     ((c < 0) ? ' ' : c < 10 ? c + '0' : c - 10 + 'A')
308
309 /* ----------------------------------------------------------------------
310  * General struct manipulation and other straightforward code
311  */
312
313 static game_state *dup_game(game_state *state)
314 {
315     game_state *ret = snew(game_state);
316
317     ret->game_grid = state->game_grid;
318     ret->game_grid->refcount++;
319
320     ret->solved = state->solved;
321     ret->cheated = state->cheated;
322
323     ret->clues = snewn(state->game_grid->num_faces, signed char);
324     memcpy(ret->clues, state->clues, state->game_grid->num_faces);
325
326     ret->lines = snewn(state->game_grid->num_edges, char);
327     memcpy(ret->lines, state->lines, state->game_grid->num_edges);
328
329     ret->line_errors = snewn(state->game_grid->num_edges, unsigned char);
330     memcpy(ret->line_errors, state->line_errors, state->game_grid->num_edges);
331
332     ret->grid_type = state->grid_type;
333     return ret;
334 }
335
336 static void free_game(game_state *state)
337 {
338     if (state) {
339         grid_free(state->game_grid);
340         sfree(state->clues);
341         sfree(state->lines);
342         sfree(state->line_errors);
343         sfree(state);
344     }
345 }
346
347 static solver_state *new_solver_state(game_state *state, int diff) {
348     int i;
349     int num_dots = state->game_grid->num_dots;
350     int num_faces = state->game_grid->num_faces;
351     int num_edges = state->game_grid->num_edges;
352     solver_state *ret = snew(solver_state);
353
354     ret->state = dup_game(state);
355
356     ret->solver_status = SOLVER_INCOMPLETE;
357     ret->diff = diff;
358
359     ret->dotdsf = snew_dsf(num_dots);
360     ret->looplen = snewn(num_dots, int);
361
362     for (i = 0; i < num_dots; i++) {
363         ret->looplen[i] = 1;
364     }
365
366     ret->dot_solved = snewn(num_dots, char);
367     ret->face_solved = snewn(num_faces, char);
368     memset(ret->dot_solved, FALSE, num_dots);
369     memset(ret->face_solved, FALSE, num_faces);
370
371     ret->dot_yes_count = snewn(num_dots, char);
372     memset(ret->dot_yes_count, 0, num_dots);
373     ret->dot_no_count = snewn(num_dots, char);
374     memset(ret->dot_no_count, 0, num_dots);
375     ret->face_yes_count = snewn(num_faces, char);
376     memset(ret->face_yes_count, 0, num_faces);
377     ret->face_no_count = snewn(num_faces, char);
378     memset(ret->face_no_count, 0, num_faces);
379
380     if (diff < DIFF_NORMAL) {
381         ret->dlines = NULL;
382     } else {
383         ret->dlines = snewn(2*num_edges, char);
384         memset(ret->dlines, 0, 2*num_edges);
385     }
386
387     if (diff < DIFF_HARD) {
388         ret->linedsf = NULL;
389     } else {
390         ret->linedsf = snew_dsf(state->game_grid->num_edges);
391     }
392
393     return ret;
394 }
395
396 static void free_solver_state(solver_state *sstate) {
397     if (sstate) {
398         free_game(sstate->state);
399         sfree(sstate->dotdsf);
400         sfree(sstate->looplen);
401         sfree(sstate->dot_solved);
402         sfree(sstate->face_solved);
403         sfree(sstate->dot_yes_count);
404         sfree(sstate->dot_no_count);
405         sfree(sstate->face_yes_count);
406         sfree(sstate->face_no_count);
407
408         /* OK, because sfree(NULL) is a no-op */
409         sfree(sstate->dlines);
410         sfree(sstate->linedsf);
411
412         sfree(sstate);
413     }
414 }
415
416 static solver_state *dup_solver_state(const solver_state *sstate) {
417     game_state *state = sstate->state;
418     int num_dots = state->game_grid->num_dots;
419     int num_faces = state->game_grid->num_faces;
420     int num_edges = state->game_grid->num_edges;
421     solver_state *ret = snew(solver_state);
422
423     ret->state = state = dup_game(sstate->state);
424
425     ret->solver_status = sstate->solver_status;
426     ret->diff = sstate->diff;
427
428     ret->dotdsf = snewn(num_dots, int);
429     ret->looplen = snewn(num_dots, int);
430     memcpy(ret->dotdsf, sstate->dotdsf,
431            num_dots * sizeof(int));
432     memcpy(ret->looplen, sstate->looplen,
433            num_dots * sizeof(int));
434
435     ret->dot_solved = snewn(num_dots, char);
436     ret->face_solved = snewn(num_faces, char);
437     memcpy(ret->dot_solved, sstate->dot_solved, num_dots);
438     memcpy(ret->face_solved, sstate->face_solved, num_faces);
439
440     ret->dot_yes_count = snewn(num_dots, char);
441     memcpy(ret->dot_yes_count, sstate->dot_yes_count, num_dots);
442     ret->dot_no_count = snewn(num_dots, char);
443     memcpy(ret->dot_no_count, sstate->dot_no_count, num_dots);
444
445     ret->face_yes_count = snewn(num_faces, char);
446     memcpy(ret->face_yes_count, sstate->face_yes_count, num_faces);
447     ret->face_no_count = snewn(num_faces, char);
448     memcpy(ret->face_no_count, sstate->face_no_count, num_faces);
449
450     if (sstate->dlines) {
451         ret->dlines = snewn(2*num_edges, char);
452         memcpy(ret->dlines, sstate->dlines,
453                2*num_edges);
454     } else {
455         ret->dlines = NULL;
456     }
457
458     if (sstate->linedsf) {
459         ret->linedsf = snewn(num_edges, int);
460         memcpy(ret->linedsf, sstate->linedsf,
461                num_edges * sizeof(int));
462     } else {
463         ret->linedsf = NULL;
464     }
465
466     return ret;
467 }
468
469 static game_params *default_params(void)
470 {
471     game_params *ret = snew(game_params);
472
473 #ifdef SLOW_SYSTEM
474     ret->h = 7;
475     ret->w = 7;
476 #else
477     ret->h = 10;
478     ret->w = 10;
479 #endif
480     ret->diff = DIFF_EASY;
481     ret->type = 0;
482
483     ret->game_grid = NULL;
484
485     return ret;
486 }
487
488 static game_params *dup_params(game_params *params)
489 {
490     game_params *ret = snew(game_params);
491
492     *ret = *params;                       /* structure copy */
493     if (ret->game_grid) {
494         ret->game_grid->refcount++;
495     }
496     return ret;
497 }
498
499 static const game_params presets[] = {
500 #ifdef SMALL_SCREEN
501     {  7,  7, DIFF_EASY, 0, NULL },
502     {  7,  7, DIFF_NORMAL, 0, NULL },
503     {  7,  7, DIFF_HARD, 0, NULL },
504     {  7,  7, DIFF_HARD, 1, NULL },
505     {  7,  7, DIFF_HARD, 2, NULL },
506     {  5,  5, DIFF_HARD, 3, NULL },
507     {  7,  7, DIFF_HARD, 4, NULL },
508     {  5,  4, DIFF_HARD, 5, NULL },
509     {  5,  5, DIFF_HARD, 6, NULL },
510     {  5,  5, DIFF_HARD, 7, NULL },
511     {  3,  3, DIFF_HARD, 8, NULL },
512     {  3,  3, DIFF_HARD, 9, NULL },
513     {  3,  3, DIFF_HARD, 10, NULL },
514 #else
515     {  7,  7, DIFF_EASY, 0, NULL },
516     {  10,  10, DIFF_EASY, 0, NULL },
517     {  7,  7, DIFF_NORMAL, 0, NULL },
518     {  10,  10, DIFF_NORMAL, 0, NULL },
519     {  7,  7, DIFF_HARD, 0, NULL },
520     {  10,  10, DIFF_HARD, 0, NULL },
521     {  10,  10, DIFF_HARD, 1, NULL },
522     {  12,  10, DIFF_HARD, 2, NULL },
523     {  7,  7, DIFF_HARD, 3, NULL },
524     {  9,  9, DIFF_HARD, 4, NULL },
525     {  5,  4, DIFF_HARD, 5, NULL },
526     {  7,  7, DIFF_HARD, 6, NULL },
527     {  5,  5, DIFF_HARD, 7, NULL },
528     {  5,  5, DIFF_HARD, 8, NULL },
529     {  5,  4, DIFF_HARD, 9, NULL },
530     {  5,  4, DIFF_HARD, 10, NULL },
531 #endif
532 };
533
534 static int game_fetch_preset(int i, char **name, game_params **params)
535 {
536     game_params *tmppar;
537     char buf[80];
538
539     if (i < 0 || i >= lenof(presets))
540         return FALSE;
541
542     tmppar = snew(game_params);
543     *tmppar = presets[i];
544     *params = tmppar;
545     sprintf(buf, "%dx%d %s - %s", tmppar->h, tmppar->w,
546             gridnames[tmppar->type], diffnames[tmppar->diff]);
547     *name = dupstr(buf);
548
549     return TRUE;
550 }
551
552 static void free_params(game_params *params)
553 {
554     if (params->game_grid) {
555         grid_free(params->game_grid);
556     }
557     sfree(params);
558 }
559
560 static void decode_params(game_params *params, char const *string)
561 {
562     if (params->game_grid) {
563         grid_free(params->game_grid);
564         params->game_grid = NULL;
565     }
566     params->h = params->w = atoi(string);
567     params->diff = DIFF_EASY;
568     while (*string && isdigit((unsigned char)*string)) string++;
569     if (*string == 'x') {
570         string++;
571         params->h = atoi(string);
572         while (*string && isdigit((unsigned char)*string)) string++;
573     }
574     if (*string == 't') {
575         string++;
576         params->type = atoi(string);
577         while (*string && isdigit((unsigned char)*string)) string++;
578     }
579     if (*string == 'd') {
580         int i;
581         string++;
582         for (i = 0; i < DIFF_MAX; i++)
583             if (*string == diffchars[i])
584                 params->diff = i;
585         if (*string) string++;
586     }
587 }
588
589 static char *encode_params(game_params *params, int full)
590 {
591     char str[80];
592     sprintf(str, "%dx%dt%d", params->w, params->h, params->type);
593     if (full)
594         sprintf(str + strlen(str), "d%c", diffchars[params->diff]);
595     return dupstr(str);
596 }
597
598 static config_item *game_configure(game_params *params)
599 {
600     config_item *ret;
601     char buf[80];
602
603     ret = snewn(5, config_item);
604
605     ret[0].name = "Width";
606     ret[0].type = C_STRING;
607     sprintf(buf, "%d", params->w);
608     ret[0].sval = dupstr(buf);
609     ret[0].ival = 0;
610
611     ret[1].name = "Height";
612     ret[1].type = C_STRING;
613     sprintf(buf, "%d", params->h);
614     ret[1].sval = dupstr(buf);
615     ret[1].ival = 0;
616
617     ret[2].name = "Grid type";
618     ret[2].type = C_CHOICES;
619     ret[2].sval = GRID_CONFIGS;
620     ret[2].ival = params->type;
621
622     ret[3].name = "Difficulty";
623     ret[3].type = C_CHOICES;
624     ret[3].sval = DIFFCONFIG;
625     ret[3].ival = params->diff;
626
627     ret[4].name = NULL;
628     ret[4].type = C_END;
629     ret[4].sval = NULL;
630     ret[4].ival = 0;
631
632     return ret;
633 }
634
635 static game_params *custom_params(config_item *cfg)
636 {
637     game_params *ret = snew(game_params);
638
639     ret->w = atoi(cfg[0].sval);
640     ret->h = atoi(cfg[1].sval);
641     ret->type = cfg[2].ival;
642     ret->diff = cfg[3].ival;
643
644     ret->game_grid = NULL;
645     return ret;
646 }
647
648 static char *validate_params(game_params *params, int full)
649 {
650     if (params->type < 0 || params->type >= NUM_GRID_TYPES)
651         return "Illegal grid type";
652     if (params->w < grid_size_limits[params->type].amin ||
653         params->h < grid_size_limits[params->type].amin)
654         return grid_size_limits[params->type].aerr;
655     if (params->w < grid_size_limits[params->type].omin &&
656         params->h < grid_size_limits[params->type].omin)
657         return grid_size_limits[params->type].oerr;
658
659     /*
660      * This shouldn't be able to happen at all, since decode_params
661      * and custom_params will never generate anything that isn't
662      * within range.
663      */
664     assert(params->diff < DIFF_MAX);
665
666     return NULL;
667 }
668
669 /* Returns a newly allocated string describing the current puzzle */
670 static char *state_to_text(const game_state *state)
671 {
672     grid *g = state->game_grid;
673     char *retval;
674     int num_faces = g->num_faces;
675     char *description = snewn(num_faces + 1, char);
676     char *dp = description;
677     int empty_count = 0;
678     int i;
679
680     for (i = 0; i < num_faces; i++) {
681         if (state->clues[i] < 0) {
682             if (empty_count > 25) {
683                 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
684                 empty_count = 0;
685             }
686             empty_count++;
687         } else {
688             if (empty_count) {
689                 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
690                 empty_count = 0;
691             }
692             dp += sprintf(dp, "%c", (int)CLUE2CHAR(state->clues[i]));
693         }
694     }
695
696     if (empty_count)
697         dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
698
699     retval = dupstr(description);
700     sfree(description);
701
702     return retval;
703 }
704
705 /* We require that the params pass the test in validate_params and that the
706  * description fills the entire game area */
707 static char *validate_desc(game_params *params, char *desc)
708 {
709     int count = 0;
710     grid *g;
711     params_generate_grid(params);
712     g = params->game_grid;
713
714     for (; *desc; ++desc) {
715         if ((*desc >= '0' && *desc <= '9') || (*desc >= 'A' && *desc <= 'Z')) {
716             count++;
717             continue;
718         }
719         if (*desc >= 'a') {
720             count += *desc - 'a' + 1;
721             continue;
722         }
723         return "Unknown character in description";
724     }
725
726     if (count < g->num_faces)
727         return "Description too short for board size";
728     if (count > g->num_faces)
729         return "Description too long for board size";
730
731     return NULL;
732 }
733
734 /* Sums the lengths of the numbers in range [0,n) */
735 /* See equivalent function in solo.c for justification of this. */
736 static int len_0_to_n(int n)
737 {
738     int len = 1; /* Counting 0 as a bit of a special case */
739     int i;
740
741     for (i = 1; i < n; i *= 10) {
742         len += max(n - i, 0);
743     }
744
745     return len;
746 }
747
748 static char *encode_solve_move(const game_state *state)
749 {
750     int len;
751     char *ret, *p;
752     int i;
753     int num_edges = state->game_grid->num_edges;
754
755     /* This is going to return a string representing the moves needed to set
756      * every line in a grid to be the same as the ones in 'state'.  The exact
757      * length of this string is predictable. */
758
759     len = 1;  /* Count the 'S' prefix */
760     /* Numbers in all lines */
761     len += len_0_to_n(num_edges);
762     /* For each line we also have a letter */
763     len += num_edges;
764
765     ret = snewn(len + 1, char);
766     p = ret;
767
768     p += sprintf(p, "S");
769
770     for (i = 0; i < num_edges; i++) {
771         switch (state->lines[i]) {
772           case LINE_YES:
773             p += sprintf(p, "%dy", i);
774             break;
775           case LINE_NO:
776             p += sprintf(p, "%dn", i);
777             break;
778         }
779     }
780
781     /* No point in doing sums like that if they're going to be wrong */
782     assert(strlen(ret) <= (size_t)len);
783     return ret;
784 }
785
786 static game_ui *new_ui(game_state *state)
787 {
788     return NULL;
789 }
790
791 static void free_ui(game_ui *ui)
792 {
793 }
794
795 static char *encode_ui(game_ui *ui)
796 {
797     return NULL;
798 }
799
800 static void decode_ui(game_ui *ui, char *encoding)
801 {
802 }
803
804 static void game_changed_state(game_ui *ui, game_state *oldstate,
805                                game_state *newstate)
806 {
807 }
808
809 static void game_compute_size(game_params *params, int tilesize,
810                               int *x, int *y)
811 {
812     grid *g;
813     int grid_width, grid_height, rendered_width, rendered_height;
814
815     params_generate_grid(params);
816     g = params->game_grid;
817     grid_width = g->highest_x - g->lowest_x;
818     grid_height = g->highest_y - g->lowest_y;
819     /* multiply first to minimise rounding error on integer division */
820     rendered_width = grid_width * tilesize / g->tilesize;
821     rendered_height = grid_height * tilesize / g->tilesize;
822     *x = rendered_width + 2 * BORDER(tilesize) + 1;
823     *y = rendered_height + 2 * BORDER(tilesize) + 1;
824 }
825
826 static void game_set_size(drawing *dr, game_drawstate *ds,
827                           game_params *params, int tilesize)
828 {
829     ds->tilesize = tilesize;
830 }
831
832 static float *game_colours(frontend *fe, int *ncolours)
833 {
834     float *ret = snewn(4 * NCOLOURS, float);
835
836     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
837
838     ret[COL_FOREGROUND * 3 + 0] = 0.0F;
839     ret[COL_FOREGROUND * 3 + 1] = 0.0F;
840     ret[COL_FOREGROUND * 3 + 2] = 0.0F;
841
842     /*
843      * We want COL_LINEUNKNOWN to be a yellow which is a bit darker
844      * than the background. (I previously set it to 0.8,0.8,0, but
845      * found that this went badly with the 0.8,0.8,0.8 favoured as a
846      * background by the Java frontend.)
847      */
848     ret[COL_LINEUNKNOWN * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
849     ret[COL_LINEUNKNOWN * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
850     ret[COL_LINEUNKNOWN * 3 + 2] = 0.0F;
851
852     ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
853     ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
854     ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
855
856     ret[COL_MISTAKE * 3 + 0] = 1.0F;
857     ret[COL_MISTAKE * 3 + 1] = 0.0F;
858     ret[COL_MISTAKE * 3 + 2] = 0.0F;
859
860     ret[COL_SATISFIED * 3 + 0] = 0.0F;
861     ret[COL_SATISFIED * 3 + 1] = 0.0F;
862     ret[COL_SATISFIED * 3 + 2] = 0.0F;
863
864     /* We want the faint lines to be a bit darker than the background.
865      * Except if the background is pretty dark already; then it ought to be a
866      * bit lighter.  Oy vey.
867      */
868     ret[COL_FAINT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
869     ret[COL_FAINT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
870     ret[COL_FAINT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.9F;
871
872     *ncolours = NCOLOURS;
873     return ret;
874 }
875
876 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
877 {
878     struct game_drawstate *ds = snew(struct game_drawstate);
879     int num_faces = state->game_grid->num_faces;
880     int num_edges = state->game_grid->num_edges;
881     int i;
882
883     ds->tilesize = 0;
884     ds->started = 0;
885     ds->lines = snewn(num_edges, char);
886     ds->clue_error = snewn(num_faces, char);
887     ds->clue_satisfied = snewn(num_faces, char);
888     ds->textx = snewn(num_faces, int);
889     ds->texty = snewn(num_faces, int);
890     ds->flashing = 0;
891
892     memset(ds->lines, LINE_UNKNOWN, num_edges);
893     memset(ds->clue_error, 0, num_faces);
894     memset(ds->clue_satisfied, 0, num_faces);
895     for (i = 0; i < num_faces; i++)
896         ds->textx[i] = ds->texty[i] = -1;
897
898     return ds;
899 }
900
901 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
902 {
903     sfree(ds->clue_error);
904     sfree(ds->clue_satisfied);
905     sfree(ds->lines);
906     sfree(ds);
907 }
908
909 static int game_timing_state(game_state *state, game_ui *ui)
910 {
911     return TRUE;
912 }
913
914 static float game_anim_length(game_state *oldstate, game_state *newstate,
915                               int dir, game_ui *ui)
916 {
917     return 0.0F;
918 }
919
920 static int game_can_format_as_text_now(game_params *params)
921 {
922     if (params->type != 0)
923         return FALSE;
924     return TRUE;
925 }
926
927 static char *game_text_format(game_state *state)
928 {
929     int w, h, W, H;
930     int x, y, i;
931     int cell_size;
932     char *ret;
933     grid *g = state->game_grid;
934     grid_face *f;
935
936     assert(state->grid_type == 0);
937
938     /* Work out the basic size unit */
939     f = g->faces; /* first face */
940     assert(f->order == 4);
941     /* The dots are ordered clockwise, so the two opposite
942      * corners are guaranteed to span the square */
943     cell_size = abs(f->dots[0]->x - f->dots[2]->x);
944
945     w = (g->highest_x - g->lowest_x) / cell_size;
946     h = (g->highest_y - g->lowest_y) / cell_size;
947
948     /* Create a blank "canvas" to "draw" on */
949     W = 2 * w + 2;
950     H = 2 * h + 1;
951     ret = snewn(W * H + 1, char);
952     for (y = 0; y < H; y++) {
953         for (x = 0; x < W-1; x++) {
954             ret[y*W + x] = ' ';
955         }
956         ret[y*W + W-1] = '\n';
957     }
958     ret[H*W] = '\0';
959
960     /* Fill in edge info */
961     for (i = 0; i < g->num_edges; i++) {
962         grid_edge *e = g->edges + i;
963         /* Cell coordinates, from (0,0) to (w-1,h-1) */
964         int x1 = (e->dot1->x - g->lowest_x) / cell_size;
965         int x2 = (e->dot2->x - g->lowest_x) / cell_size;
966         int y1 = (e->dot1->y - g->lowest_y) / cell_size;
967         int y2 = (e->dot2->y - g->lowest_y) / cell_size;
968         /* Midpoint, in canvas coordinates (canvas coordinates are just twice
969          * cell coordinates) */
970         x = x1 + x2;
971         y = y1 + y2;
972         switch (state->lines[i]) {
973           case LINE_YES:
974             ret[y*W + x] = (y1 == y2) ? '-' : '|';
975             break;
976           case LINE_NO:
977             ret[y*W + x] = 'x';
978             break;
979           case LINE_UNKNOWN:
980             break; /* already a space */
981           default:
982             assert(!"Illegal line state");
983         }
984     }
985
986     /* Fill in clues */
987     for (i = 0; i < g->num_faces; i++) {
988         int x1, x2, y1, y2;
989
990         f = g->faces + i;
991         assert(f->order == 4);
992         /* Cell coordinates, from (0,0) to (w-1,h-1) */
993         x1 = (f->dots[0]->x - g->lowest_x) / cell_size;
994         x2 = (f->dots[2]->x - g->lowest_x) / cell_size;
995         y1 = (f->dots[0]->y - g->lowest_y) / cell_size;
996         y2 = (f->dots[2]->y - g->lowest_y) / cell_size;
997         /* Midpoint, in canvas coordinates */
998         x = x1 + x2;
999         y = y1 + y2;
1000         ret[y*W + x] = CLUE2CHAR(state->clues[i]);
1001     }
1002     return ret;
1003 }
1004
1005 /* ----------------------------------------------------------------------
1006  * Debug code
1007  */
1008
1009 #ifdef DEBUG_CACHES
1010 static void check_caches(const solver_state* sstate)
1011 {
1012     int i;
1013     const game_state *state = sstate->state;
1014     const grid *g = state->game_grid;
1015
1016     for (i = 0; i < g->num_dots; i++) {
1017         assert(dot_order(state, i, LINE_YES) == sstate->dot_yes_count[i]);
1018         assert(dot_order(state, i, LINE_NO) == sstate->dot_no_count[i]);
1019     }
1020
1021     for (i = 0; i < g->num_faces; i++) {
1022         assert(face_order(state, i, LINE_YES) == sstate->face_yes_count[i]);
1023         assert(face_order(state, i, LINE_NO) == sstate->face_no_count[i]);
1024     }
1025 }
1026
1027 #if 0
1028 #define check_caches(s) \
1029     do { \
1030         fprintf(stderr, "check_caches at line %d\n", __LINE__); \
1031         check_caches(s); \
1032     } while (0)
1033 #endif
1034 #endif /* DEBUG_CACHES */
1035
1036 /* ----------------------------------------------------------------------
1037  * Solver utility functions
1038  */
1039
1040 /* Sets the line (with index i) to the new state 'line_new', and updates
1041  * the cached counts of any affected faces and dots.
1042  * Returns TRUE if this actually changed the line's state. */
1043 static int solver_set_line(solver_state *sstate, int i,
1044                            enum line_state line_new
1045 #ifdef SHOW_WORKING
1046                            , const char *reason
1047 #endif
1048                            )
1049 {
1050     game_state *state = sstate->state;
1051     grid *g;
1052     grid_edge *e;
1053
1054     assert(line_new != LINE_UNKNOWN);
1055
1056     check_caches(sstate);
1057
1058     if (state->lines[i] == line_new) {
1059         return FALSE; /* nothing changed */
1060     }
1061     state->lines[i] = line_new;
1062
1063 #ifdef SHOW_WORKING
1064     fprintf(stderr, "solver: set line [%d] to %s (%s)\n",
1065             i, line_new == LINE_YES ? "YES" : "NO",
1066             reason);
1067 #endif
1068
1069     g = state->game_grid;
1070     e = g->edges + i;
1071
1072     /* Update the cache for both dots and both faces affected by this. */
1073     if (line_new == LINE_YES) {
1074         sstate->dot_yes_count[e->dot1 - g->dots]++;
1075         sstate->dot_yes_count[e->dot2 - g->dots]++;
1076         if (e->face1) {
1077             sstate->face_yes_count[e->face1 - g->faces]++;
1078         }
1079         if (e->face2) {
1080             sstate->face_yes_count[e->face2 - g->faces]++;
1081         }
1082     } else {
1083         sstate->dot_no_count[e->dot1 - g->dots]++;
1084         sstate->dot_no_count[e->dot2 - g->dots]++;
1085         if (e->face1) {
1086             sstate->face_no_count[e->face1 - g->faces]++;
1087         }
1088         if (e->face2) {
1089             sstate->face_no_count[e->face2 - g->faces]++;
1090         }
1091     }
1092
1093     check_caches(sstate);
1094     return TRUE;
1095 }
1096
1097 #ifdef SHOW_WORKING
1098 #define solver_set_line(a, b, c) \
1099     solver_set_line(a, b, c, __FUNCTION__)
1100 #endif
1101
1102 /*
1103  * Merge two dots due to the existence of an edge between them.
1104  * Updates the dsf tracking equivalence classes, and keeps track of
1105  * the length of path each dot is currently a part of.
1106  * Returns TRUE if the dots were already linked, ie if they are part of a
1107  * closed loop, and false otherwise.
1108  */
1109 static int merge_dots(solver_state *sstate, int edge_index)
1110 {
1111     int i, j, len;
1112     grid *g = sstate->state->game_grid;
1113     grid_edge *e = g->edges + edge_index;
1114
1115     i = e->dot1 - g->dots;
1116     j = e->dot2 - g->dots;
1117
1118     i = dsf_canonify(sstate->dotdsf, i);
1119     j = dsf_canonify(sstate->dotdsf, j);
1120
1121     if (i == j) {
1122         return TRUE;
1123     } else {
1124         len = sstate->looplen[i] + sstate->looplen[j];
1125         dsf_merge(sstate->dotdsf, i, j);
1126         i = dsf_canonify(sstate->dotdsf, i);
1127         sstate->looplen[i] = len;
1128         return FALSE;
1129     }
1130 }
1131
1132 /* Merge two lines because the solver has deduced that they must be either
1133  * identical or opposite.   Returns TRUE if this is new information, otherwise
1134  * FALSE. */
1135 static int merge_lines(solver_state *sstate, int i, int j, int inverse
1136 #ifdef SHOW_WORKING
1137                        , const char *reason
1138 #endif
1139                        )
1140 {
1141     int inv_tmp;
1142
1143     assert(i < sstate->state->game_grid->num_edges);
1144     assert(j < sstate->state->game_grid->num_edges);
1145
1146     i = edsf_canonify(sstate->linedsf, i, &inv_tmp);
1147     inverse ^= inv_tmp;
1148     j = edsf_canonify(sstate->linedsf, j, &inv_tmp);
1149     inverse ^= inv_tmp;
1150
1151     edsf_merge(sstate->linedsf, i, j, inverse);
1152
1153 #ifdef SHOW_WORKING
1154     if (i != j) {
1155         fprintf(stderr, "%s [%d] [%d] %s(%s)\n",
1156                 __FUNCTION__, i, j,
1157                 inverse ? "inverse " : "", reason);
1158     }
1159 #endif
1160     return (i != j);
1161 }
1162
1163 #ifdef SHOW_WORKING
1164 #define merge_lines(a, b, c, d) \
1165     merge_lines(a, b, c, d, __FUNCTION__)
1166 #endif
1167
1168 /* Count the number of lines of a particular type currently going into the
1169  * given dot. */
1170 static int dot_order(const game_state* state, int dot, char line_type)
1171 {
1172     int n = 0;
1173     grid *g = state->game_grid;
1174     grid_dot *d = g->dots + dot;
1175     int i;
1176
1177     for (i = 0; i < d->order; i++) {
1178         grid_edge *e = d->edges[i];
1179         if (state->lines[e - g->edges] == line_type)
1180             ++n;
1181     }
1182     return n;
1183 }
1184
1185 /* Count the number of lines of a particular type currently surrounding the
1186  * given face */
1187 static int face_order(const game_state* state, int face, char line_type)
1188 {
1189     int n = 0;
1190     grid *g = state->game_grid;
1191     grid_face *f = g->faces + face;
1192     int i;
1193
1194     for (i = 0; i < f->order; i++) {
1195         grid_edge *e = f->edges[i];
1196         if (state->lines[e - g->edges] == line_type)
1197             ++n;
1198     }
1199     return n;
1200 }
1201
1202 /* Set all lines bordering a dot of type old_type to type new_type
1203  * Return value tells caller whether this function actually did anything */
1204 static int dot_setall(solver_state *sstate, int dot,
1205                       char old_type, char new_type)
1206 {
1207     int retval = FALSE, r;
1208     game_state *state = sstate->state;
1209     grid *g;
1210     grid_dot *d;
1211     int i;
1212
1213     if (old_type == new_type)
1214         return FALSE;
1215
1216     g = state->game_grid;
1217     d = g->dots + dot;
1218
1219     for (i = 0; i < d->order; i++) {
1220         int line_index = d->edges[i] - g->edges;
1221         if (state->lines[line_index] == old_type) {
1222             r = solver_set_line(sstate, line_index, new_type);
1223             assert(r == TRUE);
1224             retval = TRUE;
1225         }
1226     }
1227     return retval;
1228 }
1229
1230 /* Set all lines bordering a face of type old_type to type new_type */
1231 static int face_setall(solver_state *sstate, int face,
1232                        char old_type, char new_type)
1233 {
1234     int retval = FALSE, r;
1235     game_state *state = sstate->state;
1236     grid *g;
1237     grid_face *f;
1238     int i;
1239
1240     if (old_type == new_type)
1241         return FALSE;
1242
1243     g = state->game_grid;
1244     f = g->faces + face;
1245
1246     for (i = 0; i < f->order; i++) {
1247         int line_index = f->edges[i] - g->edges;
1248         if (state->lines[line_index] == old_type) {
1249             r = solver_set_line(sstate, line_index, new_type);
1250             assert(r == TRUE);
1251             retval = TRUE;
1252         }
1253     }
1254     return retval;
1255 }
1256
1257 /* ----------------------------------------------------------------------
1258  * Loop generation and clue removal
1259  */
1260
1261 /* We're going to store lists of current candidate faces for colouring black
1262  * or white.
1263  * Each face gets a 'score', which tells us how adding that face right
1264  * now would affect the curliness of the solution loop.  We're trying to
1265  * maximise that quantity so will bias our random selection of faces to
1266  * colour those with high scores */
1267 struct face_score {
1268     int white_score;
1269     int black_score;
1270     unsigned long random;
1271     /* No need to store a grid_face* here.  The 'face_scores' array will
1272      * be a list of 'face_score' objects, one for each face of the grid, so
1273      * the position (index) within the 'face_scores' array will determine
1274      * which face corresponds to a particular face_score.
1275      * Having a single 'face_scores' array for all faces simplifies memory
1276      * management, and probably improves performance, because we don't have to 
1277      * malloc/free each individual face_score, and we don't have to maintain
1278      * a mapping from grid_face* pointers to face_score* pointers.
1279      */
1280 };
1281
1282 static int generic_sort_cmpfn(void *v1, void *v2, size_t offset)
1283 {
1284     struct face_score *f1 = v1;
1285     struct face_score *f2 = v2;
1286     int r;
1287
1288     r = *(int *)((char *)f2 + offset) - *(int *)((char *)f1 + offset);
1289     if (r) {
1290         return r;
1291     }
1292
1293     if (f1->random < f2->random)
1294         return -1;
1295     else if (f1->random > f2->random)
1296         return 1;
1297
1298     /*
1299      * It's _just_ possible that two faces might have been given
1300      * the same random value. In that situation, fall back to
1301      * comparing based on the positions within the face_scores list.
1302      * This introduces a tiny directional bias, but not a significant one.
1303      */
1304     return f1 - f2;
1305 }
1306
1307 static int white_sort_cmpfn(void *v1, void *v2)
1308 {
1309     return generic_sort_cmpfn(v1, v2, offsetof(struct face_score,white_score));
1310 }
1311
1312 static int black_sort_cmpfn(void *v1, void *v2)
1313 {
1314     return generic_sort_cmpfn(v1, v2, offsetof(struct face_score,black_score));
1315 }
1316
1317 enum face_colour { FACE_WHITE, FACE_GREY, FACE_BLACK };
1318
1319 /* face should be of type grid_face* here. */
1320 #define FACE_COLOUR(face) \
1321     ( (face) == NULL ? FACE_BLACK : \
1322           board[(face) - g->faces] )
1323
1324 /* 'board' is an array of these enums, indicating which faces are
1325  * currently black/white/grey.  'colour' is FACE_WHITE or FACE_BLACK.
1326  * Returns whether it's legal to colour the given face with this colour. */
1327 static int can_colour_face(grid *g, char* board, int face_index,
1328                            enum face_colour colour)
1329 {
1330     int i, j;
1331     grid_face *test_face = g->faces + face_index;
1332     grid_face *starting_face, *current_face;
1333     grid_dot *starting_dot;
1334     int transitions;
1335     int current_state, s; /* booleans: equal or not-equal to 'colour' */
1336     int found_same_coloured_neighbour = FALSE;
1337     assert(board[face_index] != colour);
1338
1339     /* Can only consider a face for colouring if it's adjacent to a face
1340      * with the same colour. */
1341     for (i = 0; i < test_face->order; i++) {
1342         grid_edge *e = test_face->edges[i];
1343         grid_face *f = (e->face1 == test_face) ? e->face2 : e->face1;
1344         if (FACE_COLOUR(f) == colour) {
1345             found_same_coloured_neighbour = TRUE;
1346             break;
1347         }
1348     }
1349     if (!found_same_coloured_neighbour)
1350         return FALSE;
1351
1352     /* Need to avoid creating a loop of faces of this colour around some
1353      * differently-coloured faces.
1354      * Also need to avoid meeting a same-coloured face at a corner, with
1355      * other-coloured faces in between.  Here's a simple test that (I believe)
1356      * takes care of both these conditions:
1357      *
1358      * Take the circular path formed by this face's edges, and inflate it
1359      * slightly outwards.  Imagine walking around this path and consider
1360      * the faces that you visit in sequence.  This will include all faces
1361      * touching the given face, either along an edge or just at a corner.
1362      * Count the number of 'colour'/not-'colour' transitions you encounter, as
1363      * you walk along the complete loop.  This will obviously turn out to be
1364      * an even number.
1365      * If 0, we're either in the middle of an "island" of this colour (should
1366      * be impossible as we're not supposed to create black or white loops),
1367      * or we're about to start a new island - also not allowed.
1368      * If 4 or greater, there are too many separate coloured regions touching
1369      * this face, and colouring it would create a loop or a corner-violation.
1370      * The only allowed case is when the count is exactly 2. */
1371
1372     /* i points to a dot around the test face.
1373      * j points to a face around the i^th dot.
1374      * The current face will always be:
1375      *     test_face->dots[i]->faces[j]
1376      * We assume dots go clockwise around the test face,
1377      * and faces go clockwise around dots. */
1378
1379     /*
1380      * The end condition is slightly fiddly. In sufficiently strange
1381      * degenerate grids, our test face may be adjacent to the same
1382      * other face multiple times (typically if it's the exterior
1383      * face). Consider this, in particular:
1384      * 
1385      *   +--+
1386      *   |  |
1387      *   +--+--+
1388      *   |  |  |
1389      *   +--+--+
1390      * 
1391      * The bottom left face there is adjacent to the exterior face
1392      * twice, so we can't just terminate our iteration when we reach
1393      * the same _face_ we started at. Furthermore, we can't
1394      * condition on having the same (i,j) pair either, because
1395      * several (i,j) pairs identify the bottom left contiguity with
1396      * the exterior face! We canonicalise the (i,j) pair by taking
1397      * one step around before we set the termination tracking.
1398      */
1399
1400     i = j = 0;
1401     current_face = test_face->dots[0]->faces[0];
1402     if (current_face == test_face) {
1403         j = 1;
1404         current_face = test_face->dots[0]->faces[1];
1405     }
1406     transitions = 0;
1407     current_state = (FACE_COLOUR(current_face) == colour);
1408     starting_dot = NULL;
1409     starting_face = NULL;
1410     while (TRUE) {
1411         /* Advance to next face.
1412          * Need to loop here because it might take several goes to
1413          * find it. */
1414         while (TRUE) {
1415             j++;
1416             if (j == test_face->dots[i]->order)
1417                 j = 0;
1418
1419             if (test_face->dots[i]->faces[j] == test_face) {
1420                 /* Advance to next dot round test_face, then
1421                  * find current_face around new dot
1422                  * and advance to the next face clockwise */
1423                 i++;
1424                 if (i == test_face->order)
1425                     i = 0;
1426                 for (j = 0; j < test_face->dots[i]->order; j++) {
1427                     if (test_face->dots[i]->faces[j] == current_face)
1428                         break;
1429                 }
1430                 /* Must actually find current_face around new dot,
1431                  * or else something's wrong with the grid. */
1432                 assert(j != test_face->dots[i]->order);
1433                 /* Found, so advance to next face and try again */
1434             } else {
1435                 break;
1436             }
1437         }
1438         /* (i,j) are now advanced to next face */
1439         current_face = test_face->dots[i]->faces[j];
1440         s = (FACE_COLOUR(current_face) == colour);
1441         if (!starting_dot) {
1442             starting_dot = test_face->dots[i];
1443             starting_face = current_face;
1444             current_state = s;
1445         } else {
1446             if (s != current_state) {
1447                 ++transitions;
1448                 current_state = s;
1449                 if (transitions > 2)
1450                     break;
1451             }
1452             if (test_face->dots[i] == starting_dot &&
1453                 current_face == starting_face)
1454                 break;
1455         }
1456     }
1457
1458     return (transitions == 2) ? TRUE : FALSE;
1459 }
1460
1461 /* Count the number of neighbours of 'face', having colour 'colour' */
1462 static int face_num_neighbours(grid *g, char *board, grid_face *face,
1463                                enum face_colour colour)
1464 {
1465     int colour_count = 0;
1466     int i;
1467     grid_face *f;
1468     grid_edge *e;
1469     for (i = 0; i < face->order; i++) {
1470         e = face->edges[i];
1471         f = (e->face1 == face) ? e->face2 : e->face1;
1472         if (FACE_COLOUR(f) == colour)
1473             ++colour_count;
1474     }
1475     return colour_count;
1476 }
1477
1478 /* The 'score' of a face reflects its current desirability for selection
1479  * as the next face to colour white or black.  We want to encourage moving
1480  * into grey areas and increasing loopiness, so we give scores according to
1481  * how many of the face's neighbours are currently coloured the same as the
1482  * proposed colour. */
1483 static int face_score(grid *g, char *board, grid_face *face,
1484                       enum face_colour colour)
1485 {
1486     /* Simple formula: score = 0 - num. same-coloured neighbours,
1487      * so a higher score means fewer same-coloured neighbours. */
1488     return -face_num_neighbours(g, board, face, colour);
1489 }
1490
1491 /* Generate a new complete set of clues for the given game_state.
1492  * The method is to generate a WHITE/BLACK colouring of all the faces,
1493  * such that the WHITE faces will define the inside of the path, and the
1494  * BLACK faces define the outside.
1495  * To do this, we initially colour all faces GREY.  The infinite space outside
1496  * the grid is coloured BLACK, and we choose a random face to colour WHITE.
1497  * Then we gradually grow the BLACK and the WHITE regions, eliminating GREY
1498  * faces, until the grid is filled with BLACK/WHITE.  As we grow the regions,
1499  * we avoid creating loops of a single colour, to preserve the topological
1500  * shape of the WHITE and BLACK regions.
1501  * We also try to make the boundary as loopy and twisty as possible, to avoid
1502  * generating paths that are uninteresting.
1503  * The algorithm works by choosing a BLACK/WHITE colour, then choosing a GREY
1504  * face that can be coloured with that colour (without violating the
1505  * topological shape of that region).  It's not obvious, but I think this
1506  * algorithm is guaranteed to terminate without leaving any GREY faces behind.
1507  * Indeed, if there are any GREY faces at all, both the WHITE and BLACK
1508  * regions can be grown.
1509  * This is checked using assert()ions, and I haven't seen any failures yet.
1510  *
1511  * Hand-wavy proof: imagine what can go wrong...
1512  *
1513  * Could the white faces get completely cut off by the black faces, and still
1514  * leave some grey faces remaining?
1515  * No, because then the black faces would form a loop around both the white
1516  * faces and the grey faces, which is disallowed because we continually
1517  * maintain the correct topological shape of the black region.
1518  * Similarly, the black faces can never get cut off by the white faces.  That
1519  * means both the WHITE and BLACK regions always have some room to grow into
1520  * the GREY regions.
1521  * Could it be that we can't colour some GREY face, because there are too many
1522  * WHITE/BLACK transitions as we walk round the face? (see the
1523  * can_colour_face() function for details)
1524  * No.  Imagine otherwise, and we see WHITE/BLACK/WHITE/BLACK as we walk
1525  * around the face.  The two WHITE faces would be connected by a WHITE path,
1526  * and the BLACK faces would be connected by a BLACK path.  These paths would
1527  * have to cross, which is impossible.
1528  * Another thing that could go wrong: perhaps we can't find any GREY face to
1529  * colour WHITE, because it would create a loop-violation or a corner-violation
1530  * with the other WHITE faces?
1531  * This is a little bit tricky to prove impossible.  Imagine you have such a
1532  * GREY face (that is, if you coloured it WHITE, you would create a WHITE loop
1533  * or corner violation).
1534  * That would cut all the non-white area into two blobs.  One of those blobs
1535  * must be free of BLACK faces (because the BLACK stuff is a connected blob).
1536  * So we have a connected GREY area, completely surrounded by WHITE
1537  * (including the GREY face we've tentatively coloured WHITE).
1538  * A well-known result in graph theory says that you can always find a GREY
1539  * face whose removal leaves the remaining GREY area connected.  And it says
1540  * there are at least two such faces, so we can always choose the one that
1541  * isn't the "tentative" GREY face.  Colouring that face WHITE leaves
1542  * everything nice and connected, including that "tentative" GREY face which
1543  * acts as a gateway to the rest of the non-WHITE grid.
1544  */
1545 static void add_full_clues(game_state *state, random_state *rs)
1546 {
1547     signed char *clues = state->clues;
1548     char *board;
1549     grid *g = state->game_grid;
1550     int i, j;
1551     int num_faces = g->num_faces;
1552     struct face_score *face_scores; /* Array of face_score objects */
1553     struct face_score *fs; /* Points somewhere in the above list */
1554     struct grid_face *cur_face;
1555     tree234 *lightable_faces_sorted;
1556     tree234 *darkable_faces_sorted;
1557     int *face_list;
1558     int do_random_pass;
1559
1560     board = snewn(num_faces, char);
1561
1562     /* Make a board */
1563     memset(board, FACE_GREY, num_faces);
1564     
1565     /* Create and initialise the list of face_scores */
1566     face_scores = snewn(num_faces, struct face_score);
1567     for (i = 0; i < num_faces; i++) {
1568         face_scores[i].random = random_bits(rs, 31);
1569         face_scores[i].black_score = face_scores[i].white_score = 0;
1570     }
1571     
1572     /* Colour a random, finite face white.  The infinite face is implicitly
1573      * coloured black.  Together, they will seed the random growth process
1574      * for the black and white areas. */
1575     i = random_upto(rs, num_faces);
1576     board[i] = FACE_WHITE;
1577
1578     /* We need a way of favouring faces that will increase our loopiness.
1579      * We do this by maintaining a list of all candidate faces sorted by
1580      * their score and choose randomly from that with appropriate skew.
1581      * In order to avoid consistently biasing towards particular faces, we
1582      * need the sort order _within_ each group of scores to be completely
1583      * random.  But it would be abusing the hospitality of the tree234 data
1584      * structure if our comparison function were nondeterministic :-).  So with
1585      * each face we associate a random number that does not change during a
1586      * particular run of the generator, and use that as a secondary sort key.
1587      * Yes, this means we will be biased towards particular random faces in
1588      * any one run but that doesn't actually matter. */
1589
1590     lightable_faces_sorted = newtree234(white_sort_cmpfn);
1591     darkable_faces_sorted = newtree234(black_sort_cmpfn);
1592
1593     /* Initialise the lists of lightable and darkable faces.  This is
1594      * slightly different from the code inside the while-loop, because we need
1595      * to check every face of the board (the grid structure does not keep a
1596      * list of the infinite face's neighbours). */
1597     for (i = 0; i < num_faces; i++) {
1598         grid_face *f = g->faces + i;
1599         struct face_score *fs = face_scores + i;
1600         if (board[i] != FACE_GREY) continue;
1601         /* We need the full colourability check here, it's not enough simply
1602          * to check neighbourhood.  On some grids, a neighbour of the infinite
1603          * face is not necessarily darkable. */
1604         if (can_colour_face(g, board, i, FACE_BLACK)) {
1605             fs->black_score = face_score(g, board, f, FACE_BLACK);
1606             add234(darkable_faces_sorted, fs);
1607         }
1608         if (can_colour_face(g, board, i, FACE_WHITE)) {
1609             fs->white_score = face_score(g, board, f, FACE_WHITE);
1610             add234(lightable_faces_sorted, fs);
1611         }
1612     }
1613
1614     /* Colour faces one at a time until no more faces are colourable. */
1615     while (TRUE)
1616     {
1617         enum face_colour colour;
1618         struct face_score *fs_white, *fs_black;
1619         int c_lightable = count234(lightable_faces_sorted);
1620         int c_darkable = count234(darkable_faces_sorted);
1621         if (c_lightable == 0 && c_darkable == 0) {
1622             /* No more faces we can use at all. */
1623             break;
1624         }
1625         assert(c_lightable != 0 && c_darkable != 0);
1626
1627         fs_white = (struct face_score *)index234(lightable_faces_sorted, 0);
1628         fs_black = (struct face_score *)index234(darkable_faces_sorted, 0);
1629
1630         /* Choose a colour, and colour the best available face
1631          * with that colour. */
1632         colour = random_upto(rs, 2) ? FACE_WHITE : FACE_BLACK;
1633
1634         if (colour == FACE_WHITE)
1635             fs = fs_white;
1636         else
1637             fs = fs_black;
1638         assert(fs);
1639         i = fs - face_scores;
1640         assert(board[i] == FACE_GREY);
1641         board[i] = colour;
1642
1643         /* Remove this newly-coloured face from the lists.  These lists should
1644          * only contain grey faces. */
1645         del234(lightable_faces_sorted, fs);
1646         del234(darkable_faces_sorted, fs);
1647
1648         /* Remember which face we've just coloured */
1649         cur_face = g->faces + i;
1650
1651         /* The face we've just coloured potentially affects the colourability
1652          * and the scores of any neighbouring faces (touching at a corner or
1653          * edge).  So the search needs to be conducted around all faces
1654          * touching the one we've just lit.  Iterate over its corners, then
1655          * over each corner's faces.  For each such face, we remove it from
1656          * the lists, recalculate any scores, then add it back to the lists
1657          * (depending on whether it is lightable, darkable or both). */
1658         for (i = 0; i < cur_face->order; i++) {
1659             grid_dot *d = cur_face->dots[i];
1660             for (j = 0; j < d->order; j++) {
1661                 grid_face *f = d->faces[j];
1662                 int fi; /* face index of f */
1663
1664                 if (f == NULL)
1665                     continue;
1666                 if (f == cur_face)
1667                     continue;
1668                 
1669                 /* If the face is already coloured, it won't be on our
1670                  * lightable/darkable lists anyway, so we can skip it without 
1671                  * bothering with the removal step. */
1672                 if (FACE_COLOUR(f) != FACE_GREY) continue; 
1673
1674                 /* Find the face index and face_score* corresponding to f */
1675                 fi = f - g->faces;                
1676                 fs = face_scores + fi;
1677
1678                 /* Remove from lightable list if it's in there.  We do this,
1679                  * even if it is still lightable, because the score might
1680                  * be different, and we need to remove-then-add to maintain
1681                  * correct sort order. */
1682                 del234(lightable_faces_sorted, fs);
1683                 if (can_colour_face(g, board, fi, FACE_WHITE)) {
1684                     fs->white_score = face_score(g, board, f, FACE_WHITE);
1685                     add234(lightable_faces_sorted, fs);
1686                 }
1687                 /* Do the same for darkable list. */
1688                 del234(darkable_faces_sorted, fs);
1689                 if (can_colour_face(g, board, fi, FACE_BLACK)) {
1690                     fs->black_score = face_score(g, board, f, FACE_BLACK);
1691                     add234(darkable_faces_sorted, fs);
1692                 }
1693             }
1694         }
1695     }
1696
1697     /* Clean up */
1698     freetree234(lightable_faces_sorted);
1699     freetree234(darkable_faces_sorted);
1700     sfree(face_scores);
1701
1702     /* The next step requires a shuffled list of all faces */
1703     face_list = snewn(num_faces, int);
1704     for (i = 0; i < num_faces; ++i) {
1705         face_list[i] = i;
1706     }
1707     shuffle(face_list, num_faces, sizeof(int), rs);
1708
1709     /* The above loop-generation algorithm can often leave large clumps
1710      * of faces of one colour.  In extreme cases, the resulting path can be 
1711      * degenerate and not very satisfying to solve.
1712      * This next step alleviates this problem:
1713      * Go through the shuffled list, and flip the colour of any face we can
1714      * legally flip, and which is adjacent to only one face of the opposite
1715      * colour - this tends to grow 'tendrils' into any clumps.
1716      * Repeat until we can find no more faces to flip.  This will
1717      * eventually terminate, because each flip increases the loop's
1718      * perimeter, which cannot increase for ever.
1719      * The resulting path will have maximal loopiness (in the sense that it
1720      * cannot be improved "locally".  Unfortunately, this allows a player to
1721      * make some illicit deductions.  To combat this (and make the path more
1722      * interesting), we do one final pass making random flips. */
1723
1724     /* Set to TRUE for final pass */
1725     do_random_pass = FALSE;
1726
1727     while (TRUE) {
1728         /* Remember whether a flip occurred during this pass */
1729         int flipped = FALSE;
1730
1731         for (i = 0; i < num_faces; ++i) {
1732             int j = face_list[i];
1733             enum face_colour opp =
1734                 (board[j] == FACE_WHITE) ? FACE_BLACK : FACE_WHITE;
1735             if (can_colour_face(g, board, j, opp)) {
1736                 grid_face *face = g->faces +j;
1737                 if (do_random_pass) {
1738                     /* final random pass */
1739                     if (!random_upto(rs, 10))
1740                         board[j] = opp;
1741                 } else {
1742                     /* normal pass - flip when neighbour count is 1 */
1743                     if (face_num_neighbours(g, board, face, opp) == 1) {
1744                         board[j] = opp;
1745                         flipped = TRUE;
1746                     }
1747                 }
1748             }
1749         }
1750
1751         if (do_random_pass) break;
1752         if (!flipped) do_random_pass = TRUE;
1753      }
1754
1755     sfree(face_list);
1756
1757     /* Fill out all the clues by initialising to 0, then iterating over
1758      * all edges and incrementing each clue as we find edges that border
1759      * between BLACK/WHITE faces.  While we're at it, we verify that the
1760      * algorithm does work, and there aren't any GREY faces still there. */
1761     memset(clues, 0, num_faces);
1762     for (i = 0; i < g->num_edges; i++) {
1763         grid_edge *e = g->edges + i;
1764         grid_face *f1 = e->face1;
1765         grid_face *f2 = e->face2;
1766         enum face_colour c1 = FACE_COLOUR(f1);
1767         enum face_colour c2 = FACE_COLOUR(f2);
1768         assert(c1 != FACE_GREY);
1769         assert(c2 != FACE_GREY);
1770         if (c1 != c2) {
1771             if (f1) clues[f1 - g->faces]++;
1772             if (f2) clues[f2 - g->faces]++;
1773         }
1774     }
1775
1776     sfree(board);
1777 }
1778
1779
1780 static int game_has_unique_soln(const game_state *state, int diff)
1781 {
1782     int ret;
1783     solver_state *sstate_new;
1784     solver_state *sstate = new_solver_state((game_state *)state, diff);
1785
1786     sstate_new = solve_game_rec(sstate);
1787
1788     assert(sstate_new->solver_status != SOLVER_MISTAKE);
1789     ret = (sstate_new->solver_status == SOLVER_SOLVED);
1790
1791     free_solver_state(sstate_new);
1792     free_solver_state(sstate);
1793
1794     return ret;
1795 }
1796
1797
1798 /* Remove clues one at a time at random. */
1799 static game_state *remove_clues(game_state *state, random_state *rs,
1800                                 int diff)
1801 {
1802     int *face_list;
1803     int num_faces = state->game_grid->num_faces;
1804     game_state *ret = dup_game(state), *saved_ret;
1805     int n;
1806
1807     /* We need to remove some clues.  We'll do this by forming a list of all
1808      * available clues, shuffling it, then going along one at a
1809      * time clearing each clue in turn for which doing so doesn't render the
1810      * board unsolvable. */
1811     face_list = snewn(num_faces, int);
1812     for (n = 0; n < num_faces; ++n) {
1813         face_list[n] = n;
1814     }
1815
1816     shuffle(face_list, num_faces, sizeof(int), rs);
1817
1818     for (n = 0; n < num_faces; ++n) {
1819         saved_ret = dup_game(ret);
1820         ret->clues[face_list[n]] = -1;
1821
1822         if (game_has_unique_soln(ret, diff)) {
1823             free_game(saved_ret);
1824         } else {
1825             free_game(ret);
1826             ret = saved_ret;
1827         }
1828     }
1829     sfree(face_list);
1830
1831     return ret;
1832 }
1833
1834
1835 static char *new_game_desc(game_params *params, random_state *rs,
1836                            char **aux, int interactive)
1837 {
1838     /* solution and description both use run-length encoding in obvious ways */
1839     char *retval;
1840     grid *g;
1841     game_state *state = snew(game_state);
1842     game_state *state_new;
1843     params_generate_grid(params);
1844     state->game_grid = g = params->game_grid;
1845     g->refcount++;
1846     state->clues = snewn(g->num_faces, signed char);
1847     state->lines = snewn(g->num_edges, char);
1848     state->line_errors = snewn(g->num_edges, unsigned char);
1849
1850     state->grid_type = params->type;
1851
1852     newboard_please:
1853
1854     memset(state->lines, LINE_UNKNOWN, g->num_edges);
1855     memset(state->line_errors, 0, g->num_edges);
1856
1857     state->solved = state->cheated = FALSE;
1858
1859     /* Get a new random solvable board with all its clues filled in.  Yes, this
1860      * can loop for ever if the params are suitably unfavourable, but
1861      * preventing games smaller than 4x4 seems to stop this happening */
1862     do {
1863         add_full_clues(state, rs);
1864     } while (!game_has_unique_soln(state, params->diff));
1865
1866     state_new = remove_clues(state, rs, params->diff);
1867     free_game(state);
1868     state = state_new;
1869
1870
1871     if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1872 #ifdef SHOW_WORKING
1873         fprintf(stderr, "Rejecting board, it is too easy\n");
1874 #endif
1875         goto newboard_please;
1876     }
1877
1878     retval = state_to_text(state);
1879
1880     free_game(state);
1881
1882     assert(!validate_desc(params, retval));
1883
1884     return retval;
1885 }
1886
1887 static game_state *new_game(midend *me, game_params *params, char *desc)
1888 {
1889     int i;
1890     game_state *state = snew(game_state);
1891     int empties_to_make = 0;
1892     int n,n2;
1893     const char *dp = desc;
1894     grid *g;
1895     int num_faces, num_edges;
1896
1897     params_generate_grid(params);
1898     state->game_grid = g = params->game_grid;
1899     g->refcount++;
1900     num_faces = g->num_faces;
1901     num_edges = g->num_edges;
1902
1903     state->clues = snewn(num_faces, signed char);
1904     state->lines = snewn(num_edges, char);
1905     state->line_errors = snewn(num_edges, unsigned char);
1906
1907     state->solved = state->cheated = FALSE;
1908
1909     state->grid_type = params->type;
1910
1911     for (i = 0; i < num_faces; i++) {
1912         if (empties_to_make) {
1913             empties_to_make--;
1914             state->clues[i] = -1;
1915             continue;
1916         }
1917
1918         assert(*dp);
1919         n = *dp - '0';
1920         n2 = *dp - 'A' + 10;
1921         if (n >= 0 && n < 10) {
1922             state->clues[i] = n;
1923         } else if (n2 >= 10 && n2 < 36) {
1924             state->clues[i] = n2;
1925         } else {
1926             n = *dp - 'a' + 1;
1927             assert(n > 0);
1928             state->clues[i] = -1;
1929             empties_to_make = n - 1;
1930         }
1931         ++dp;
1932     }
1933
1934     memset(state->lines, LINE_UNKNOWN, num_edges);
1935     memset(state->line_errors, 0, num_edges);
1936     return state;
1937 }
1938
1939 /* Calculates the line_errors data, and checks if the current state is a
1940  * solution */
1941 static int check_completion(game_state *state)
1942 {
1943     grid *g = state->game_grid;
1944     int *dsf;
1945     int num_faces = g->num_faces;
1946     int i;
1947     int infinite_area, finite_area;
1948     int loops_found = 0;
1949     int found_edge_not_in_loop = FALSE;
1950
1951     memset(state->line_errors, 0, g->num_edges);
1952
1953     /* LL implementation of SGT's idea:
1954      * A loop will partition the grid into an inside and an outside.
1955      * If there is more than one loop, the grid will be partitioned into
1956      * even more distinct regions.  We can therefore track equivalence of
1957      * faces, by saying that two faces are equivalent when there is a non-YES
1958      * edge between them.
1959      * We could keep track of the number of connected components, by counting
1960      * the number of dsf-merges that aren't no-ops.
1961      * But we're only interested in 3 separate cases:
1962      * no loops, one loop, more than one loop.
1963      *
1964      * No loops: all faces are equivalent to the infinite face.
1965      * One loop: only two equivalence classes - finite and infinite.
1966      * >= 2 loops: there are 2 distinct finite regions.
1967      *
1968      * So we simply make two passes through all the edges.
1969      * In the first pass, we dsf-merge the two faces bordering each non-YES
1970      * edge.
1971      * In the second pass, we look for YES-edges bordering:
1972      * a) two non-equivalent faces.
1973      * b) two non-equivalent faces, and one of them is part of a different
1974      *    finite area from the first finite area we've seen.
1975      *
1976      * An occurrence of a) means there is at least one loop.
1977      * An occurrence of b) means there is more than one loop.
1978      * Edges satisfying a) are marked as errors.
1979      *
1980      * While we're at it, we set a flag if we find a YES edge that is not
1981      * part of a loop.
1982      * This information will help decide, if there's a single loop, whether it
1983      * is a candidate for being a solution (that is, all YES edges are part of
1984      * this loop).
1985      *
1986      * If there is a candidate loop, we then go through all clues and check
1987      * they are all satisfied.  If so, we have found a solution and we can
1988      * unmark all line_errors.
1989      */
1990     
1991     /* Infinite face is at the end - its index is num_faces.
1992      * This macro is just to make this obvious! */
1993     #define INF_FACE num_faces
1994     dsf = snewn(num_faces + 1, int);
1995     dsf_init(dsf, num_faces + 1);
1996     
1997     /* First pass */
1998     for (i = 0; i < g->num_edges; i++) {
1999         grid_edge *e = g->edges + i;
2000         int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
2001         int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
2002         if (state->lines[i] != LINE_YES)
2003             dsf_merge(dsf, f1, f2);
2004     }
2005     
2006     /* Second pass */
2007     infinite_area = dsf_canonify(dsf, INF_FACE);
2008     finite_area = -1;
2009     for (i = 0; i < g->num_edges; i++) {
2010         grid_edge *e = g->edges + i;
2011         int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
2012         int can1 = dsf_canonify(dsf, f1);
2013         int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
2014         int can2 = dsf_canonify(dsf, f2);
2015         if (state->lines[i] != LINE_YES) continue;
2016
2017         if (can1 == can2) {
2018             /* Faces are equivalent, so this edge not part of a loop */
2019             found_edge_not_in_loop = TRUE;
2020             continue;
2021         }
2022         state->line_errors[i] = TRUE;
2023         if (loops_found == 0) loops_found = 1;
2024
2025         /* Don't bother with further checks if we've already found 2 loops */
2026         if (loops_found == 2) continue;
2027
2028         if (finite_area == -1) {
2029             /* Found our first finite area */
2030             if (can1 != infinite_area)
2031                 finite_area = can1;
2032             else
2033                 finite_area = can2;
2034         }
2035
2036         /* Have we found a second area? */
2037         if (finite_area != -1) {
2038             if (can1 != infinite_area && can1 != finite_area) {
2039                 loops_found = 2;
2040                 continue;
2041             }
2042             if (can2 != infinite_area && can2 != finite_area) {
2043                 loops_found = 2;
2044             }
2045         }
2046     }
2047
2048 /*
2049     printf("loops_found = %d\n", loops_found);
2050     printf("found_edge_not_in_loop = %s\n",
2051         found_edge_not_in_loop ? "TRUE" : "FALSE");
2052 */
2053
2054     sfree(dsf); /* No longer need the dsf */
2055     
2056     /* Have we found a candidate loop? */
2057     if (loops_found == 1 && !found_edge_not_in_loop) {
2058         /* Yes, so check all clues are satisfied */
2059         int found_clue_violation = FALSE;
2060         for (i = 0; i < num_faces; i++) {
2061             int c = state->clues[i];
2062             if (c >= 0) {
2063                 if (face_order(state, i, LINE_YES) != c) {
2064                     found_clue_violation = TRUE;
2065                     break;
2066                 }
2067             }
2068         }
2069         
2070         if (!found_clue_violation) {
2071             /* The loop is good */
2072             memset(state->line_errors, 0, g->num_edges);
2073             return TRUE; /* No need to bother checking for dot violations */
2074         }
2075     }
2076
2077     /* Check for dot violations */
2078     for (i = 0; i < g->num_dots; i++) {
2079         int yes = dot_order(state, i, LINE_YES);
2080         int unknown = dot_order(state, i, LINE_UNKNOWN);
2081         if ((yes == 1 && unknown == 0) || (yes >= 3)) {
2082             /* violation, so mark all YES edges as errors */
2083             grid_dot *d = g->dots + i;
2084             int j;
2085             for (j = 0; j < d->order; j++) {
2086                 int e = d->edges[j] - g->edges;
2087                 if (state->lines[e] == LINE_YES)
2088                     state->line_errors[e] = TRUE;
2089             }
2090         }
2091     }
2092     return FALSE;
2093 }
2094
2095 /* ----------------------------------------------------------------------
2096  * Solver logic
2097  *
2098  * Our solver modes operate as follows.  Each mode also uses the modes above it.
2099  *
2100  *   Easy Mode
2101  *   Just implement the rules of the game.
2102  *
2103  *   Normal and Tricky Modes
2104  *   For each (adjacent) pair of lines through each dot we store a bit for
2105  *   whether at least one of them is on and whether at most one is on.  (If we
2106  *   know both or neither is on that's already stored more directly.)
2107  *
2108  *   Advanced Mode
2109  *   Use edsf data structure to make equivalence classes of lines that are
2110  *   known identical to or opposite to one another.
2111  */
2112
2113
2114 /* DLines:
2115  * For general grids, we consider "dlines" to be pairs of lines joined
2116  * at a dot.  The lines must be adjacent around the dot, so we can think of
2117  * a dline as being a dot+face combination.  Or, a dot+edge combination where
2118  * the second edge is taken to be the next clockwise edge from the dot.
2119  * Original loopy code didn't have this extra restriction of the lines being
2120  * adjacent.  From my tests with square grids, this extra restriction seems to
2121  * take little, if anything, away from the quality of the puzzles.
2122  * A dline can be uniquely identified by an edge/dot combination, given that
2123  * a dline-pair always goes clockwise around its common dot.  The edge/dot
2124  * combination can be represented by an edge/bool combination - if bool is
2125  * TRUE, use edge->dot1 else use edge->dot2.  So the total number of dlines is
2126  * exactly twice the number of edges in the grid - although the dlines
2127  * spanning the infinite face are not all that useful to the solver.
2128  * Note that, by convention, a dline goes clockwise around its common dot,
2129  * which means the dline goes anti-clockwise around its common face.
2130  */
2131
2132 /* Helper functions for obtaining an index into an array of dlines, given
2133  * various information.  We assume the grid layout conventions about how
2134  * the various lists are interleaved - see grid_make_consistent() for
2135  * details. */
2136
2137 /* i points to the first edge of the dline pair, reading clockwise around
2138  * the dot. */
2139 static int dline_index_from_dot(grid *g, grid_dot *d, int i)
2140 {
2141     grid_edge *e = d->edges[i];
2142     int ret;
2143 #ifdef DEBUG_DLINES
2144     grid_edge *e2;
2145     int i2 = i+1;
2146     if (i2 == d->order) i2 = 0;
2147     e2 = d->edges[i2];
2148 #endif
2149     ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
2150 #ifdef DEBUG_DLINES
2151     printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
2152            (int)(d - g->dots), i, (int)(e - g->edges),
2153            (int)(e2 - g->edges), ret);
2154 #endif
2155     return ret;
2156 }
2157 /* i points to the second edge of the dline pair, reading clockwise around
2158  * the face.  That is, the edges of the dline, starting at edge{i}, read
2159  * anti-clockwise around the face.  By layout conventions, the common dot
2160  * of the dline will be f->dots[i] */
2161 static int dline_index_from_face(grid *g, grid_face *f, int i)
2162 {
2163     grid_edge *e = f->edges[i];
2164     grid_dot *d = f->dots[i];
2165     int ret;
2166 #ifdef DEBUG_DLINES
2167     grid_edge *e2;
2168     int i2 = i - 1;
2169     if (i2 < 0) i2 += f->order;
2170     e2 = f->edges[i2];
2171 #endif
2172     ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
2173 #ifdef DEBUG_DLINES
2174     printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
2175            (int)(f - g->faces), i, (int)(e - g->edges),
2176            (int)(e2 - g->edges), ret);
2177 #endif
2178     return ret;
2179 }
2180 static int is_atleastone(const char *dline_array, int index)
2181 {
2182     return BIT_SET(dline_array[index], 0);
2183 }
2184 static int set_atleastone(char *dline_array, int index)
2185 {
2186     return SET_BIT(dline_array[index], 0);
2187 }
2188 static int is_atmostone(const char *dline_array, int index)
2189 {
2190     return BIT_SET(dline_array[index], 1);
2191 }
2192 static int set_atmostone(char *dline_array, int index)
2193 {
2194     return SET_BIT(dline_array[index], 1);
2195 }
2196
2197 static void array_setall(char *array, char from, char to, int len)
2198 {
2199     char *p = array, *p_old = p;
2200     int len_remaining = len;
2201
2202     while ((p = memchr(p, from, len_remaining))) {
2203         *p = to;
2204         len_remaining -= p - p_old;
2205         p_old = p;
2206     }
2207 }
2208
2209 /* Helper, called when doing dline dot deductions, in the case where we
2210  * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
2211  * them (because of dline atmostone/atleastone).
2212  * On entry, edge points to the first of these two UNKNOWNs.  This function
2213  * will find the opposite UNKNOWNS (if they are adjacent to one another)
2214  * and set their corresponding dline to atleastone.  (Setting atmostone
2215  * already happens in earlier dline deductions) */
2216 static int dline_set_opp_atleastone(solver_state *sstate,
2217                                     grid_dot *d, int edge)
2218 {
2219     game_state *state = sstate->state;
2220     grid *g = state->game_grid;
2221     int N = d->order;
2222     int opp, opp2;
2223     for (opp = 0; opp < N; opp++) {
2224         int opp_dline_index;
2225         if (opp == edge || opp == edge+1 || opp == edge-1)
2226             continue;
2227         if (opp == 0 && edge == N-1)
2228             continue;
2229         if (opp == N-1 && edge == 0)
2230             continue;
2231         opp2 = opp + 1;
2232         if (opp2 == N) opp2 = 0;
2233         /* Check if opp, opp2 point to LINE_UNKNOWNs */
2234         if (state->lines[d->edges[opp] - g->edges] != LINE_UNKNOWN)
2235             continue;
2236         if (state->lines[d->edges[opp2] - g->edges] != LINE_UNKNOWN)
2237             continue;
2238         /* Found opposite UNKNOWNS and they're next to each other */
2239         opp_dline_index = dline_index_from_dot(g, d, opp);
2240         return set_atleastone(sstate->dlines, opp_dline_index);
2241     }
2242     return FALSE;
2243 }
2244
2245
2246 /* Set pairs of lines around this face which are known to be identical, to
2247  * the given line_state */
2248 static int face_setall_identical(solver_state *sstate, int face_index,
2249                                  enum line_state line_new)
2250 {
2251     /* can[dir] contains the canonical line associated with the line in
2252      * direction dir from the square in question.  Similarly inv[dir] is
2253      * whether or not the line in question is inverse to its canonical
2254      * element. */
2255     int retval = FALSE;
2256     game_state *state = sstate->state;
2257     grid *g = state->game_grid;
2258     grid_face *f = g->faces + face_index;
2259     int N = f->order;
2260     int i, j;
2261     int can1, can2, inv1, inv2;
2262
2263     for (i = 0; i < N; i++) {
2264         int line1_index = f->edges[i] - g->edges;
2265         if (state->lines[line1_index] != LINE_UNKNOWN)
2266             continue;
2267         for (j = i + 1; j < N; j++) {
2268             int line2_index = f->edges[j] - g->edges;
2269             if (state->lines[line2_index] != LINE_UNKNOWN)
2270                 continue;
2271
2272             /* Found two UNKNOWNS */
2273             can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
2274             can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
2275             if (can1 == can2 && inv1 == inv2) {
2276                 solver_set_line(sstate, line1_index, line_new);
2277                 solver_set_line(sstate, line2_index, line_new);
2278             }
2279         }
2280     }
2281     return retval;
2282 }
2283
2284 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
2285  * return the edge indices into e. */
2286 static void find_unknowns(game_state *state,
2287     grid_edge **edge_list, /* Edge list to search (from a face or a dot) */
2288     int expected_count, /* Number of UNKNOWNs (comes from solver's cache) */
2289     int *e /* Returned edge indices */)
2290 {
2291     int c = 0;
2292     grid *g = state->game_grid;
2293     while (c < expected_count) {
2294         int line_index = *edge_list - g->edges;
2295         if (state->lines[line_index] == LINE_UNKNOWN) {
2296             e[c] = line_index;
2297             c++;
2298         }
2299         ++edge_list;
2300     }
2301 }
2302
2303 /* If we have a list of edges, and we know whether the number of YESs should
2304  * be odd or even, and there are only a few UNKNOWNs, we can do some simple
2305  * linedsf deductions.  This can be used for both face and dot deductions.
2306  * Returns the difficulty level of the next solver that should be used,
2307  * or DIFF_MAX if no progress was made. */
2308 static int parity_deductions(solver_state *sstate,
2309     grid_edge **edge_list, /* Edge list (from a face or a dot) */
2310     int total_parity, /* Expected number of YESs modulo 2 (either 0 or 1) */
2311     int unknown_count)
2312 {
2313     game_state *state = sstate->state;
2314     int diff = DIFF_MAX;
2315     int *linedsf = sstate->linedsf;
2316
2317     if (unknown_count == 2) {
2318         /* Lines are known alike/opposite, depending on inv. */
2319         int e[2];
2320         find_unknowns(state, edge_list, 2, e);
2321         if (merge_lines(sstate, e[0], e[1], total_parity))
2322             diff = min(diff, DIFF_HARD);
2323     } else if (unknown_count == 3) {
2324         int e[3];
2325         int can[3]; /* canonical edges */
2326         int inv[3]; /* whether can[x] is inverse to e[x] */
2327         find_unknowns(state, edge_list, 3, e);
2328         can[0] = edsf_canonify(linedsf, e[0], inv);
2329         can[1] = edsf_canonify(linedsf, e[1], inv+1);
2330         can[2] = edsf_canonify(linedsf, e[2], inv+2);
2331         if (can[0] == can[1]) {
2332             if (solver_set_line(sstate, e[2], (total_parity^inv[0]^inv[1]) ?
2333                                 LINE_YES : LINE_NO))
2334                 diff = min(diff, DIFF_EASY);
2335         }
2336         if (can[0] == can[2]) {
2337             if (solver_set_line(sstate, e[1], (total_parity^inv[0]^inv[2]) ?
2338                                 LINE_YES : LINE_NO))
2339                 diff = min(diff, DIFF_EASY);
2340         }
2341         if (can[1] == can[2]) {
2342             if (solver_set_line(sstate, e[0], (total_parity^inv[1]^inv[2]) ?
2343                                 LINE_YES : LINE_NO))
2344                 diff = min(diff, DIFF_EASY);
2345         }
2346     } else if (unknown_count == 4) {
2347         int e[4];
2348         int can[4]; /* canonical edges */
2349         int inv[4]; /* whether can[x] is inverse to e[x] */
2350         find_unknowns(state, edge_list, 4, e);
2351         can[0] = edsf_canonify(linedsf, e[0], inv);
2352         can[1] = edsf_canonify(linedsf, e[1], inv+1);
2353         can[2] = edsf_canonify(linedsf, e[2], inv+2);
2354         can[3] = edsf_canonify(linedsf, e[3], inv+3);
2355         if (can[0] == can[1]) {
2356             if (merge_lines(sstate, e[2], e[3], total_parity^inv[0]^inv[1]))
2357                 diff = min(diff, DIFF_HARD);
2358         } else if (can[0] == can[2]) {
2359             if (merge_lines(sstate, e[1], e[3], total_parity^inv[0]^inv[2]))
2360                 diff = min(diff, DIFF_HARD);
2361         } else if (can[0] == can[3]) {
2362             if (merge_lines(sstate, e[1], e[2], total_parity^inv[0]^inv[3]))
2363                 diff = min(diff, DIFF_HARD);
2364         } else if (can[1] == can[2]) {
2365             if (merge_lines(sstate, e[0], e[3], total_parity^inv[1]^inv[2]))
2366                 diff = min(diff, DIFF_HARD);
2367         } else if (can[1] == can[3]) {
2368             if (merge_lines(sstate, e[0], e[2], total_parity^inv[1]^inv[3]))
2369                 diff = min(diff, DIFF_HARD);
2370         } else if (can[2] == can[3]) {
2371             if (merge_lines(sstate, e[0], e[1], total_parity^inv[2]^inv[3]))
2372                 diff = min(diff, DIFF_HARD);
2373         }
2374     }
2375     return diff;
2376 }
2377
2378
2379 /*
2380  * These are the main solver functions.
2381  *
2382  * Their return values are diff values corresponding to the lowest mode solver
2383  * that would notice the work that they have done.  For example if the normal
2384  * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2385  * easy mode solver might be able to make progress using that.  It doesn't make
2386  * sense for one of them to return a diff value higher than that of the
2387  * function itself.
2388  *
2389  * Each function returns the lowest value it can, as early as possible, in
2390  * order to try and pass as much work as possible back to the lower level
2391  * solvers which progress more quickly.
2392  */
2393
2394 /* PROPOSED NEW DESIGN:
2395  * We have a work queue consisting of 'events' notifying us that something has
2396  * happened that a particular solver mode might be interested in.  For example
2397  * the hard mode solver might do something that helps the normal mode solver at
2398  * dot [x,y] in which case it will enqueue an event recording this fact.  Then
2399  * we pull events off the work queue, and hand each in turn to the solver that
2400  * is interested in them.  If a solver reports that it failed we pass the same
2401  * event on to progressively more advanced solvers and the loop detector.  Once
2402  * we've exhausted an event, or it has helped us progress, we drop it and
2403  * continue to the next one.  The events are sorted first in order of solver
2404  * complexity (easy first) then order of insertion (oldest first).
2405  * Once we run out of events we loop over each permitted solver in turn
2406  * (easiest first) until either a deduction is made (and an event therefore
2407  * emerges) or no further deductions can be made (in which case we've failed).
2408  *
2409  * QUESTIONS:
2410  *    * How do we 'loop over' a solver when both dots and squares are concerned.
2411  *      Answer: first all squares then all dots.
2412  */
2413
2414 static int trivial_deductions(solver_state *sstate)
2415 {
2416     int i, current_yes, current_no;
2417     game_state *state = sstate->state;
2418     grid *g = state->game_grid;
2419     int diff = DIFF_MAX;
2420
2421     /* Per-face deductions */
2422     for (i = 0; i < g->num_faces; i++) {
2423         grid_face *f = g->faces + i;
2424
2425         if (sstate->face_solved[i])
2426             continue;
2427
2428         current_yes = sstate->face_yes_count[i];
2429         current_no  = sstate->face_no_count[i];
2430
2431         if (current_yes + current_no == f->order)  {
2432             sstate->face_solved[i] = TRUE;
2433             continue;
2434         }
2435
2436         if (state->clues[i] < 0)
2437             continue;
2438
2439         /*
2440          * This code checks whether the numeric clue on a face is so
2441          * large as to permit all its remaining LINE_UNKNOWNs to be
2442          * filled in as LINE_YES, or alternatively so small as to
2443          * permit them all to be filled in as LINE_NO.
2444          */
2445
2446         if (state->clues[i] < current_yes) {
2447             sstate->solver_status = SOLVER_MISTAKE;
2448             return DIFF_EASY;
2449         }
2450         if (state->clues[i] == current_yes) {
2451             if (face_setall(sstate, i, LINE_UNKNOWN, LINE_NO))
2452                 diff = min(diff, DIFF_EASY);
2453             sstate->face_solved[i] = TRUE;
2454             continue;
2455         }
2456
2457         if (f->order - state->clues[i] < current_no) {
2458             sstate->solver_status = SOLVER_MISTAKE;
2459             return DIFF_EASY;
2460         }
2461         if (f->order - state->clues[i] == current_no) {
2462             if (face_setall(sstate, i, LINE_UNKNOWN, LINE_YES))
2463                 diff = min(diff, DIFF_EASY);
2464             sstate->face_solved[i] = TRUE;
2465             continue;
2466         }
2467
2468         if (f->order - state->clues[i] == current_no + 1 &&
2469             f->order - current_yes - current_no > 2) {
2470             /*
2471              * One small refinement to the above: we also look for any
2472              * adjacent pair of LINE_UNKNOWNs around the face with
2473              * some LINE_YES incident on it from elsewhere. If we find
2474              * one, then we know that pair of LINE_UNKNOWNs can't
2475              * _both_ be LINE_YES, and hence that pushes us one line
2476              * closer to being able to determine all the rest.
2477              */
2478             int j, k, e1, e2, e, d;
2479
2480             for (j = 0; j < f->order; j++) {
2481                 e1 = f->edges[j] - g->edges;
2482                 e2 = f->edges[j+1 < f->order ? j+1 : 0] - g->edges;
2483
2484                 if (g->edges[e1].dot1 == g->edges[e2].dot1 ||
2485                     g->edges[e1].dot1 == g->edges[e2].dot2) {
2486                     d = g->edges[e1].dot1 - g->dots;
2487                 } else {
2488                     assert(g->edges[e1].dot2 == g->edges[e2].dot1 ||
2489                            g->edges[e1].dot2 == g->edges[e2].dot2);
2490                     d = g->edges[e1].dot2 - g->dots;
2491                 }
2492
2493                 if (state->lines[e1] == LINE_UNKNOWN &&
2494                     state->lines[e2] == LINE_UNKNOWN) {
2495                     for (k = 0; k < g->dots[d].order; k++) {
2496                         int e = g->dots[d].edges[k] - g->edges;
2497                         if (state->lines[e] == LINE_YES)
2498                             goto found;    /* multi-level break */
2499                     }
2500                 }
2501             }
2502             continue;
2503
2504           found:
2505             /*
2506              * If we get here, we've found such a pair of edges, and
2507              * they're e1 and e2.
2508              */
2509             for (j = 0; j < f->order; j++) {
2510                 e = f->edges[j] - g->edges;
2511                 if (state->lines[e] == LINE_UNKNOWN && e != e1 && e != e2) {
2512                     int r = solver_set_line(sstate, e, LINE_YES);
2513                     assert(r);
2514                     diff = min(diff, DIFF_EASY);
2515                 }
2516             }
2517         }
2518     }
2519
2520     check_caches(sstate);
2521
2522     /* Per-dot deductions */
2523     for (i = 0; i < g->num_dots; i++) {
2524         grid_dot *d = g->dots + i;
2525         int yes, no, unknown;
2526
2527         if (sstate->dot_solved[i])
2528             continue;
2529
2530         yes = sstate->dot_yes_count[i];
2531         no = sstate->dot_no_count[i];
2532         unknown = d->order - yes - no;
2533
2534         if (yes == 0) {
2535             if (unknown == 0) {
2536                 sstate->dot_solved[i] = TRUE;
2537             } else if (unknown == 1) {
2538                 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2539                 diff = min(diff, DIFF_EASY);
2540                 sstate->dot_solved[i] = TRUE;
2541             }
2542         } else if (yes == 1) {
2543             if (unknown == 0) {
2544                 sstate->solver_status = SOLVER_MISTAKE;
2545                 return DIFF_EASY;
2546             } else if (unknown == 1) {
2547                 dot_setall(sstate, i, LINE_UNKNOWN, LINE_YES);
2548                 diff = min(diff, DIFF_EASY);
2549             }
2550         } else if (yes == 2) {
2551             if (unknown > 0) {
2552                 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2553                 diff = min(diff, DIFF_EASY);
2554             }
2555             sstate->dot_solved[i] = TRUE;
2556         } else {
2557             sstate->solver_status = SOLVER_MISTAKE;
2558             return DIFF_EASY;
2559         }
2560     }
2561
2562     check_caches(sstate);
2563
2564     return diff;
2565 }
2566
2567 static int dline_deductions(solver_state *sstate)
2568 {
2569     game_state *state = sstate->state;
2570     grid *g = state->game_grid;
2571     char *dlines = sstate->dlines;
2572     int i;
2573     int diff = DIFF_MAX;
2574
2575     /* ------ Face deductions ------ */
2576
2577     /* Given a set of dline atmostone/atleastone constraints, need to figure
2578      * out if we can deduce any further info.  For more general faces than
2579      * squares, this turns out to be a tricky problem.
2580      * The approach taken here is to define (per face) NxN matrices:
2581      * "maxs" and "mins".
2582      * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2583      * for the possible number of edges that are YES between positions j and k
2584      * going clockwise around the face.  Can think of j and k as marking dots
2585      * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2586      * edge1 joins dot1 to dot2 etc).
2587      * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2588      * these.  mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2589      * is YES, NO or UNKNOWN.  mins(j,j+2) and maxs(j,j+2) are related to
2590      * the dline atmostone/atleastone status for edges j and j+1.
2591      *
2592      * Then we calculate the remaining entries recursively.  We definitely
2593      * know that
2594      * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2595      * This is because any valid placement of YESs between j and k must give
2596      * a valid placement between j and u, and also between u and k.
2597      * I believe it's sufficient to use just the two values of u:
2598      * j+1 and j+2.  Seems to work well in practice - the bounds we compute
2599      * are rigorous, even if they might not be best-possible.
2600      *
2601      * Once we have maxs and mins calculated, we can make inferences about
2602      * each dline{j,j+1} by looking at the possible complementary edge-counts
2603      * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2604      * As well as dlines, we can make similar inferences about single edges.
2605      * For example, consider a pentagon with clue 3, and we know at most one
2606      * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2607      * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2608      * that final edge would have to be YES to make the count up to 3.
2609      */
2610
2611     /* Much quicker to allocate arrays on the stack than the heap, so
2612      * define the largest possible face size, and base our array allocations
2613      * on that.  We check this with an assertion, in case someone decides to
2614      * make a grid which has larger faces than this.  Note, this algorithm
2615      * could get quite expensive if there are many large faces. */
2616 #define MAX_FACE_SIZE 12
2617
2618     for (i = 0; i < g->num_faces; i++) {
2619         int maxs[MAX_FACE_SIZE][MAX_FACE_SIZE];
2620         int mins[MAX_FACE_SIZE][MAX_FACE_SIZE];
2621         grid_face *f = g->faces + i;
2622         int N = f->order;
2623         int j,m;
2624         int clue = state->clues[i];
2625         assert(N <= MAX_FACE_SIZE);
2626         if (sstate->face_solved[i])
2627             continue;
2628         if (clue < 0) continue;
2629
2630         /* Calculate the (j,j+1) entries */
2631         for (j = 0; j < N; j++) {
2632             int edge_index = f->edges[j] - g->edges;
2633             int dline_index;
2634             enum line_state line1 = state->lines[edge_index];
2635             enum line_state line2;
2636             int tmp;
2637             int k = j + 1;
2638             if (k >= N) k = 0;
2639             maxs[j][k] = (line1 == LINE_NO) ? 0 : 1;
2640             mins[j][k] = (line1 == LINE_YES) ? 1 : 0;
2641             /* Calculate the (j,j+2) entries */
2642             dline_index = dline_index_from_face(g, f, k);
2643             edge_index = f->edges[k] - g->edges;
2644             line2 = state->lines[edge_index];
2645             k++;
2646             if (k >= N) k = 0;
2647
2648             /* max */
2649             tmp = 2;
2650             if (line1 == LINE_NO) tmp--;
2651             if (line2 == LINE_NO) tmp--;
2652             if (tmp == 2 && is_atmostone(dlines, dline_index))
2653                 tmp = 1;
2654             maxs[j][k] = tmp;
2655
2656             /* min */
2657             tmp = 0;
2658             if (line1 == LINE_YES) tmp++;
2659             if (line2 == LINE_YES) tmp++;
2660             if (tmp == 0 && is_atleastone(dlines, dline_index))
2661                 tmp = 1;
2662             mins[j][k] = tmp;
2663         }
2664
2665         /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2666         for (m = 3; m < N; m++) {
2667             for (j = 0; j < N; j++) {
2668                 int k = j + m;
2669                 int u = j + 1;
2670                 int v = j + 2;
2671                 int tmp;
2672                 if (k >= N) k -= N;
2673                 if (u >= N) u -= N;
2674                 if (v >= N) v -= N;
2675                 maxs[j][k] = maxs[j][u] + maxs[u][k];
2676                 mins[j][k] = mins[j][u] + mins[u][k];
2677                 tmp = maxs[j][v] + maxs[v][k];
2678                 maxs[j][k] = min(maxs[j][k], tmp);
2679                 tmp = mins[j][v] + mins[v][k];
2680                 mins[j][k] = max(mins[j][k], tmp);
2681             }
2682         }
2683
2684         /* See if we can make any deductions */
2685         for (j = 0; j < N; j++) {
2686             int k;
2687             grid_edge *e = f->edges[j];
2688             int line_index = e - g->edges;
2689             int dline_index;
2690
2691             if (state->lines[line_index] != LINE_UNKNOWN)
2692                 continue;
2693             k = j + 1;
2694             if (k >= N) k = 0;
2695
2696             /* minimum YESs in the complement of this edge */
2697             if (mins[k][j] > clue) {
2698                 sstate->solver_status = SOLVER_MISTAKE;
2699                 return DIFF_EASY;
2700             }
2701             if (mins[k][j] == clue) {
2702                 /* setting this edge to YES would make at least
2703                  * (clue+1) edges - contradiction */
2704                 solver_set_line(sstate, line_index, LINE_NO);
2705                 diff = min(diff, DIFF_EASY);
2706             }
2707             if (maxs[k][j] < clue - 1) {
2708                 sstate->solver_status = SOLVER_MISTAKE;
2709                 return DIFF_EASY;
2710             }
2711             if (maxs[k][j] == clue - 1) {
2712                 /* Only way to satisfy the clue is to set edge{j} as YES */
2713                 solver_set_line(sstate, line_index, LINE_YES);
2714                 diff = min(diff, DIFF_EASY);
2715             }
2716
2717             /* More advanced deduction that allows propagation along diagonal
2718              * chains of faces connected by dots, for example, 3-2-...-2-3
2719              * in square grids. */
2720             if (sstate->diff >= DIFF_TRICKY) {
2721                 /* Now see if we can make dline deduction for edges{j,j+1} */
2722                 e = f->edges[k];
2723                 if (state->lines[e - g->edges] != LINE_UNKNOWN)
2724                     /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2725                      * Dlines where one of the edges is known, are handled in the
2726                      * dot-deductions */
2727                     continue;
2728     
2729                 dline_index = dline_index_from_face(g, f, k);
2730                 k++;
2731                 if (k >= N) k = 0;
2732     
2733                 /* minimum YESs in the complement of this dline */
2734                 if (mins[k][j] > clue - 2) {
2735                     /* Adding 2 YESs would break the clue */
2736                     if (set_atmostone(dlines, dline_index))
2737                         diff = min(diff, DIFF_NORMAL);
2738                 }
2739                 /* maximum YESs in the complement of this dline */
2740                 if (maxs[k][j] < clue) {
2741                     /* Adding 2 NOs would mean not enough YESs */
2742                     if (set_atleastone(dlines, dline_index))
2743                         diff = min(diff, DIFF_NORMAL);
2744                 }
2745             }
2746         }
2747     }
2748
2749     if (diff < DIFF_NORMAL)
2750         return diff;
2751
2752     /* ------ Dot deductions ------ */
2753
2754     for (i = 0; i < g->num_dots; i++) {
2755         grid_dot *d = g->dots + i;
2756         int N = d->order;
2757         int yes, no, unknown;
2758         int j;
2759         if (sstate->dot_solved[i])
2760             continue;
2761         yes = sstate->dot_yes_count[i];
2762         no = sstate->dot_no_count[i];
2763         unknown = N - yes - no;
2764
2765         for (j = 0; j < N; j++) {
2766             int k;
2767             int dline_index;
2768             int line1_index, line2_index;
2769             enum line_state line1, line2;
2770             k = j + 1;
2771             if (k >= N) k = 0;
2772             dline_index = dline_index_from_dot(g, d, j);
2773             line1_index = d->edges[j] - g->edges;
2774             line2_index = d->edges[k] - g->edges;
2775             line1 = state->lines[line1_index];
2776             line2 = state->lines[line2_index];
2777
2778             /* Infer dline state from line state */
2779             if (line1 == LINE_NO || line2 == LINE_NO) {
2780                 if (set_atmostone(dlines, dline_index))
2781                     diff = min(diff, DIFF_NORMAL);
2782             }
2783             if (line1 == LINE_YES || line2 == LINE_YES) {
2784                 if (set_atleastone(dlines, dline_index))
2785                     diff = min(diff, DIFF_NORMAL);
2786             }
2787             /* Infer line state from dline state */
2788             if (is_atmostone(dlines, dline_index)) {
2789                 if (line1 == LINE_YES && line2 == LINE_UNKNOWN) {
2790                     solver_set_line(sstate, line2_index, LINE_NO);
2791                     diff = min(diff, DIFF_EASY);
2792                 }
2793                 if (line2 == LINE_YES && line1 == LINE_UNKNOWN) {
2794                     solver_set_line(sstate, line1_index, LINE_NO);
2795                     diff = min(diff, DIFF_EASY);
2796                 }
2797             }
2798             if (is_atleastone(dlines, dline_index)) {
2799                 if (line1 == LINE_NO && line2 == LINE_UNKNOWN) {
2800                     solver_set_line(sstate, line2_index, LINE_YES);
2801                     diff = min(diff, DIFF_EASY);
2802                 }
2803                 if (line2 == LINE_NO && line1 == LINE_UNKNOWN) {
2804                     solver_set_line(sstate, line1_index, LINE_YES);
2805                     diff = min(diff, DIFF_EASY);
2806                 }
2807             }
2808             /* Deductions that depend on the numbers of lines.
2809              * Only bother if both lines are UNKNOWN, otherwise the
2810              * easy-mode solver (or deductions above) would have taken
2811              * care of it. */
2812             if (line1 != LINE_UNKNOWN || line2 != LINE_UNKNOWN)
2813                 continue;
2814
2815             if (yes == 0 && unknown == 2) {
2816                 /* Both these unknowns must be identical.  If we know
2817                  * atmostone or atleastone, we can make progress. */
2818                 if (is_atmostone(dlines, dline_index)) {
2819                     solver_set_line(sstate, line1_index, LINE_NO);
2820                     solver_set_line(sstate, line2_index, LINE_NO);
2821                     diff = min(diff, DIFF_EASY);
2822                 }
2823                 if (is_atleastone(dlines, dline_index)) {
2824                     solver_set_line(sstate, line1_index, LINE_YES);
2825                     solver_set_line(sstate, line2_index, LINE_YES);
2826                     diff = min(diff, DIFF_EASY);
2827                 }
2828             }
2829             if (yes == 1) {
2830                 if (set_atmostone(dlines, dline_index))
2831                     diff = min(diff, DIFF_NORMAL);
2832                 if (unknown == 2) {
2833                     if (set_atleastone(dlines, dline_index))
2834                         diff = min(diff, DIFF_NORMAL);
2835                 }
2836             }
2837
2838             /* More advanced deduction that allows propagation along diagonal
2839              * chains of faces connected by dots, for example: 3-2-...-2-3
2840              * in square grids. */
2841             if (sstate->diff >= DIFF_TRICKY) {
2842                 /* If we have atleastone set for this dline, infer
2843                  * atmostone for each "opposite" dline (that is, each
2844                  * dline without edges in common with this one).
2845                  * Again, this test is only worth doing if both these
2846                  * lines are UNKNOWN.  For if one of these lines were YES,
2847                  * the (yes == 1) test above would kick in instead. */
2848                 if (is_atleastone(dlines, dline_index)) {
2849                     int opp;
2850                     for (opp = 0; opp < N; opp++) {
2851                         int opp_dline_index;
2852                         if (opp == j || opp == j+1 || opp == j-1)
2853                             continue;
2854                         if (j == 0 && opp == N-1)
2855                             continue;
2856                         if (j == N-1 && opp == 0)
2857                             continue;
2858                         opp_dline_index = dline_index_from_dot(g, d, opp);
2859                         if (set_atmostone(dlines, opp_dline_index))
2860                             diff = min(diff, DIFF_NORMAL);
2861                     }
2862                     if (yes == 0 && is_atmostone(dlines, dline_index)) {
2863                         /* This dline has *exactly* one YES and there are no
2864                          * other YESs.  This allows more deductions. */
2865                         if (unknown == 3) {
2866                             /* Third unknown must be YES */
2867                             for (opp = 0; opp < N; opp++) {
2868                                 int opp_index;
2869                                 if (opp == j || opp == k)
2870                                     continue;
2871                                 opp_index = d->edges[opp] - g->edges;
2872                                 if (state->lines[opp_index] == LINE_UNKNOWN) {
2873                                     solver_set_line(sstate, opp_index,
2874                                                     LINE_YES);
2875                                     diff = min(diff, DIFF_EASY);
2876                                 }
2877                             }
2878                         } else if (unknown == 4) {
2879                             /* Exactly one of opposite UNKNOWNS is YES.  We've
2880                              * already set atmostone, so set atleastone as
2881                              * well.
2882                              */
2883                             if (dline_set_opp_atleastone(sstate, d, j))
2884                                 diff = min(diff, DIFF_NORMAL);
2885                         }
2886                     }
2887                 }
2888             }
2889         }
2890     }
2891     return diff;
2892 }
2893
2894 static int linedsf_deductions(solver_state *sstate)
2895 {
2896     game_state *state = sstate->state;
2897     grid *g = state->game_grid;
2898     char *dlines = sstate->dlines;
2899     int i;
2900     int diff = DIFF_MAX;
2901     int diff_tmp;
2902
2903     /* ------ Face deductions ------ */
2904
2905     /* A fully-general linedsf deduction seems overly complicated
2906      * (I suspect the problem is NP-complete, though in practice it might just
2907      * be doable because faces are limited in size).
2908      * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2909      * known to be identical.  If setting them both to YES (or NO) would break
2910      * the clue, set them to NO (or YES). */
2911
2912     for (i = 0; i < g->num_faces; i++) {
2913         int N, yes, no, unknown;
2914         int clue;
2915
2916         if (sstate->face_solved[i])
2917             continue;
2918         clue = state->clues[i];
2919         if (clue < 0)
2920             continue;
2921
2922         N = g->faces[i].order;
2923         yes = sstate->face_yes_count[i];
2924         if (yes + 1 == clue) {
2925             if (face_setall_identical(sstate, i, LINE_NO))
2926                 diff = min(diff, DIFF_EASY);
2927         }
2928         no = sstate->face_no_count[i];
2929         if (no + 1 == N - clue) {
2930             if (face_setall_identical(sstate, i, LINE_YES))
2931                 diff = min(diff, DIFF_EASY);
2932         }
2933
2934         /* Reload YES count, it might have changed */
2935         yes = sstate->face_yes_count[i];
2936         unknown = N - no - yes;
2937
2938         /* Deductions with small number of LINE_UNKNOWNs, based on overall
2939          * parity of lines. */
2940         diff_tmp = parity_deductions(sstate, g->faces[i].edges,
2941                                      (clue - yes) % 2, unknown);
2942         diff = min(diff, diff_tmp);
2943     }
2944
2945     /* ------ Dot deductions ------ */
2946     for (i = 0; i < g->num_dots; i++) {
2947         grid_dot *d = g->dots + i;
2948         int N = d->order;
2949         int j;
2950         int yes, no, unknown;
2951         /* Go through dlines, and do any dline<->linedsf deductions wherever
2952          * we find two UNKNOWNS. */
2953         for (j = 0; j < N; j++) {
2954             int dline_index = dline_index_from_dot(g, d, j);
2955             int line1_index;
2956             int line2_index;
2957             int can1, can2, inv1, inv2;
2958             int j2;
2959             line1_index = d->edges[j] - g->edges;
2960             if (state->lines[line1_index] != LINE_UNKNOWN)
2961                 continue;
2962             j2 = j + 1;
2963             if (j2 == N) j2 = 0;
2964             line2_index = d->edges[j2] - g->edges;
2965             if (state->lines[line2_index] != LINE_UNKNOWN)
2966                 continue;
2967             /* Infer dline flags from linedsf */
2968             can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
2969             can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
2970             if (can1 == can2 && inv1 != inv2) {
2971                 /* These are opposites, so set dline atmostone/atleastone */
2972                 if (set_atmostone(dlines, dline_index))
2973                     diff = min(diff, DIFF_NORMAL);
2974                 if (set_atleastone(dlines, dline_index))
2975                     diff = min(diff, DIFF_NORMAL);
2976                 continue;
2977             }
2978             /* Infer linedsf from dline flags */
2979             if (is_atmostone(dlines, dline_index)
2980                 && is_atleastone(dlines, dline_index)) {
2981                 if (merge_lines(sstate, line1_index, line2_index, 1))
2982                     diff = min(diff, DIFF_HARD);
2983             }
2984         }
2985
2986         /* Deductions with small number of LINE_UNKNOWNs, based on overall
2987          * parity of lines. */
2988         yes = sstate->dot_yes_count[i];
2989         no = sstate->dot_no_count[i];
2990         unknown = N - yes - no;
2991         diff_tmp = parity_deductions(sstate, d->edges,
2992                                      yes % 2, unknown);
2993         diff = min(diff, diff_tmp);
2994     }
2995
2996     /* ------ Edge dsf deductions ------ */
2997
2998     /* If the state of a line is known, deduce the state of its canonical line
2999      * too, and vice versa. */
3000     for (i = 0; i < g->num_edges; i++) {
3001         int can, inv;
3002         enum line_state s;
3003         can = edsf_canonify(sstate->linedsf, i, &inv);
3004         if (can == i)
3005             continue;
3006         s = sstate->state->lines[can];
3007         if (s != LINE_UNKNOWN) {
3008             if (solver_set_line(sstate, i, inv ? OPP(s) : s))
3009                 diff = min(diff, DIFF_EASY);
3010         } else {
3011             s = sstate->state->lines[i];
3012             if (s != LINE_UNKNOWN) {
3013                 if (solver_set_line(sstate, can, inv ? OPP(s) : s))
3014                     diff = min(diff, DIFF_EASY);
3015             }
3016         }
3017     }
3018
3019     return diff;
3020 }
3021
3022 static int loop_deductions(solver_state *sstate)
3023 {
3024     int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
3025     game_state *state = sstate->state;
3026     grid *g = state->game_grid;
3027     int shortest_chainlen = g->num_dots;
3028     int loop_found = FALSE;
3029     int dots_connected;
3030     int progress = FALSE;
3031     int i;
3032
3033     /*
3034      * Go through the grid and update for all the new edges.
3035      * Since merge_dots() is idempotent, the simplest way to
3036      * do this is just to update for _all_ the edges.
3037      * Also, while we're here, we count the edges.
3038      */
3039     for (i = 0; i < g->num_edges; i++) {
3040         if (state->lines[i] == LINE_YES) {
3041             loop_found |= merge_dots(sstate, i);
3042             edgecount++;
3043         }
3044     }
3045
3046     /*
3047      * Count the clues, count the satisfied clues, and count the
3048      * satisfied-minus-one clues.
3049      */
3050     for (i = 0; i < g->num_faces; i++) {
3051         int c = state->clues[i];
3052         if (c >= 0) {
3053             int o = sstate->face_yes_count[i];
3054             if (o == c)
3055                 satclues++;
3056             else if (o == c-1)
3057                 sm1clues++;
3058             clues++;
3059         }
3060     }
3061
3062     for (i = 0; i < g->num_dots; ++i) {
3063         dots_connected =
3064             sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
3065         if (dots_connected > 1)
3066             shortest_chainlen = min(shortest_chainlen, dots_connected);
3067     }
3068
3069     assert(sstate->solver_status == SOLVER_INCOMPLETE);
3070
3071     if (satclues == clues && shortest_chainlen == edgecount) {
3072         sstate->solver_status = SOLVER_SOLVED;
3073         /* This discovery clearly counts as progress, even if we haven't
3074          * just added any lines or anything */
3075         progress = TRUE;
3076         goto finished_loop_deductionsing;
3077     }
3078
3079     /*
3080      * Now go through looking for LINE_UNKNOWN edges which
3081      * connect two dots that are already in the same
3082      * equivalence class. If we find one, test to see if the
3083      * loop it would create is a solution.
3084      */
3085     for (i = 0; i < g->num_edges; i++) {
3086         grid_edge *e = g->edges + i;
3087         int d1 = e->dot1 - g->dots;
3088         int d2 = e->dot2 - g->dots;
3089         int eqclass, val;
3090         if (state->lines[i] != LINE_UNKNOWN)
3091             continue;
3092
3093         eqclass = dsf_canonify(sstate->dotdsf, d1);
3094         if (eqclass != dsf_canonify(sstate->dotdsf, d2))
3095             continue;
3096
3097         val = LINE_NO;  /* loop is bad until proven otherwise */
3098
3099         /*
3100          * This edge would form a loop. Next
3101          * question: how long would the loop be?
3102          * Would it equal the total number of edges
3103          * (plus the one we'd be adding if we added
3104          * it)?
3105          */
3106         if (sstate->looplen[eqclass] == edgecount + 1) {
3107             int sm1_nearby;
3108
3109             /*
3110              * This edge would form a loop which
3111              * took in all the edges in the entire
3112              * grid. So now we need to work out
3113              * whether it would be a valid solution
3114              * to the puzzle, which means we have to
3115              * check if it satisfies all the clues.
3116              * This means that every clue must be
3117              * either satisfied or satisfied-minus-
3118              * 1, and also that the number of
3119              * satisfied-minus-1 clues must be at
3120              * most two and they must lie on either
3121              * side of this edge.
3122              */
3123             sm1_nearby = 0;
3124             if (e->face1) {
3125                 int f = e->face1 - g->faces;
3126                 int c = state->clues[f];
3127                 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
3128                     sm1_nearby++;
3129             }
3130             if (e->face2) {
3131                 int f = e->face2 - g->faces;
3132                 int c = state->clues[f];
3133                 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
3134                     sm1_nearby++;
3135             }
3136             if (sm1clues == sm1_nearby &&
3137                 sm1clues + satclues == clues) {
3138                 val = LINE_YES;  /* loop is good! */
3139             }
3140         }
3141
3142         /*
3143          * Right. Now we know that adding this edge
3144          * would form a loop, and we know whether
3145          * that loop would be a viable solution or
3146          * not.
3147          *
3148          * If adding this edge produces a solution,
3149          * then we know we've found _a_ solution but
3150          * we don't know that it's _the_ solution -
3151          * if it were provably the solution then
3152          * we'd have deduced this edge some time ago
3153          * without the need to do loop detection. So
3154          * in this state we return SOLVER_AMBIGUOUS,
3155          * which has the effect that hitting Solve
3156          * on a user-provided puzzle will fill in a
3157          * solution but using the solver to
3158          * construct new puzzles won't consider this
3159          * a reasonable deduction for the user to
3160          * make.
3161          */
3162         progress = solver_set_line(sstate, i, val);
3163         assert(progress == TRUE);
3164         if (val == LINE_YES) {
3165             sstate->solver_status = SOLVER_AMBIGUOUS;
3166             goto finished_loop_deductionsing;
3167         }
3168     }
3169
3170     finished_loop_deductionsing:
3171     return progress ? DIFF_EASY : DIFF_MAX;
3172 }
3173
3174 /* This will return a dynamically allocated solver_state containing the (more)
3175  * solved grid */
3176 static solver_state *solve_game_rec(const solver_state *sstate_start)
3177 {
3178     solver_state *sstate;
3179
3180     /* Index of the solver we should call next. */
3181     int i = 0;
3182     
3183     /* As a speed-optimisation, we avoid re-running solvers that we know
3184      * won't make any progress.  This happens when a high-difficulty
3185      * solver makes a deduction that can only help other high-difficulty
3186      * solvers.
3187      * For example: if a new 'dline' flag is set by dline_deductions, the
3188      * trivial_deductions solver cannot do anything with this information.
3189      * If we've already run the trivial_deductions solver (because it's
3190      * earlier in the list), there's no point running it again.
3191      *
3192      * Therefore: if a solver is earlier in the list than "threshold_index",
3193      * we don't bother running it if it's difficulty level is less than
3194      * "threshold_diff".
3195      */
3196     int threshold_diff = 0;
3197     int threshold_index = 0;
3198     
3199     sstate = dup_solver_state(sstate_start);
3200
3201     check_caches(sstate);
3202
3203     while (i < NUM_SOLVERS) {
3204         if (sstate->solver_status == SOLVER_MISTAKE)
3205             return sstate;
3206         if (sstate->solver_status == SOLVER_SOLVED ||
3207             sstate->solver_status == SOLVER_AMBIGUOUS) {
3208             /* solver finished */
3209             break;
3210         }
3211
3212         if ((solver_diffs[i] >= threshold_diff || i >= threshold_index)
3213             && solver_diffs[i] <= sstate->diff) {
3214             /* current_solver is eligible, so use it */
3215             int next_diff = solver_fns[i](sstate);
3216             if (next_diff != DIFF_MAX) {
3217                 /* solver made progress, so use new thresholds and
3218                 * start again at top of list. */
3219                 threshold_diff = next_diff;
3220                 threshold_index = i;
3221                 i = 0;
3222                 continue;
3223             }
3224         }
3225         /* current_solver is ineligible, or failed to make progress, so
3226          * go to the next solver in the list */
3227         i++;
3228     }
3229
3230     if (sstate->solver_status == SOLVER_SOLVED ||
3231         sstate->solver_status == SOLVER_AMBIGUOUS) {
3232         /* s/LINE_UNKNOWN/LINE_NO/g */
3233         array_setall(sstate->state->lines, LINE_UNKNOWN, LINE_NO,
3234                      sstate->state->game_grid->num_edges);
3235         return sstate;
3236     }
3237
3238     return sstate;
3239 }
3240
3241 static char *solve_game(game_state *state, game_state *currstate,
3242                         char *aux, char **error)
3243 {
3244     char *soln = NULL;
3245     solver_state *sstate, *new_sstate;
3246
3247     sstate = new_solver_state(state, DIFF_MAX);
3248     new_sstate = solve_game_rec(sstate);
3249
3250     if (new_sstate->solver_status == SOLVER_SOLVED) {
3251         soln = encode_solve_move(new_sstate->state);
3252     } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
3253         soln = encode_solve_move(new_sstate->state);
3254         /**error = "Solver found ambiguous solutions"; */
3255     } else {
3256         soln = encode_solve_move(new_sstate->state);
3257         /**error = "Solver failed"; */
3258     }
3259
3260     free_solver_state(new_sstate);
3261     free_solver_state(sstate);
3262
3263     return soln;
3264 }
3265
3266 /* ----------------------------------------------------------------------
3267  * Drawing and mouse-handling
3268  */
3269
3270 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3271                             int x, int y, int button)
3272 {
3273     grid *g = state->game_grid;
3274     grid_edge *e;
3275     int i;
3276     char *ret, buf[80];
3277     char button_char = ' ';
3278     enum line_state old_state;
3279
3280     button &= ~MOD_MASK;
3281
3282     /* Convert mouse-click (x,y) to grid coordinates */
3283     x -= BORDER(ds->tilesize);
3284     y -= BORDER(ds->tilesize);
3285     x = x * g->tilesize / ds->tilesize;
3286     y = y * g->tilesize / ds->tilesize;
3287     x += g->lowest_x;
3288     y += g->lowest_y;
3289
3290     e = grid_nearest_edge(g, x, y);
3291     if (e == NULL)
3292         return NULL;
3293
3294     i = e - g->edges;
3295
3296     /* I think it's only possible to play this game with mouse clicks, sorry */
3297     /* Maybe will add mouse drag support some time */
3298     old_state = state->lines[i];
3299
3300     switch (button) {
3301       case LEFT_BUTTON:
3302         switch (old_state) {
3303           case LINE_UNKNOWN:
3304             button_char = 'y';
3305             break;
3306           case LINE_YES:
3307 #ifdef STYLUS_BASED
3308             button_char = 'n';
3309             break;
3310 #endif
3311           case LINE_NO:
3312             button_char = 'u';
3313             break;
3314         }
3315         break;
3316       case MIDDLE_BUTTON:
3317         button_char = 'u';
3318         break;
3319       case RIGHT_BUTTON:
3320         switch (old_state) {
3321           case LINE_UNKNOWN:
3322             button_char = 'n';
3323             break;
3324           case LINE_NO:
3325 #ifdef STYLUS_BASED
3326             button_char = 'y';
3327             break;
3328 #endif
3329           case LINE_YES:
3330             button_char = 'u';
3331             break;
3332         }
3333         break;
3334       default:
3335         return NULL;
3336     }
3337
3338
3339     sprintf(buf, "%d%c", i, (int)button_char);
3340     ret = dupstr(buf);
3341
3342     return ret;
3343 }
3344
3345 static game_state *execute_move(game_state *state, char *move)
3346 {
3347     int i;
3348     game_state *newstate = dup_game(state);
3349
3350     if (move[0] == 'S') {
3351         move++;
3352         newstate->cheated = TRUE;
3353     }
3354
3355     while (*move) {
3356         i = atoi(move);
3357         if (i < 0 || i >= newstate->game_grid->num_edges)
3358             goto fail;
3359         move += strspn(move, "1234567890");
3360         switch (*(move++)) {
3361           case 'y':
3362             newstate->lines[i] = LINE_YES;
3363             break;
3364           case 'n':
3365             newstate->lines[i] = LINE_NO;
3366             break;
3367           case 'u':
3368             newstate->lines[i] = LINE_UNKNOWN;
3369             break;
3370           default:
3371             goto fail;
3372         }
3373     }
3374
3375     /*
3376      * Check for completion.
3377      */
3378     if (check_completion(newstate))
3379         newstate->solved = TRUE;
3380
3381     return newstate;
3382
3383     fail:
3384     free_game(newstate);
3385     return NULL;
3386 }
3387
3388 /* ----------------------------------------------------------------------
3389  * Drawing routines.
3390  */
3391
3392 /* Convert from grid coordinates to screen coordinates */
3393 static void grid_to_screen(const game_drawstate *ds, const grid *g,
3394                            int grid_x, int grid_y, int *x, int *y)
3395 {
3396     *x = grid_x - g->lowest_x;
3397     *y = grid_y - g->lowest_y;
3398     *x = *x * ds->tilesize / g->tilesize;
3399     *y = *y * ds->tilesize / g->tilesize;
3400     *x += BORDER(ds->tilesize);
3401     *y += BORDER(ds->tilesize);
3402 }
3403
3404 static int solve_2x2_matrix(double mx[4], double vin[2], double vout[2])
3405 {
3406     double inv[4];
3407     double det;
3408     det = (mx[0]*mx[3] - mx[1]*mx[2]);
3409     if (det == 0)
3410         return FALSE;
3411
3412     inv[0] = mx[3] / det;
3413     inv[1] = -mx[1] / det;
3414     inv[2] = -mx[2] / det;
3415     inv[3] = mx[0] / det;
3416
3417     vout[0] = inv[0]*vin[0] + inv[1]*vin[1];
3418     vout[1] = inv[2]*vin[0] + inv[3]*vin[1];
3419
3420     return TRUE;
3421 }
3422
3423 static int solve_3x3_matrix(double mx[9], double vin[3], double vout[3])
3424 {
3425     double inv[9];
3426     double det;
3427
3428     det = (mx[0]*mx[4]*mx[8] + mx[1]*mx[5]*mx[6] + mx[2]*mx[3]*mx[7] -
3429            mx[0]*mx[5]*mx[7] - mx[1]*mx[3]*mx[8] - mx[2]*mx[4]*mx[6]);
3430     if (det == 0)
3431         return FALSE;
3432
3433     inv[0] = (mx[4]*mx[8] - mx[5]*mx[7]) / det;
3434     inv[1] = (mx[2]*mx[7] - mx[1]*mx[8]) / det;
3435     inv[2] = (mx[1]*mx[5] - mx[2]*mx[4]) / det;
3436     inv[3] = (mx[5]*mx[6] - mx[3]*mx[8]) / det;
3437     inv[4] = (mx[0]*mx[8] - mx[2]*mx[6]) / det;
3438     inv[5] = (mx[2]*mx[3] - mx[0]*mx[5]) / det;
3439     inv[6] = (mx[3]*mx[7] - mx[4]*mx[6]) / det;
3440     inv[7] = (mx[1]*mx[6] - mx[0]*mx[7]) / det;
3441     inv[8] = (mx[0]*mx[4] - mx[1]*mx[3]) / det;
3442
3443     vout[0] = inv[0]*vin[0] + inv[1]*vin[1] + inv[2]*vin[2];
3444     vout[1] = inv[3]*vin[0] + inv[4]*vin[1] + inv[5]*vin[2];
3445     vout[2] = inv[6]*vin[0] + inv[7]*vin[1] + inv[8]*vin[2];
3446
3447     return TRUE;
3448 }
3449
3450 /* Returns (into x,y) position of centre of face for rendering the text clue.
3451  */
3452 static void face_text_pos(const game_drawstate *ds, const grid *g,
3453                           const grid_face *f, int *xret, int *yret)
3454 {
3455     double xbest, ybest, bestdist;
3456     int i, j, k, m;
3457     grid_dot *edgedot1[3], *edgedot2[3];
3458     grid_dot *dots[3];
3459     int nedges, ndots;
3460     int faceindex = f - g->faces;
3461
3462     /*
3463      * Return the cached position for this face, if we've already
3464      * worked it out.
3465      */
3466     if (ds->textx[faceindex] >= 0) {
3467         *xret = ds->textx[faceindex];
3468         *yret = ds->texty[faceindex];
3469         return;
3470     }
3471
3472     /*
3473      * Otherwise, try to find the point in the polygon with the
3474      * maximum distance to any edge or corner.
3475      *
3476      * This point must be in contact with at least three edges and/or
3477      * vertices; so we iterate through all combinations of three of
3478      * those, and find candidate points in each set.
3479      *
3480      * We don't actually iterate literally over _edges_, in the sense
3481      * of grid_edge structures. Instead, we fill in edgedot1[] and
3482      * edgedot2[] with a pair of dots adjacent in the face's list of
3483      * vertices. This ensures that we get the edges in consistent
3484      * orientation, which we could not do from the grid structure
3485      * alone. (A moment's consideration of an order-3 vertex should
3486      * make it clear that if a notional arrow was written on each
3487      * edge, _at least one_ of the three faces bordering that vertex
3488      * would have to have the two arrows tip-to-tip or tail-to-tail
3489      * rather than tip-to-tail.)
3490      */
3491     nedges = ndots = 0;
3492     bestdist = 0;
3493     xbest = ybest = 0;
3494
3495     for (i = 0; i+2 < 2*f->order; i++) {
3496         if (i < f->order) {
3497             edgedot1[nedges] = f->dots[i];
3498             edgedot2[nedges++] = f->dots[(i+1)%f->order];
3499         } else
3500             dots[ndots++] = f->dots[i - f->order];
3501
3502         for (j = i+1; j+1 < 2*f->order; j++) {
3503             if (j < f->order) {
3504                 edgedot1[nedges] = f->dots[j];
3505                 edgedot2[nedges++] = f->dots[(j+1)%f->order];
3506             } else
3507                 dots[ndots++] = f->dots[j - f->order];
3508
3509             for (k = j+1; k < 2*f->order; k++) {
3510                 double cx[2], cy[2];   /* candidate positions */
3511                 int cn = 0;            /* number of candidates */
3512
3513                 if (k < f->order) {
3514                     edgedot1[nedges] = f->dots[k];
3515                     edgedot2[nedges++] = f->dots[(k+1)%f->order];
3516                 } else
3517                     dots[ndots++] = f->dots[k - f->order];
3518
3519                 /*
3520                  * Find a point, or pair of points, equidistant from
3521                  * all the specified edges and/or vertices.
3522                  */
3523                 if (nedges == 3) {
3524                     /*
3525                      * Three edges. This is a linear matrix equation:
3526                      * each row of the matrix represents the fact that
3527                      * the point (x,y) we seek is at distance r from
3528                      * that edge, and we solve three of those
3529                      * simultaneously to obtain x,y,r. (We ignore r.)
3530                      */
3531                     double matrix[9], vector[3], vector2[3];
3532                     int m;
3533
3534                     for (m = 0; m < 3; m++) {
3535                         int x1 = edgedot1[m]->x, x2 = edgedot2[m]->x;
3536                         int y1 = edgedot1[m]->y, y2 = edgedot2[m]->y;
3537                         int dx = x2-x1, dy = y2-y1;
3538
3539                         /*
3540                          * ((x,y) - (x1,y1)) . (dy,-dx) = r |(dx,dy)|
3541                          *
3542                          * => x dy - y dx - r |(dx,dy)| = (x1 dy - y1 dx)
3543                          */
3544                         matrix[3*m+0] = dy;
3545                         matrix[3*m+1] = -dx;
3546                         matrix[3*m+2] = -sqrt((double)dx*dx+(double)dy*dy);
3547                         vector[m] = (double)x1*dy - (double)y1*dx;
3548                     }
3549
3550                     if (solve_3x3_matrix(matrix, vector, vector2)) {
3551                         cx[cn] = vector2[0];
3552                         cy[cn] = vector2[1];
3553                         cn++;
3554                     }
3555                 } else if (nedges == 2) {
3556                     /*
3557                      * Two edges and a dot. This will end up in a
3558                      * quadratic equation.
3559                      *
3560                      * First, look at the two edges. Having our point
3561                      * be some distance r from both of them gives rise
3562                      * to a pair of linear equations in x,y,r of the
3563                      * form
3564                      *
3565                      *   (x-x1) dy - (y-y1) dx = r sqrt(dx^2+dy^2)
3566                      *
3567                      * We eliminate r between those equations to give
3568                      * us a single linear equation in x,y describing
3569                      * the locus of points equidistant from both lines
3570                      * - i.e. the angle bisector. 
3571                      *
3572                      * We then choose one of x,y to be a parameter t,
3573                      * and derive linear formulae for x,y,r in terms
3574                      * of t. This enables us to write down the
3575                      * circular equation (x-xd)^2+(y-yd)^2=r^2 as a
3576                      * quadratic in t; solving that and substituting
3577                      * in for x,y gives us two candidate points.
3578                      */
3579                     double eqs[2][4];  /* a,b,c,d : ax+by+cr=d */
3580                     double eq[3];      /* a,b,c: ax+by=c */
3581                     double xt[2], yt[2], rt[2]; /* a,b: {x,y,r}=at+b */
3582                     double q[3];                /* a,b,c: at^2+bt+c=0 */
3583                     double disc;
3584
3585                     /* Find equations of the two input lines. */
3586                     for (m = 0; m < 2; m++) {
3587                         int x1 = edgedot1[m]->x, x2 = edgedot2[m]->x;
3588                         int y1 = edgedot1[m]->y, y2 = edgedot2[m]->y;
3589                         int dx = x2-x1, dy = y2-y1;
3590
3591                         eqs[m][0] = dy;
3592                         eqs[m][1] = -dx;
3593                         eqs[m][2] = -sqrt(dx*dx+dy*dy);
3594                         eqs[m][3] = x1*dy - y1*dx;
3595                     }
3596
3597                     /* Derive the angle bisector by eliminating r. */
3598                     eq[0] = eqs[0][0]*eqs[1][2] - eqs[1][0]*eqs[0][2];
3599                     eq[1] = eqs[0][1]*eqs[1][2] - eqs[1][1]*eqs[0][2];
3600                     eq[2] = eqs[0][3]*eqs[1][2] - eqs[1][3]*eqs[0][2];
3601
3602                     /* Parametrise x and y in terms of some t. */
3603                     if (abs(eq[0]) < abs(eq[1])) {
3604                         /* Parameter is x. */
3605                         xt[0] = 1; xt[1] = 0;
3606                         yt[0] = -eq[0]/eq[1]; yt[1] = eq[2]/eq[1];
3607                     } else {
3608                         /* Parameter is y. */
3609                         yt[0] = 1; yt[1] = 0;
3610                         xt[0] = -eq[1]/eq[0]; xt[1] = eq[2]/eq[0];
3611                     }
3612
3613                     /* Find a linear representation of r using eqs[0]. */
3614                     rt[0] = -(eqs[0][0]*xt[0] + eqs[0][1]*yt[0])/eqs[0][2];
3615                     rt[1] = (eqs[0][3] - eqs[0][0]*xt[1] -
3616                              eqs[0][1]*yt[1])/eqs[0][2];
3617
3618                     /* Construct the quadratic equation. */
3619                     q[0] = -rt[0]*rt[0];
3620                     q[1] = -2*rt[0]*rt[1];
3621                     q[2] = -rt[1]*rt[1];
3622                     q[0] += xt[0]*xt[0];
3623                     q[1] += 2*xt[0]*(xt[1]-dots[0]->x);
3624                     q[2] += (xt[1]-dots[0]->x)*(xt[1]-dots[0]->x);
3625                     q[0] += yt[0]*yt[0];
3626                     q[1] += 2*yt[0]*(yt[1]-dots[0]->y);
3627                     q[2] += (yt[1]-dots[0]->y)*(yt[1]-dots[0]->y);
3628
3629                     /* And solve it. */
3630                     disc = q[1]*q[1] - 4*q[0]*q[2];
3631                     if (disc >= 0) {
3632                         double t;
3633
3634                         disc = sqrt(disc);
3635
3636                         t = (-q[1] + disc) / (2*q[0]);
3637                         cx[cn] = xt[0]*t + xt[1];
3638                         cy[cn] = yt[0]*t + yt[1];
3639                         cn++;
3640
3641                         t = (-q[1] - disc) / (2*q[0]);
3642                         cx[cn] = xt[0]*t + xt[1];
3643                         cy[cn] = yt[0]*t + yt[1];
3644                         cn++;
3645                     }
3646                 } else if (nedges == 1) {
3647                     /*
3648                      * Two dots and an edge. This one's another
3649                      * quadratic equation.
3650                      *
3651                      * The point we want must lie on the perpendicular
3652                      * bisector of the two dots; that much is obvious.
3653                      * So we can construct a parametrisation of that
3654                      * bisecting line, giving linear formulae for x,y
3655                      * in terms of t. We can also express the distance
3656                      * from the edge as such a linear formula.
3657                      *
3658                      * Then we set that equal to the radius of the
3659                      * circle passing through the two points, which is
3660                      * a Pythagoras exercise; that gives rise to a
3661                      * quadratic in t, which we solve.
3662                      */
3663                     double xt[2], yt[2], rt[2]; /* a,b: {x,y,r}=at+b */
3664                     double q[3];                /* a,b,c: at^2+bt+c=0 */
3665                     double disc;
3666                     double halfsep;
3667
3668                     /* Find parametric formulae for x,y. */
3669                     {
3670                         int x1 = dots[0]->x, x2 = dots[1]->x;
3671                         int y1 = dots[0]->y, y2 = dots[1]->y;
3672                         int dx = x2-x1, dy = y2-y1;
3673                         double d = sqrt((double)dx*dx + (double)dy*dy);
3674
3675                         xt[1] = (x1+x2)/2.0;
3676                         yt[1] = (y1+y2)/2.0;
3677                         /* It's convenient if we have t at standard scale. */
3678                         xt[0] = -dy/d;
3679                         yt[0] = dx/d;
3680
3681                         /* Also note down half the separation between
3682                          * the dots, for use in computing the circle radius. */
3683                         halfsep = 0.5*d;
3684                     }
3685
3686                     /* Find a parametric formula for r. */
3687                     {
3688                         int x1 = edgedot1[0]->x, x2 = edgedot2[0]->x;
3689                         int y1 = edgedot1[0]->y, y2 = edgedot2[0]->y;
3690                         int dx = x2-x1, dy = y2-y1;
3691                         double d = sqrt((double)dx*dx + (double)dy*dy);
3692                         rt[0] = (xt[0]*dy - yt[0]*dx) / d;
3693                         rt[1] = ((xt[1]-x1)*dy - (yt[1]-y1)*dx) / d;
3694                     }
3695
3696                     /* Construct the quadratic equation. */
3697                     q[0] = rt[0]*rt[0];
3698                     q[1] = 2*rt[0]*rt[1];
3699                     q[2] = rt[1]*rt[1];
3700                     q[0] -= 1;
3701                     q[2] -= halfsep*halfsep;
3702
3703                     /* And solve it. */
3704                     disc = q[1]*q[1] - 4*q[0]*q[2];
3705                     if (disc >= 0) {
3706                         double t;
3707
3708                         disc = sqrt(disc);
3709
3710                         t = (-q[1] + disc) / (2*q[0]);
3711                         cx[cn] = xt[0]*t + xt[1];
3712                         cy[cn] = yt[0]*t + yt[1];
3713                         cn++;
3714
3715                         t = (-q[1] - disc) / (2*q[0]);
3716                         cx[cn] = xt[0]*t + xt[1];
3717                         cy[cn] = yt[0]*t + yt[1];
3718                         cn++;
3719                     }
3720                 } else if (nedges == 0) {
3721                     /*
3722                      * Three dots. This is another linear matrix
3723                      * equation, this time with each row of the matrix
3724                      * representing the perpendicular bisector between
3725                      * two of the points. Of course we only need two
3726                      * such lines to find their intersection, so we
3727                      * need only solve a 2x2 matrix equation.
3728                      */
3729
3730                     double matrix[4], vector[2], vector2[2];
3731                     int m;
3732
3733                     for (m = 0; m < 2; m++) {
3734                         int x1 = dots[m]->x, x2 = dots[m+1]->x;
3735                         int y1 = dots[m]->y, y2 = dots[m+1]->y;
3736                         int dx = x2-x1, dy = y2-y1;
3737
3738                         /*
3739                          * ((x,y) - (x1,y1)) . (dx,dy) = 1/2 |(dx,dy)|^2
3740                          *
3741                          * => 2x dx + 2y dy = dx^2+dy^2 + (2 x1 dx + 2 y1 dy)
3742                          */
3743                         matrix[2*m+0] = 2*dx;
3744                         matrix[2*m+1] = 2*dy;
3745                         vector[m] = ((double)dx*dx + (double)dy*dy +
3746                                      2.0*x1*dx + 2.0*y1*dy);
3747                     }
3748
3749                     if (solve_2x2_matrix(matrix, vector, vector2)) {
3750                         cx[cn] = vector2[0];
3751                         cy[cn] = vector2[1];
3752                         cn++;
3753                     }
3754                 }
3755
3756                 /*
3757                  * Now go through our candidate points and see if any
3758                  * of them are better than what we've got so far.
3759                  */
3760                 for (m = 0; m < cn; m++) {
3761                     double x = cx[m], y = cy[m];
3762
3763                     /*
3764                      * First, disqualify the point if it's not inside
3765                      * the polygon, which we work out by counting the
3766                      * edges to the right of the point. (For
3767                      * tiebreaking purposes when edges start or end on
3768                      * our y-coordinate or go right through it, we
3769                      * consider our point to be offset by a small
3770                      * _positive_ epsilon in both the x- and
3771                      * y-direction.)
3772                      */
3773                     int e, in = 0;
3774                     for (e = 0; e < f->order; e++) {
3775                         int xs = f->edges[e]->dot1->x;
3776                         int xe = f->edges[e]->dot2->x;
3777                         int ys = f->edges[e]->dot1->y;
3778                         int ye = f->edges[e]->dot2->y;
3779                         if ((y >= ys && y < ye) || (y >= ye && y < ys)) {
3780                             /*
3781                              * The line goes past our y-position. Now we need
3782                              * to know if its x-coordinate when it does so is
3783                              * to our right.
3784                              *
3785                              * The x-coordinate in question is mathematically
3786                              * (y - ys) * (xe - xs) / (ye - ys), and we want
3787                              * to know whether (x - xs) >= that. Of course we
3788                              * avoid the division, so we can work in integers;
3789                              * to do this we must multiply both sides of the
3790                              * inequality by ye - ys, which means we must
3791                              * first check that's not negative.
3792                              */
3793                             int num = xe - xs, denom = ye - ys;
3794                             if (denom < 0) {
3795                                 num = -num;
3796                                 denom = -denom;
3797                             }
3798                             if ((x - xs) * denom >= (y - ys) * num)
3799                                 in ^= 1;
3800                         }
3801                     }
3802
3803                     if (in) {
3804                         double mindist = HUGE_VAL;
3805                         int e, d;
3806
3807                         /*
3808                          * This point is inside the polygon, so now we check
3809                          * its minimum distance to every edge and corner.
3810                          * First the corners ...
3811                          */
3812                         for (d = 0; d < f->order; d++) {
3813                             int xp = f->dots[d]->x;
3814                             int yp = f->dots[d]->y;
3815                             double dx = x - xp, dy = y - yp;
3816                             double dist = dx*dx + dy*dy;
3817                             if (mindist > dist)
3818                                 mindist = dist;
3819                         }
3820
3821                         /*
3822                          * ... and now also check the perpendicular distance
3823                          * to every edge, if the perpendicular lies between
3824                          * the edge's endpoints.
3825                          */
3826                         for (e = 0; e < f->order; e++) {
3827                             int xs = f->edges[e]->dot1->x;
3828                             int xe = f->edges[e]->dot2->x;
3829                             int ys = f->edges[e]->dot1->y;
3830                             int ye = f->edges[e]->dot2->y;
3831
3832                             /*
3833                              * If s and e are our endpoints, and p our
3834                              * candidate circle centre, the foot of a
3835                              * perpendicular from p to the line se lies
3836                              * between s and e if and only if (p-s).(e-s) lies
3837                              * strictly between 0 and (e-s).(e-s).
3838                              */
3839                             int edx = xe - xs, edy = ye - ys;
3840                             double pdx = x - xs, pdy = y - ys;
3841                             double pde = pdx * edx + pdy * edy;
3842                             long ede = (long)edx * edx + (long)edy * edy;
3843                             if (0 < pde && pde < ede) {
3844                                 /*
3845                                  * Yes, the nearest point on this edge is
3846                                  * closer than either endpoint, so we must
3847                                  * take it into account by measuring the
3848                                  * perpendicular distance to the edge and
3849                                  * checking its square against mindist.
3850                                  */
3851
3852                                 double pdre = pdx * edy - pdy * edx;
3853                                 double sqlen = pdre * pdre / ede;
3854
3855                                 if (mindist > sqlen)
3856                                     mindist = sqlen;
3857                             }
3858                         }
3859
3860                         /*
3861                          * Right. Now we know the biggest circle around this
3862                          * point, so we can check it against bestdist.
3863                          */
3864                         if (bestdist < mindist) {
3865                             bestdist = mindist;
3866                             xbest = x;
3867                             ybest = y;
3868                         }
3869                     }
3870                 }
3871
3872                 if (k < f->order)
3873                     nedges--;
3874                 else
3875                     ndots--;
3876             }
3877             if (j < f->order)
3878                 nedges--;
3879             else
3880                 ndots--;
3881         }
3882         if (i < f->order)
3883             nedges--;
3884         else
3885             ndots--;
3886     }
3887
3888     assert(bestdist > 0);
3889
3890     /* convert to screen coordinates. Round doubles to nearest. */
3891     grid_to_screen(ds, g, xbest+0.5, ybest+0.5,
3892                    &ds->textx[faceindex], &ds->texty[faceindex]);
3893
3894     *xret = ds->textx[faceindex];
3895     *yret = ds->texty[faceindex];
3896 }
3897
3898 static void face_text_bbox(game_drawstate *ds, grid *g, grid_face *f,
3899                            int *x, int *y, int *w, int *h)
3900 {
3901     int xx, yy;
3902     face_text_pos(ds, g, f, &xx, &yy);
3903
3904     /* There seems to be a certain amount of trial-and-error involved
3905      * in working out the correct bounding-box for the text. */
3906
3907     *x = xx - ds->tilesize/4 - 1;
3908     *y = yy - ds->tilesize/4 - 3;
3909     *w = ds->tilesize/2 + 2;
3910     *h = ds->tilesize/2 + 5;
3911 }
3912
3913 static void game_redraw_clue(drawing *dr, game_drawstate *ds,
3914                              game_state *state, int i)
3915 {
3916     grid *g = state->game_grid;
3917     grid_face *f = g->faces + i;
3918     int x, y;
3919     char c[3];
3920
3921     if (state->clues[i] < 10) {
3922         c[0] = CLUE2CHAR(state->clues[i]);
3923         c[1] = '\0';
3924     } else {
3925         sprintf(c, "%d", state->clues[i]);
3926     }
3927
3928     face_text_pos(ds, g, f, &x, &y);
3929     draw_text(dr, x, y,
3930               FONT_VARIABLE, ds->tilesize/2,
3931               ALIGN_VCENTRE | ALIGN_HCENTRE,
3932               ds->clue_error[i] ? COL_MISTAKE :
3933               ds->clue_satisfied[i] ? COL_SATISFIED : COL_FOREGROUND, c);
3934 }
3935
3936 static void edge_bbox(game_drawstate *ds, grid *g, grid_edge *e,
3937                       int *x, int *y, int *w, int *h)
3938 {
3939     int x1 = e->dot1->x;
3940     int y1 = e->dot1->y;
3941     int x2 = e->dot2->x;
3942     int y2 = e->dot2->y;
3943     int xmin, xmax, ymin, ymax;
3944
3945     grid_to_screen(ds, g, x1, y1, &x1, &y1);
3946     grid_to_screen(ds, g, x2, y2, &x2, &y2);
3947     /* Allow extra margin for dots, and thickness of lines */
3948     xmin = min(x1, x2) - 2;
3949     xmax = max(x1, x2) + 2;
3950     ymin = min(y1, y2) - 2;
3951     ymax = max(y1, y2) + 2;
3952
3953     *x = xmin;
3954     *y = ymin;
3955     *w = xmax - xmin + 1;
3956     *h = ymax - ymin + 1;
3957 }
3958
3959 static void dot_bbox(game_drawstate *ds, grid *g, grid_dot *d,
3960                      int *x, int *y, int *w, int *h)
3961 {
3962     int x1, y1;
3963
3964     grid_to_screen(ds, g, d->x, d->y, &x1, &y1);
3965
3966     *x = x1 - 2;
3967     *y = y1 - 2;
3968     *w = 5;
3969     *h = 5;
3970 }
3971
3972 static const int loopy_line_redraw_phases[] = {
3973     COL_FAINT, COL_LINEUNKNOWN, COL_FOREGROUND, COL_HIGHLIGHT, COL_MISTAKE
3974 };
3975 #define NPHASES lenof(loopy_line_redraw_phases)
3976
3977 static void game_redraw_line(drawing *dr, game_drawstate *ds,
3978                              game_state *state, int i, int phase)
3979 {
3980     grid *g = state->game_grid;
3981     grid_edge *e = g->edges + i;
3982     int x1, x2, y1, y2;
3983     int xmin, ymin, xmax, ymax;
3984     int line_colour;
3985
3986     if (state->line_errors[i])
3987         line_colour = COL_MISTAKE;
3988     else if (state->lines[i] == LINE_UNKNOWN)
3989         line_colour = COL_LINEUNKNOWN;
3990     else if (state->lines[i] == LINE_NO)
3991         line_colour = COL_FAINT;
3992     else if (ds->flashing)
3993         line_colour = COL_HIGHLIGHT;
3994     else
3995         line_colour = COL_FOREGROUND;
3996     if (line_colour != loopy_line_redraw_phases[phase])
3997         return;
3998
3999     /* Convert from grid to screen coordinates */
4000     grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
4001     grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
4002
4003     xmin = min(x1, x2);
4004     xmax = max(x1, x2);
4005     ymin = min(y1, y2);
4006     ymax = max(y1, y2);
4007
4008     if (line_colour == COL_FAINT) {
4009         static int draw_faint_lines = -1;
4010         if (draw_faint_lines < 0) {
4011             char *env = getenv("LOOPY_FAINT_LINES");
4012             draw_faint_lines = (!env || (env[0] == 'y' ||
4013                                          env[0] == 'Y'));
4014         }
4015         if (draw_faint_lines)
4016             draw_line(dr, x1, y1, x2, y2, line_colour);
4017     } else {
4018         draw_thick_line(dr, 3.0,
4019                         x1 + 0.5, y1 + 0.5,
4020                         x2 + 0.5, y2 + 0.5,
4021                         line_colour);
4022     }
4023 }
4024
4025 static void game_redraw_dot(drawing *dr, game_drawstate *ds,
4026                             game_state *state, int i)
4027 {
4028     grid *g = state->game_grid;
4029     grid_dot *d = g->dots + i;
4030     int x, y;
4031
4032     grid_to_screen(ds, g, d->x, d->y, &x, &y);
4033     draw_circle(dr, x, y, 2, COL_FOREGROUND, COL_FOREGROUND);
4034 }
4035
4036 static int boxes_intersect(int x0, int y0, int w0, int h0,
4037                            int x1, int y1, int w1, int h1)
4038 {
4039     /*
4040      * Two intervals intersect iff neither is wholly on one side of
4041      * the other. Two boxes intersect iff their horizontal and
4042      * vertical intervals both intersect.
4043      */
4044     return (x0 < x1+w1 && x1 < x0+w0 && y0 < y1+h1 && y1 < y0+h0);
4045 }
4046
4047 static void game_redraw_in_rect(drawing *dr, game_drawstate *ds,
4048                                 game_state *state, int x, int y, int w, int h)
4049 {
4050     grid *g = state->game_grid;
4051     int i, phase;
4052     int bx, by, bw, bh;
4053
4054     clip(dr, x, y, w, h);
4055     draw_rect(dr, x, y, w, h, COL_BACKGROUND);
4056
4057     for (i = 0; i < g->num_faces; i++) {
4058         if (state->clues[i] >= 0) {
4059             face_text_bbox(ds, g, &g->faces[i], &bx, &by, &bw, &bh);
4060             if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
4061                 game_redraw_clue(dr, ds, state, i);
4062         }
4063     }
4064     for (phase = 0; phase < NPHASES; phase++) {
4065         for (i = 0; i < g->num_edges; i++) {
4066             edge_bbox(ds, g, &g->edges[i], &bx, &by, &bw, &bh);
4067             if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
4068                 game_redraw_line(dr, ds, state, i, phase);
4069         }
4070     }
4071     for (i = 0; i < g->num_dots; i++) {
4072         dot_bbox(ds, g, &g->dots[i], &bx, &by, &bw, &bh);
4073         if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
4074             game_redraw_dot(dr, ds, state, i);
4075     }
4076
4077     unclip(dr);
4078     draw_update(dr, x, y, w, h);
4079 }
4080
4081 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
4082                         game_state *state, int dir, game_ui *ui,
4083                         float animtime, float flashtime)
4084 {
4085 #define REDRAW_OBJECTS_LIMIT 16         /* Somewhat arbitrary tradeoff */
4086
4087     grid *g = state->game_grid;
4088     int border = BORDER(ds->tilesize);
4089     int i;
4090     int flash_changed;
4091     int redraw_everything = FALSE;
4092
4093     int edges[REDRAW_OBJECTS_LIMIT], nedges = 0;
4094     int faces[REDRAW_OBJECTS_LIMIT], nfaces = 0;
4095
4096     /* Redrawing is somewhat involved.
4097      *
4098      * An update can theoretically affect an arbitrary number of edges
4099      * (consider, for example, completing or breaking a cycle which doesn't
4100      * satisfy all the clues -- we'll switch many edges between error and
4101      * normal states).  On the other hand, redrawing the whole grid takes a
4102      * while, making the game feel sluggish, and many updates are actually
4103      * quite well localized.
4104      *
4105      * This redraw algorithm attempts to cope with both situations gracefully
4106      * and correctly.  For localized changes, we set a clip rectangle, fill
4107      * it with background, and then redraw (a plausible but conservative
4108      * guess at) the objects which intersect the rectangle; if several
4109      * objects need redrawing, we'll do them individually.  However, if lots
4110      * of objects are affected, we'll just redraw everything.
4111      *
4112      * The reason for all of this is that it's just not safe to do the redraw
4113      * piecemeal.  If you try to draw an antialiased diagonal line over
4114      * itself, you get a slightly thicker antialiased diagonal line, which
4115      * looks rather ugly after a while.
4116      *
4117      * So, we take two passes over the grid.  The first attempts to work out
4118      * what needs doing, and the second actually does it.
4119      */
4120
4121     if (!ds->started)
4122         redraw_everything = TRUE;
4123     else {
4124
4125         /* First, trundle through the faces. */
4126         for (i = 0; i < g->num_faces; i++) {
4127             grid_face *f = g->faces + i;
4128             int sides = f->order;
4129             int clue_mistake;
4130             int clue_satisfied;
4131             int n = state->clues[i];
4132             if (n < 0)
4133                 continue;
4134
4135             clue_mistake = (face_order(state, i, LINE_YES) > n ||
4136                             face_order(state, i, LINE_NO ) > (sides-n));
4137             clue_satisfied = (face_order(state, i, LINE_YES) == n &&
4138                               face_order(state, i, LINE_NO ) == (sides-n));
4139
4140             if (clue_mistake != ds->clue_error[i] ||
4141                 clue_satisfied != ds->clue_satisfied[i]) {
4142                 ds->clue_error[i] = clue_mistake;
4143                 ds->clue_satisfied[i] = clue_satisfied;
4144                 if (nfaces == REDRAW_OBJECTS_LIMIT)
4145                     redraw_everything = TRUE;
4146                 else
4147                     faces[nfaces++] = i;
4148             }
4149         }
4150
4151         /* Work out what the flash state needs to be. */
4152         if (flashtime > 0 &&
4153             (flashtime <= FLASH_TIME/3 ||
4154              flashtime >= FLASH_TIME*2/3)) {
4155             flash_changed = !ds->flashing;
4156             ds->flashing = TRUE;
4157         } else {
4158             flash_changed = ds->flashing;
4159             ds->flashing = FALSE;
4160         }
4161
4162         /* Now, trundle through the edges. */
4163         for (i = 0; i < g->num_edges; i++) {
4164             char new_ds =
4165                 state->line_errors[i] ? DS_LINE_ERROR : state->lines[i];
4166             if (new_ds != ds->lines[i] ||
4167                 (flash_changed && state->lines[i] == LINE_YES)) {
4168                 ds->lines[i] = new_ds;
4169                 if (nedges == REDRAW_OBJECTS_LIMIT)
4170                     redraw_everything = TRUE;
4171                 else
4172                     edges[nedges++] = i;
4173             }
4174         }
4175     }
4176
4177     /* Pass one is now done.  Now we do the actual drawing. */
4178     if (redraw_everything) {
4179         int grid_width = g->highest_x - g->lowest_x;
4180         int grid_height = g->highest_y - g->lowest_y;
4181         int w = grid_width * ds->tilesize / g->tilesize;
4182         int h = grid_height * ds->tilesize / g->tilesize;
4183
4184         game_redraw_in_rect(dr, ds, state,
4185                             0, 0, w + 2*border + 1, h + 2*border + 1);
4186     } else {
4187
4188         /* Right.  Now we roll up our sleeves. */
4189
4190         for (i = 0; i < nfaces; i++) {
4191             grid_face *f = g->faces + faces[i];
4192             int x, y, w, h;
4193
4194             face_text_bbox(ds, g, f, &x, &y, &w, &h);
4195             game_redraw_in_rect(dr, ds, state, x, y, w, h);
4196         }
4197
4198         for (i = 0; i < nedges; i++) {
4199             grid_edge *e = g->edges + edges[i];
4200             int x, y, w, h;
4201
4202             edge_bbox(ds, g, e, &x, &y, &w, &h);
4203             game_redraw_in_rect(dr, ds, state, x, y, w, h);
4204         }
4205     }
4206
4207     ds->started = TRUE;
4208 }
4209
4210 static float game_flash_length(game_state *oldstate, game_state *newstate,
4211                                int dir, game_ui *ui)
4212 {
4213     if (!oldstate->solved  &&  newstate->solved &&
4214         !oldstate->cheated && !newstate->cheated) {
4215         return FLASH_TIME;
4216     }
4217
4218     return 0.0F;
4219 }
4220
4221 static int game_is_solved(game_state *state)
4222 {
4223     return state->solved;
4224 }
4225
4226 static void game_print_size(game_params *params, float *x, float *y)
4227 {
4228     int pw, ph;
4229
4230     /*
4231      * I'll use 7mm "squares" by default.
4232      */
4233     game_compute_size(params, 700, &pw, &ph);
4234     *x = pw / 100.0F;
4235     *y = ph / 100.0F;
4236 }
4237
4238 static void game_print(drawing *dr, game_state *state, int tilesize)
4239 {
4240     int ink = print_mono_colour(dr, 0);
4241     int i;
4242     game_drawstate ads, *ds = &ads;
4243     grid *g = state->game_grid;
4244
4245     ds->tilesize = tilesize;
4246
4247     for (i = 0; i < g->num_dots; i++) {
4248         int x, y;
4249         grid_to_screen(ds, g, g->dots[i].x, g->dots[i].y, &x, &y);
4250         draw_circle(dr, x, y, ds->tilesize / 15, ink, ink);
4251     }
4252
4253     /*
4254      * Clues.
4255      */
4256     for (i = 0; i < g->num_faces; i++) {
4257         grid_face *f = g->faces + i;
4258         int clue = state->clues[i];
4259         if (clue >= 0) {
4260             char c[2];
4261             int x, y;
4262             c[0] = CLUE2CHAR(clue);
4263             c[1] = '\0';
4264             face_text_pos(ds, g, f, &x, &y);
4265             draw_text(dr, x, y,
4266                       FONT_VARIABLE, ds->tilesize / 2,
4267                       ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
4268         }
4269     }
4270
4271     /*
4272      * Lines.
4273      */
4274     for (i = 0; i < g->num_edges; i++) {
4275         int thickness = (state->lines[i] == LINE_YES) ? 30 : 150;
4276         grid_edge *e = g->edges + i;
4277         int x1, y1, x2, y2;
4278         grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
4279         grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
4280         if (state->lines[i] == LINE_YES)
4281         {
4282             /* (dx, dy) points from (x1, y1) to (x2, y2).
4283              * The line is then "fattened" in a perpendicular
4284              * direction to create a thin rectangle. */
4285             double d = sqrt(SQ((double)x1 - x2) + SQ((double)y1 - y2));
4286             double dx = (x2 - x1) / d;
4287             double dy = (y2 - y1) / d;
4288             int points[8];
4289
4290             dx = (dx * ds->tilesize) / thickness;
4291             dy = (dy * ds->tilesize) / thickness;
4292             points[0] = x1 + (int)dy;
4293             points[1] = y1 - (int)dx;
4294             points[2] = x1 - (int)dy;
4295             points[3] = y1 + (int)dx;
4296             points[4] = x2 - (int)dy;
4297             points[5] = y2 + (int)dx;
4298             points[6] = x2 + (int)dy;
4299             points[7] = y2 - (int)dx;
4300             draw_polygon(dr, points, 4, ink, ink);
4301         }
4302         else
4303         {
4304             /* Draw a dotted line */
4305             int divisions = 6;
4306             int j;
4307             for (j = 1; j < divisions; j++) {
4308                 /* Weighted average */
4309                 int x = (x1 * (divisions -j) + x2 * j) / divisions;
4310                 int y = (y1 * (divisions -j) + y2 * j) / divisions;
4311                 draw_circle(dr, x, y, ds->tilesize / thickness, ink, ink);
4312             }
4313         }
4314     }
4315 }
4316
4317 #ifdef COMBINED
4318 #define thegame loopy
4319 #endif
4320
4321 const struct game thegame = {
4322     "Loopy", "games.loopy", "loopy",
4323     default_params,
4324     game_fetch_preset,
4325     decode_params,
4326     encode_params,
4327     free_params,
4328     dup_params,
4329     TRUE, game_configure, custom_params,
4330     validate_params,
4331     new_game_desc,
4332     validate_desc,
4333     new_game,
4334     dup_game,
4335     free_game,
4336     1, solve_game,
4337     TRUE, game_can_format_as_text_now, game_text_format,
4338     new_ui,
4339     free_ui,
4340     encode_ui,
4341     decode_ui,
4342     game_changed_state,
4343     interpret_move,
4344     execute_move,
4345     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
4346     game_colours,
4347     game_new_drawstate,
4348     game_free_drawstate,
4349     game_redraw,
4350     game_anim_length,
4351     game_flash_length,
4352     game_is_solved,
4353     TRUE, FALSE, game_print_size, game_print,
4354     FALSE /* wants_statusbar */,
4355     FALSE, game_timing_state,
4356     0,                                       /* mouse_priorities */
4357 };
4358
4359 #ifdef STANDALONE_SOLVER
4360
4361 /*
4362  * Half-hearted standalone solver. It can't output the solution to
4363  * anything but a square puzzle, and it can't log the deductions
4364  * it makes either. But it can solve square puzzles, and more
4365  * importantly it can use its solver to grade the difficulty of
4366  * any puzzle you give it.
4367  */
4368
4369 #include <stdarg.h>
4370
4371 int main(int argc, char **argv)
4372 {
4373     game_params *p;
4374     game_state *s;
4375     char *id = NULL, *desc, *err;
4376     int grade = FALSE;
4377     int ret, diff;
4378 #if 0 /* verbose solver not supported here (yet) */
4379     int really_verbose = FALSE;
4380 #endif
4381
4382     while (--argc > 0) {
4383         char *p = *++argv;
4384 #if 0 /* verbose solver not supported here (yet) */
4385         if (!strcmp(p, "-v")) {
4386             really_verbose = TRUE;
4387         } else
4388 #endif
4389         if (!strcmp(p, "-g")) {
4390             grade = TRUE;
4391         } else if (*p == '-') {
4392             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
4393             return 1;
4394         } else {
4395             id = p;
4396         }
4397     }
4398
4399     if (!id) {
4400         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
4401         return 1;
4402     }
4403
4404     desc = strchr(id, ':');
4405     if (!desc) {
4406         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
4407         return 1;
4408     }
4409     *desc++ = '\0';
4410
4411     p = default_params();
4412     decode_params(p, id);
4413     err = validate_desc(p, desc);
4414     if (err) {
4415         fprintf(stderr, "%s: %s\n", argv[0], err);
4416         return 1;
4417     }
4418     s = new_game(NULL, p, desc);
4419
4420     /*
4421      * When solving an Easy puzzle, we don't want to bother the
4422      * user with Hard-level deductions. For this reason, we grade
4423      * the puzzle internally before doing anything else.
4424      */
4425     ret = -1;                          /* placate optimiser */
4426     for (diff = 0; diff < DIFF_MAX; diff++) {
4427         solver_state *sstate_new;
4428         solver_state *sstate = new_solver_state((game_state *)s, diff);
4429
4430         sstate_new = solve_game_rec(sstate);
4431
4432         if (sstate_new->solver_status == SOLVER_MISTAKE)
4433             ret = 0;
4434         else if (sstate_new->solver_status == SOLVER_SOLVED)
4435             ret = 1;
4436         else
4437             ret = 2;
4438
4439         free_solver_state(sstate_new);
4440         free_solver_state(sstate);
4441
4442         if (ret < 2)
4443             break;
4444     }
4445
4446     if (diff == DIFF_MAX) {
4447         if (grade)
4448             printf("Difficulty rating: harder than Hard, or ambiguous\n");
4449         else
4450             printf("Unable to find a unique solution\n");
4451     } else {
4452         if (grade) {
4453             if (ret == 0)
4454                 printf("Difficulty rating: impossible (no solution exists)\n");
4455             else if (ret == 1)
4456                 printf("Difficulty rating: %s\n", diffnames[diff]);
4457         } else {
4458             solver_state *sstate_new;
4459             solver_state *sstate = new_solver_state((game_state *)s, diff);
4460
4461             /* If we supported a verbose solver, we'd set verbosity here */
4462
4463             sstate_new = solve_game_rec(sstate);
4464
4465             if (sstate_new->solver_status == SOLVER_MISTAKE)
4466                 printf("Puzzle is inconsistent\n");
4467             else {
4468                 assert(sstate_new->solver_status == SOLVER_SOLVED);
4469                 if (s->grid_type == 0) {
4470                     fputs(game_text_format(sstate_new->state), stdout);
4471                 } else {
4472                     printf("Unable to output non-square grids\n");
4473                 }
4474             }
4475
4476             free_solver_state(sstate_new);
4477             free_solver_state(sstate);
4478         }
4479     }
4480
4481     return 0;
4482 }
4483
4484 #endif