chiark / gitweb /
Forbid undo of new-game if it would change the params.
[sgt-puzzles.git] / net.c
1 /*
2  * net.c: Net game.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <ctype.h>
10 #include <math.h>
11
12 #include "puzzles.h"
13 #include "tree234.h"
14
15 /*
16  * The standard user interface for Net simply has left- and
17  * right-button mouse clicks in a square rotate it one way or the
18  * other. We also provide, by #ifdef, a separate interface based on
19  * rotational dragging motions. I initially developed this for the
20  * Mac on the basis that it might work better than the click
21  * interface with only one mouse button available, but in fact
22  * found it to be quite strange and unintuitive. Apparently it
23  * works better on stylus-driven platforms such as Palm and
24  * PocketPC, though, so we enable it by default there.
25  */
26 #ifdef STYLUS_BASED
27 #define USE_DRAGGING
28 #endif
29
30 /* Direction and other bitfields */
31 #define R 0x01
32 #define U 0x02
33 #define L 0x04
34 #define D 0x08
35 #define LOCKED 0x10
36 #define ACTIVE 0x20
37 #define RLOOP (R << 6)
38 #define ULOOP (U << 6)
39 #define LLOOP (L << 6)
40 #define DLOOP (D << 6)
41 #define LOOP(dir) ((dir) << 6)
42
43 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
44 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
45 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
46 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
47 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
48                     ((n)&3) == 1 ? A(x) : \
49                     ((n)&3) == 2 ? F(x) : C(x) )
50
51 /* X and Y displacements */
52 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
53 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
54
55 /* Bit count */
56 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
57                    (((x) & 0x02) >> 1) + ((x) & 0x01) )
58
59 #define PREFERRED_TILE_SIZE 32
60 #define TILE_SIZE (ds->tilesize)
61 #define LINE_THICK ((TILE_SIZE+47)/48)
62 #ifdef SMALL_SCREEN
63 #define WINDOW_OFFSET 4
64 #else
65 #define WINDOW_OFFSET 16
66 #endif
67
68 #define ROTATE_TIME 0.13F
69 #define FLASH_FRAME 0.07F
70
71 enum {
72     COL_BACKGROUND,
73     COL_LOCKED,
74     COL_BORDER,
75     COL_WIRE,
76     COL_ENDPOINT,
77     COL_POWERED,
78     COL_BARRIER,
79     COL_LOOP,
80     NCOLOURS
81 };
82
83 struct game_params {
84     int width;
85     int height;
86     int wrapping;
87     int unique;
88     float barrier_probability;
89 };
90
91 typedef struct game_immutable_state {
92     int refcount;
93     unsigned char *barriers;
94 } game_immutable_state;
95
96 struct game_state {
97     int width, height, wrapping, completed;
98     int last_rotate_x, last_rotate_y, last_rotate_dir;
99     int used_solve;
100     unsigned char *tiles;
101     struct game_immutable_state *imm;
102 };
103
104 #define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
105     ( (x2) = ((x1) + width + X((dir))) % width, \
106       (y2) = ((y1) + height + Y((dir))) % height)
107
108 #define OFFSET(x2,y2,x1,y1,dir,state) \
109         OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
110
111 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
112 #define tile(state, x, y)     index(state, (state)->tiles, x, y)
113 #define barrier(state, x, y)  index(state, (state)->imm->barriers, x, y)
114
115 struct xyd {
116     int x, y, direction;
117 };
118
119 static int xyd_cmp(const void *av, const void *bv) {
120     const struct xyd *a = (const struct xyd *)av;
121     const struct xyd *b = (const struct xyd *)bv;
122     if (a->x < b->x)
123         return -1;
124     if (a->x > b->x)
125         return +1;
126     if (a->y < b->y)
127         return -1;
128     if (a->y > b->y)
129         return +1;
130     if (a->direction < b->direction)
131         return -1;
132     if (a->direction > b->direction)
133         return +1;
134     return 0;
135 }
136
137 static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
138
139 static struct xyd *new_xyd(int x, int y, int direction)
140 {
141     struct xyd *xyd = snew(struct xyd);
142     xyd->x = x;
143     xyd->y = y;
144     xyd->direction = direction;
145     return xyd;
146 }
147
148 /* ----------------------------------------------------------------------
149  * Manage game parameters.
150  */
151 static game_params *default_params(void)
152 {
153     game_params *ret = snew(game_params);
154
155     ret->width = 5;
156     ret->height = 5;
157     ret->wrapping = FALSE;
158     ret->unique = TRUE;
159     ret->barrier_probability = 0.0;
160
161     return ret;
162 }
163
164 static const struct game_params net_presets[] = {
165     {5, 5, FALSE, TRUE, 0.0},
166     {7, 7, FALSE, TRUE, 0.0},
167     {9, 9, FALSE, TRUE, 0.0},
168     {11, 11, FALSE, TRUE, 0.0},
169 #ifndef SMALL_SCREEN
170     {13, 11, FALSE, TRUE, 0.0},
171 #endif
172     {5, 5, TRUE, TRUE, 0.0},
173     {7, 7, TRUE, TRUE, 0.0},
174     {9, 9, TRUE, TRUE, 0.0},
175     {11, 11, TRUE, TRUE, 0.0},
176 #ifndef SMALL_SCREEN
177     {13, 11, TRUE, TRUE, 0.0},
178 #endif
179 };
180
181 static int game_fetch_preset(int i, char **name, game_params **params)
182 {
183     game_params *ret;
184     char str[80];
185
186     if (i < 0 || i >= lenof(net_presets))
187         return FALSE;
188
189     ret = snew(game_params);
190     *ret = net_presets[i];
191
192     sprintf(str, "%dx%d%s", ret->width, ret->height,
193             ret->wrapping ? " wrapping" : "");
194
195     *name = dupstr(str);
196     *params = ret;
197     return TRUE;
198 }
199
200 static void free_params(game_params *params)
201 {
202     sfree(params);
203 }
204
205 static game_params *dup_params(const game_params *params)
206 {
207     game_params *ret = snew(game_params);
208     *ret = *params;                    /* structure copy */
209     return ret;
210 }
211
212 static void decode_params(game_params *ret, char const *string)
213 {
214     char const *p = string;
215
216     ret->width = atoi(p);
217     while (*p && isdigit((unsigned char)*p)) p++;
218     if (*p == 'x') {
219         p++;
220         ret->height = atoi(p);
221         while (*p && isdigit((unsigned char)*p)) p++;
222     } else {
223         ret->height = ret->width;
224     }
225
226     while (*p) {
227         if (*p == 'w') {
228             p++;
229             ret->wrapping = TRUE;
230         } else if (*p == 'b') {
231             p++;
232             ret->barrier_probability = (float)atof(p);
233             while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
234         } else if (*p == 'a') {
235             p++;
236             ret->unique = FALSE;
237         } else
238             p++;                       /* skip any other gunk */
239     }
240 }
241
242 static char *encode_params(const game_params *params, int full)
243 {
244     char ret[400];
245     int len;
246
247     len = sprintf(ret, "%dx%d", params->width, params->height);
248     if (params->wrapping)
249         ret[len++] = 'w';
250     if (full && params->barrier_probability)
251         len += sprintf(ret+len, "b%g", params->barrier_probability);
252     if (full && !params->unique)
253         ret[len++] = 'a';
254     assert(len < lenof(ret));
255     ret[len] = '\0';
256
257     return dupstr(ret);
258 }
259
260 static config_item *game_configure(const game_params *params)
261 {
262     config_item *ret;
263     char buf[80];
264
265     ret = snewn(6, config_item);
266
267     ret[0].name = "Width";
268     ret[0].type = C_STRING;
269     sprintf(buf, "%d", params->width);
270     ret[0].sval = dupstr(buf);
271     ret[0].ival = 0;
272
273     ret[1].name = "Height";
274     ret[1].type = C_STRING;
275     sprintf(buf, "%d", params->height);
276     ret[1].sval = dupstr(buf);
277     ret[1].ival = 0;
278
279     ret[2].name = "Walls wrap around";
280     ret[2].type = C_BOOLEAN;
281     ret[2].sval = NULL;
282     ret[2].ival = params->wrapping;
283
284     ret[3].name = "Barrier probability";
285     ret[3].type = C_STRING;
286     sprintf(buf, "%g", params->barrier_probability);
287     ret[3].sval = dupstr(buf);
288     ret[3].ival = 0;
289
290     ret[4].name = "Ensure unique solution";
291     ret[4].type = C_BOOLEAN;
292     ret[4].sval = NULL;
293     ret[4].ival = params->unique;
294
295     ret[5].name = NULL;
296     ret[5].type = C_END;
297     ret[5].sval = NULL;
298     ret[5].ival = 0;
299
300     return ret;
301 }
302
303 static game_params *custom_params(const config_item *cfg)
304 {
305     game_params *ret = snew(game_params);
306
307     ret->width = atoi(cfg[0].sval);
308     ret->height = atoi(cfg[1].sval);
309     ret->wrapping = cfg[2].ival;
310     ret->barrier_probability = (float)atof(cfg[3].sval);
311     ret->unique = cfg[4].ival;
312
313     return ret;
314 }
315
316 static char *validate_params(const game_params *params, int full)
317 {
318     if (params->width <= 0 || params->height <= 0)
319         return "Width and height must both be greater than zero";
320     if (params->width <= 1 && params->height <= 1)
321         return "At least one of width and height must be greater than one";
322     if (params->barrier_probability < 0)
323         return "Barrier probability may not be negative";
324     if (params->barrier_probability > 1)
325         return "Barrier probability may not be greater than 1";
326
327     /*
328      * Specifying either grid dimension as 2 in a wrapping puzzle
329      * makes it actually impossible to ensure a unique puzzle
330      * solution.
331      * 
332      * Proof:
333      * 
334      * Without loss of generality, let us assume the puzzle _width_
335      * is 2, so we can conveniently discuss rows without having to
336      * say `rows/columns' all the time. (The height may be 2 as
337      * well, but that doesn't matter.)
338      * 
339      * In each row, there are two edges between tiles: the inner
340      * edge (running down the centre of the grid) and the outer
341      * edge (the identified left and right edges of the grid).
342      * 
343      * Lemma: In any valid 2xn puzzle there must be at least one
344      * row in which _exactly one_ of the inner edge and outer edge
345      * is connected.
346      * 
347      *   Proof: No row can have _both_ inner and outer edges
348      *   connected, because this would yield a loop. So the only
349      *   other way to falsify the lemma is for every row to have
350      *   _neither_ the inner nor outer edge connected. But this
351      *   means there is no connection at all between the left and
352      *   right columns of the puzzle, so there are two disjoint
353      *   subgraphs, which is also disallowed. []
354      * 
355      * Given such a row, it is always possible to make the
356      * disconnected edge connected and the connected edge
357      * disconnected without changing the state of any other edge.
358      * (This is easily seen by case analysis on the various tiles:
359      * left-pointing and right-pointing endpoints can be exchanged,
360      * likewise T-pieces, and a corner piece can select its
361      * horizontal connectivity independently of its vertical.) This
362      * yields a distinct valid solution.
363      * 
364      * Thus, for _every_ row in which exactly one of the inner and
365      * outer edge is connected, there are two valid states for that
366      * row, and hence the total number of solutions of the puzzle
367      * is at least 2^(number of such rows), and in particular is at
368      * least 2 since there must be at least one such row. []
369      */
370     if (full && params->unique && params->wrapping &&
371         (params->width == 2 || params->height == 2))
372         return "No wrapping puzzle with a width or height of 2 can have"
373         " a unique solution";
374
375     return NULL;
376 }
377
378 /* ----------------------------------------------------------------------
379  * Solver used to assure solution uniqueness during generation. 
380  */
381
382 /*
383  * Test cases I used while debugging all this were
384  * 
385  *   ./net --generate 1 13x11w#12300
386  * which expands under the non-unique grid generation rules to
387  *   13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
388  * and has two ambiguous areas.
389  * 
390  * An even better one is
391  *   13x11w#507896411361192
392  * which expands to
393  *   13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
394  * and has an ambiguous area _and_ a situation where loop avoidance
395  * is a necessary deductive technique.
396  * 
397  * Then there's
398  *   48x25w#820543338195187
399  * becoming
400  *   48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
401  * which has a spot (far right) where slightly more complex loop
402  * avoidance is required.
403  */
404
405 struct todo {
406     unsigned char *marked;
407     int *buffer;
408     int buflen;
409     int head, tail;
410 };
411
412 static struct todo *todo_new(int maxsize)
413 {
414     struct todo *todo = snew(struct todo);
415     todo->marked = snewn(maxsize, unsigned char);
416     memset(todo->marked, 0, maxsize);
417     todo->buflen = maxsize + 1;
418     todo->buffer = snewn(todo->buflen, int);
419     todo->head = todo->tail = 0;
420     return todo;
421 }
422
423 static void todo_free(struct todo *todo)
424 {
425     sfree(todo->marked);
426     sfree(todo->buffer);
427     sfree(todo);
428 }
429
430 static void todo_add(struct todo *todo, int index)
431 {
432     if (todo->marked[index])
433         return;                        /* already on the list */
434     todo->marked[index] = TRUE;
435     todo->buffer[todo->tail++] = index;
436     if (todo->tail == todo->buflen)
437         todo->tail = 0;
438 }
439
440 static int todo_get(struct todo *todo) {
441     int ret;
442
443     if (todo->head == todo->tail)
444         return -1;                     /* list is empty */
445     ret = todo->buffer[todo->head++];
446     if (todo->head == todo->buflen)
447         todo->head = 0;
448     todo->marked[ret] = FALSE;
449
450     return ret;
451 }
452
453 /*
454  * Return values: -1 means puzzle was proved inconsistent, 0 means we
455  * failed to narrow down to a unique solution, +1 means we solved it
456  * fully.
457  */
458 static int net_solver(int w, int h, unsigned char *tiles,
459                       unsigned char *barriers, int wrapping)
460 {
461     unsigned char *tilestate;
462     unsigned char *edgestate;
463     int *deadends;
464     int *equivalence;
465     struct todo *todo;
466     int i, j, x, y;
467     int area;
468     int done_something;
469
470     /*
471      * Set up the solver's data structures.
472      */
473     
474     /*
475      * tilestate stores the possible orientations of each tile.
476      * There are up to four of these, so we'll index the array in
477      * fours. tilestate[(y * w + x) * 4] and its three successive
478      * members give the possible orientations, clearing to 255 from
479      * the end as things are ruled out.
480      * 
481      * In this loop we also count up the area of the grid (which is
482      * not _necessarily_ equal to w*h, because there might be one
483      * or more blank squares present. This will never happen in a
484      * grid generated _by_ this program, but it's worth keeping the
485      * solver as general as possible.)
486      */
487     tilestate = snewn(w * h * 4, unsigned char);
488     area = 0;
489     for (i = 0; i < w*h; i++) {
490         tilestate[i * 4] = tiles[i] & 0xF;
491         for (j = 1; j < 4; j++) {
492             if (tilestate[i * 4 + j - 1] == 255 ||
493                 A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
494                 tilestate[i * 4 + j] = 255;
495             else
496                 tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
497         }
498         if (tiles[i] != 0)
499             area++;
500     }
501
502     /*
503      * edgestate stores the known state of each edge. It is 0 for
504      * unknown, 1 for open (connected) and 2 for closed (not
505      * connected).
506      * 
507      * In principle we need only worry about each edge once each,
508      * but in fact it's easier to track each edge twice so that we
509      * can reference it from either side conveniently. Also I'm
510      * going to allocate _five_ bytes per tile, rather than the
511      * obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
512      * where d is 1,2,4,8 and they never overlap.
513      */
514     edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
515     memset(edgestate, 0, (w * h - 1) * 5 + 9);
516
517     /*
518      * deadends tracks which edges have dead ends on them. It is
519      * indexed by tile and direction: deadends[(y*w+x) * 5 + d]
520      * tells you whether heading out of tile (x,y) in direction d
521      * can reach a limited amount of the grid. Values are area+1
522      * (no dead end known) or less than that (can reach _at most_
523      * this many other tiles by heading this way out of this tile).
524      */
525     deadends = snewn((w * h - 1) * 5 + 9, int);
526     for (i = 0; i < (w * h - 1) * 5 + 9; i++)
527         deadends[i] = area+1;
528
529     /*
530      * equivalence tracks which sets of tiles are known to be
531      * connected to one another, so we can avoid creating loops by
532      * linking together tiles which are already linked through
533      * another route.
534      * 
535      * This is a disjoint set forest structure: equivalence[i]
536      * contains the index of another member of the equivalence
537      * class containing i, or contains i itself for precisely one
538      * member in each such class. To find a representative member
539      * of the equivalence class containing i, you keep replacing i
540      * with equivalence[i] until it stops changing; then you go
541      * _back_ along the same path and point everything on it
542      * directly at the representative member so as to speed up
543      * future searches. Then you test equivalence between tiles by
544      * finding the representative of each tile and seeing if
545      * they're the same; and you create new equivalence (merge
546      * classes) by finding the representative of each tile and
547      * setting equivalence[one]=the_other.
548      */
549     equivalence = snew_dsf(w * h);
550
551     /*
552      * On a non-wrapping grid, we instantly know that all the edges
553      * round the edge are closed.
554      */
555     if (!wrapping) {
556         for (i = 0; i < w; i++) {
557             edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
558         }
559         for (i = 0; i < h; i++) {
560             edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
561         }
562     }
563
564     /*
565      * If we have barriers available, we can mark those edges as
566      * closed too.
567      */
568     if (barriers) {
569         for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
570             int d;
571             for (d = 1; d <= 8; d += d) {
572                 if (barriers[y*w+x] & d) {
573                     int x2, y2;
574                     /*
575                      * In principle the barrier list should already
576                      * contain each barrier from each side, but
577                      * let's not take chances with our internal
578                      * consistency.
579                      */
580                     OFFSETWH(x2, y2, x, y, d, w, h);
581                     edgestate[(y*w+x) * 5 + d] = 2;
582                     edgestate[(y2*w+x2) * 5 + F(d)] = 2;
583                 }
584             }
585         }
586     }
587
588     /*
589      * Since most deductions made by this solver are local (the
590      * exception is loop avoidance, where joining two tiles
591      * together on one side of the grid can theoretically permit a
592      * fresh deduction on the other), we can address the scaling
593      * problem inherent in iterating repeatedly over the entire
594      * grid by instead working with a to-do list.
595      */
596     todo = todo_new(w * h);
597
598     /*
599      * Main deductive loop.
600      */
601     done_something = TRUE;             /* prevent instant termination! */
602     while (1) {
603         int index;
604
605         /*
606          * Take a tile index off the todo list and process it.
607          */
608         index = todo_get(todo);
609         if (index == -1) {
610             /*
611              * If we have run out of immediate things to do, we
612              * have no choice but to scan the whole grid for
613              * longer-range things we've missed. Hence, I now add
614              * every square on the grid back on to the to-do list.
615              * I also set `done_something' to FALSE at this point;
616              * if we later come back here and find it still FALSE,
617              * we will know we've scanned the entire grid without
618              * finding anything new to do, and we can terminate.
619              */
620             if (!done_something)
621                 break;
622             for (i = 0; i < w*h; i++)
623                 todo_add(todo, i);
624             done_something = FALSE;
625
626             index = todo_get(todo);
627         }
628
629         y = index / w;
630         x = index % w;
631         {
632             int d, ourclass = dsf_canonify(equivalence, y*w+x);
633             int deadendmax[9];
634
635             deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
636
637             for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
638                 int valid;
639                 int nnondeadends, nondeadends[4], deadendtotal;
640                 int nequiv, equiv[5];
641                 int val = tilestate[(y*w+x) * 4 + i];
642
643                 valid = TRUE;
644                 nnondeadends = deadendtotal = 0;
645                 equiv[0] = ourclass;
646                 nequiv = 1;
647                 for (d = 1; d <= 8; d += d) {
648                     /*
649                      * Immediately rule out this orientation if it
650                      * conflicts with any known edge.
651                      */
652                     if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
653                         (edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
654                         valid = FALSE;
655
656                     if (val & d) {
657                         /*
658                          * Count up the dead-end statistics.
659                          */
660                         if (deadends[(y*w+x) * 5 + d] <= area) {
661                             deadendtotal += deadends[(y*w+x) * 5 + d];
662                         } else {
663                             nondeadends[nnondeadends++] = d;
664                         }
665
666                         /*
667                          * Ensure we aren't linking to any tiles,
668                          * through edges not already known to be
669                          * open, which create a loop.
670                          */
671                         if (edgestate[(y*w+x) * 5 + d] == 0) {
672                             int c, k, x2, y2;
673                             
674                             OFFSETWH(x2, y2, x, y, d, w, h);
675                             c = dsf_canonify(equivalence, y2*w+x2);
676                             for (k = 0; k < nequiv; k++)
677                                 if (c == equiv[k])
678                                     break;
679                             if (k == nequiv)
680                                 equiv[nequiv++] = c;
681                             else
682                                 valid = FALSE;
683                         }
684                     }
685                 }
686
687                 if (nnondeadends == 0) {
688                     /*
689                      * If this orientation links together dead-ends
690                      * with a total area of less than the entire
691                      * grid, it is invalid.
692                      *
693                      * (We add 1 to deadendtotal because of the
694                      * tile itself, of course; one tile linking
695                      * dead ends of size 2 and 3 forms a subnetwork
696                      * with a total area of 6, not 5.)
697                      */
698                     if (deadendtotal > 0 && deadendtotal+1 < area)
699                         valid = FALSE;
700                 } else if (nnondeadends == 1) {
701                     /*
702                      * If this orientation links together one or
703                      * more dead-ends with precisely one
704                      * non-dead-end, then we may have to mark that
705                      * non-dead-end as a dead end going the other
706                      * way. However, it depends on whether all
707                      * other orientations share the same property.
708                      */
709                     deadendtotal++;
710                     if (deadendmax[nondeadends[0]] < deadendtotal)
711                         deadendmax[nondeadends[0]] = deadendtotal;
712                 } else {
713                     /*
714                      * If this orientation links together two or
715                      * more non-dead-ends, then we can rule out the
716                      * possibility of putting in new dead-end
717                      * markings in those directions.
718                      */
719                     int k;
720                     for (k = 0; k < nnondeadends; k++)
721                         deadendmax[nondeadends[k]] = area+1;
722                 }
723
724                 if (valid)
725                     tilestate[(y*w+x) * 4 + j++] = val;
726 #ifdef SOLVER_DIAGNOSTICS
727                 else
728                     printf("ruling out orientation %x at %d,%d\n", val, x, y);
729 #endif
730             }
731
732             if (j == 0) {
733                 /* If we've ruled out all possible orientations for a
734                  * tile, then our puzzle has no solution at all. */
735                 return -1;
736             }
737
738             if (j < i) {
739                 done_something = TRUE;
740
741                 /*
742                  * We have ruled out at least one tile orientation.
743                  * Make sure the rest are blanked.
744                  */
745                 while (j < 4)
746                     tilestate[(y*w+x) * 4 + j++] = 255;
747             }
748
749             /*
750              * Now go through the tile orientations again and see
751              * if we've deduced anything new about any edges.
752              */
753             {
754                 int a, o;
755                 a = 0xF; o = 0;
756
757                 for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
758                     a &= tilestate[(y*w+x) * 4 + i];
759                     o |= tilestate[(y*w+x) * 4 + i];
760                 }
761                 for (d = 1; d <= 8; d += d)
762                     if (edgestate[(y*w+x) * 5 + d] == 0) {
763                         int x2, y2, d2;
764                         OFFSETWH(x2, y2, x, y, d, w, h);
765                         d2 = F(d);
766                         if (a & d) {
767                             /* This edge is open in all orientations. */
768 #ifdef SOLVER_DIAGNOSTICS
769                             printf("marking edge %d,%d:%d open\n", x, y, d);
770 #endif
771                             edgestate[(y*w+x) * 5 + d] = 1;
772                             edgestate[(y2*w+x2) * 5 + d2] = 1;
773                             dsf_merge(equivalence, y*w+x, y2*w+x2);
774                             done_something = TRUE;
775                             todo_add(todo, y2*w+x2);
776                         } else if (!(o & d)) {
777                             /* This edge is closed in all orientations. */
778 #ifdef SOLVER_DIAGNOSTICS
779                             printf("marking edge %d,%d:%d closed\n", x, y, d);
780 #endif
781                             edgestate[(y*w+x) * 5 + d] = 2;
782                             edgestate[(y2*w+x2) * 5 + d2] = 2;
783                             done_something = TRUE;
784                             todo_add(todo, y2*w+x2);
785                         }
786                     }
787
788             }
789
790             /*
791              * Now check the dead-end markers and see if any of
792              * them has lowered from the real ones.
793              */
794             for (d = 1; d <= 8; d += d) {
795                 int x2, y2, d2;
796                 OFFSETWH(x2, y2, x, y, d, w, h);
797                 d2 = F(d);
798                 if (deadendmax[d] > 0 &&
799                     deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
800 #ifdef SOLVER_DIAGNOSTICS
801                     printf("setting dead end value %d,%d:%d to %d\n",
802                            x2, y2, d2, deadendmax[d]);
803 #endif
804                     deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
805                     done_something = TRUE;
806                     todo_add(todo, y2*w+x2);
807                 }
808             }
809
810         }
811     }
812
813     /*
814      * Mark all completely determined tiles as locked.
815      */
816     j = +1;
817     for (i = 0; i < w*h; i++) {
818         if (tilestate[i * 4 + 1] == 255) {
819             assert(tilestate[i * 4 + 0] != 255);
820             tiles[i] = tilestate[i * 4] | LOCKED;
821         } else {
822             tiles[i] &= ~LOCKED;
823             j = 0;
824         }
825     }
826
827     /*
828      * Free up working space.
829      */
830     todo_free(todo);
831     sfree(tilestate);
832     sfree(edgestate);
833     sfree(deadends);
834     sfree(equivalence);
835
836     return j;
837 }
838
839 /* ----------------------------------------------------------------------
840  * Randomly select a new game description.
841  */
842
843 /*
844  * Function to randomly perturb an ambiguous section in a grid, to
845  * attempt to ensure unique solvability.
846  */
847 static void perturb(int w, int h, unsigned char *tiles, int wrapping,
848                     random_state *rs, int startx, int starty, int startd)
849 {
850     struct xyd *perimeter, *perim2, *loop[2], looppos[2];
851     int nperim, perimsize, nloop[2], loopsize[2];
852     int x, y, d, i;
853
854     /*
855      * We know that the tile at (startx,starty) is part of an
856      * ambiguous section, and we also know that its neighbour in
857      * direction startd is fully specified. We begin by tracing all
858      * the way round the ambiguous area.
859      */
860     nperim = perimsize = 0;
861     perimeter = NULL;
862     x = startx;
863     y = starty;
864     d = startd;
865 #ifdef PERTURB_DIAGNOSTICS
866     printf("perturb %d,%d:%d\n", x, y, d);
867 #endif
868     do {
869         int x2, y2, d2;
870
871         if (nperim >= perimsize) {
872             perimsize = perimsize * 3 / 2 + 32;
873             perimeter = sresize(perimeter, perimsize, struct xyd);
874         }
875         perimeter[nperim].x = x;
876         perimeter[nperim].y = y;
877         perimeter[nperim].direction = d;
878         nperim++;
879 #ifdef PERTURB_DIAGNOSTICS
880         printf("perimeter: %d,%d:%d\n", x, y, d);
881 #endif
882
883         /*
884          * First, see if we can simply turn left from where we are
885          * and find another locked square.
886          */
887         d2 = A(d);
888         OFFSETWH(x2, y2, x, y, d2, w, h);
889         if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
890             (tiles[y2*w+x2] & LOCKED)) {
891             d = d2;
892         } else {
893             /*
894              * Failing that, step left into the new square and look
895              * in front of us.
896              */
897             x = x2;
898             y = y2;
899             OFFSETWH(x2, y2, x, y, d, w, h);
900             if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
901                 !(tiles[y2*w+x2] & LOCKED)) {
902                 /*
903                  * And failing _that_, we're going to have to step
904                  * forward into _that_ square and look right at the
905                  * same locked square as we started with.
906                  */
907                 x = x2;
908                 y = y2;
909                 d = C(d);
910             }
911         }
912
913     } while (x != startx || y != starty || d != startd);
914
915     /*
916      * Our technique for perturbing this ambiguous area is to
917      * search round its edge for a join we can make: that is, an
918      * edge on the perimeter which is (a) not currently connected,
919      * and (b) connecting it would not yield a full cross on either
920      * side. Then we make that join, search round the network to
921      * find the loop thus constructed, and sever the loop at a
922      * randomly selected other point.
923      */
924     perim2 = snewn(nperim, struct xyd);
925     memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
926     /* Shuffle the perimeter, so as to search it without directional bias. */
927     shuffle(perim2, nperim, sizeof(*perim2), rs);
928     for (i = 0; i < nperim; i++) {
929         int x2, y2;
930
931         x = perim2[i].x;
932         y = perim2[i].y;
933         d = perim2[i].direction;
934
935         OFFSETWH(x2, y2, x, y, d, w, h);
936         if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
937             continue;            /* can't link across non-wrapping border */
938         if (tiles[y*w+x] & d)
939             continue;                  /* already linked in this direction! */
940         if (((tiles[y*w+x] | d) & 15) == 15)
941             continue;                  /* can't turn this tile into a cross */
942         if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
943             continue;                  /* can't turn other tile into a cross */
944
945         /*
946          * We've found the point at which we're going to make a new
947          * link.
948          */
949 #ifdef PERTURB_DIAGNOSTICS      
950         printf("linking %d,%d:%d\n", x, y, d);
951 #endif
952         tiles[y*w+x] |= d;
953         tiles[y2*w+x2] |= F(d);
954
955         break;
956     }
957     sfree(perim2);
958
959     if (i == nperim) {
960         sfree(perimeter);
961         return;                        /* nothing we can do! */
962     }
963
964     /*
965      * Now we've constructed a new link, we need to find the entire
966      * loop of which it is a part.
967      * 
968      * In principle, this involves doing a complete search round
969      * the network. However, I anticipate that in the vast majority
970      * of cases the loop will be quite small, so what I'm going to
971      * do is make _two_ searches round the network in parallel, one
972      * keeping its metaphorical hand on the left-hand wall while
973      * the other keeps its hand on the right. As soon as one of
974      * them gets back to its starting point, I abandon the other.
975      */
976     for (i = 0; i < 2; i++) {
977         loopsize[i] = nloop[i] = 0;
978         loop[i] = NULL;
979         looppos[i].x = x;
980         looppos[i].y = y;
981         looppos[i].direction = d;
982     }
983     while (1) {
984         for (i = 0; i < 2; i++) {
985             int x2, y2, j;
986
987             x = looppos[i].x;
988             y = looppos[i].y;
989             d = looppos[i].direction;
990
991             OFFSETWH(x2, y2, x, y, d, w, h);
992
993             /*
994              * Add this path segment to the loop, unless it exactly
995              * reverses the previous one on the loop in which case
996              * we take it away again.
997              */
998 #ifdef PERTURB_DIAGNOSTICS
999             printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);
1000 #endif
1001             if (nloop[i] > 0 &&
1002                 loop[i][nloop[i]-1].x == x2 &&
1003                 loop[i][nloop[i]-1].y == y2 &&
1004                 loop[i][nloop[i]-1].direction == F(d)) {
1005 #ifdef PERTURB_DIAGNOSTICS
1006                 printf("removing path segment %d,%d:%d from loop[%d]\n",
1007                        x2, y2, F(d), i);
1008 #endif
1009                 nloop[i]--;
1010             } else {
1011                 if (nloop[i] >= loopsize[i]) {
1012                     loopsize[i] = loopsize[i] * 3 / 2 + 32;
1013                     loop[i] = sresize(loop[i], loopsize[i], struct xyd);
1014                 }
1015 #ifdef PERTURB_DIAGNOSTICS
1016                 printf("adding path segment %d,%d:%d to loop[%d]\n",
1017                        x, y, d, i);
1018 #endif
1019                 loop[i][nloop[i]++] = looppos[i];
1020             }
1021
1022 #ifdef PERTURB_DIAGNOSTICS
1023             printf("tile at new location is %x\n", tiles[y2*w+x2] & 0xF);
1024 #endif
1025             d = F(d);
1026             for (j = 0; j < 4; j++) {
1027                 if (i == 0)
1028                     d = A(d);
1029                 else
1030                     d = C(d);
1031 #ifdef PERTURB_DIAGNOSTICS
1032                 printf("trying dir %d\n", d);
1033 #endif
1034                 if (tiles[y2*w+x2] & d) {
1035                     looppos[i].x = x2;
1036                     looppos[i].y = y2;
1037                     looppos[i].direction = d;
1038                     break;
1039                 }
1040             }
1041
1042             assert(j < 4);
1043             assert(nloop[i] > 0);
1044
1045             if (looppos[i].x == loop[i][0].x &&
1046                 looppos[i].y == loop[i][0].y &&
1047                 looppos[i].direction == loop[i][0].direction) {
1048 #ifdef PERTURB_DIAGNOSTICS
1049                 printf("loop %d finished tracking\n", i);
1050 #endif
1051
1052                 /*
1053                  * Having found our loop, we now sever it at a
1054                  * randomly chosen point - absolutely any will do -
1055                  * which is not the one we joined it at to begin
1056                  * with. Conveniently, the one we joined it at is
1057                  * loop[i][0], so we just avoid that one.
1058                  */
1059                 j = random_upto(rs, nloop[i]-1) + 1;
1060                 x = loop[i][j].x;
1061                 y = loop[i][j].y;
1062                 d = loop[i][j].direction;
1063                 OFFSETWH(x2, y2, x, y, d, w, h);
1064                 tiles[y*w+x] &= ~d;
1065                 tiles[y2*w+x2] &= ~F(d);
1066
1067                 break;
1068             }
1069         }
1070         if (i < 2)
1071             break;
1072     }
1073     sfree(loop[0]);
1074     sfree(loop[1]);
1075
1076     /*
1077      * Finally, we must mark the entire disputed section as locked,
1078      * to prevent the perturb function being called on it multiple
1079      * times.
1080      * 
1081      * To do this, we _sort_ the perimeter of the area. The
1082      * existing xyd_cmp function will arrange things into columns
1083      * for us, in such a way that each column has the edges in
1084      * vertical order. Then we can work down each column and fill
1085      * in all the squares between an up edge and a down edge.
1086      */
1087     qsort(perimeter, nperim, sizeof(struct xyd), xyd_cmp);
1088     x = y = -1;
1089     for (i = 0; i <= nperim; i++) {
1090         if (i == nperim || perimeter[i].x > x) {
1091             /*
1092              * Fill in everything from the last Up edge to the
1093              * bottom of the grid, if necessary.
1094              */
1095             if (x != -1) {
1096                 while (y < h) {
1097 #ifdef PERTURB_DIAGNOSTICS
1098                     printf("resolved: locking tile %d,%d\n", x, y);
1099 #endif
1100                     tiles[y * w + x] |= LOCKED;
1101                     y++;
1102                 }
1103                 x = y = -1;
1104             }
1105
1106             if (i == nperim)
1107                 break;
1108
1109             x = perimeter[i].x;
1110             y = 0;
1111         }
1112
1113         if (perimeter[i].direction == U) {
1114             x = perimeter[i].x;
1115             y = perimeter[i].y;
1116         } else if (perimeter[i].direction == D) {
1117             /*
1118              * Fill in everything from the last Up edge to here.
1119              */
1120             assert(x == perimeter[i].x && y <= perimeter[i].y);
1121             while (y <= perimeter[i].y) {
1122 #ifdef PERTURB_DIAGNOSTICS
1123                 printf("resolved: locking tile %d,%d\n", x, y);
1124 #endif
1125                 tiles[y * w + x] |= LOCKED;
1126                 y++;
1127             }
1128             x = y = -1;
1129         }
1130     }
1131
1132     sfree(perimeter);
1133 }
1134
1135 static int *compute_loops_inner(int w, int h, int wrapping,
1136                                 const unsigned char *tiles,
1137                                 const unsigned char *barriers);
1138
1139 static char *new_game_desc(const game_params *params, random_state *rs,
1140                            char **aux, int interactive)
1141 {
1142     tree234 *possibilities, *barriertree;
1143     int w, h, x, y, cx, cy, nbarriers;
1144     unsigned char *tiles, *barriers;
1145     char *desc, *p;
1146
1147     w = params->width;
1148     h = params->height;
1149
1150     cx = w / 2;
1151     cy = h / 2;
1152
1153     tiles = snewn(w * h, unsigned char);
1154     barriers = snewn(w * h, unsigned char);
1155
1156     begin_generation:
1157
1158     memset(tiles, 0, w * h);
1159     memset(barriers, 0, w * h);
1160
1161     /*
1162      * Construct the unshuffled grid.
1163      * 
1164      * To do this, we simply start at the centre point, repeatedly
1165      * choose a random possibility out of the available ways to
1166      * extend a used square into an unused one, and do it. After
1167      * extending the third line out of a square, we remove the
1168      * fourth from the possibilities list to avoid any full-cross
1169      * squares (which would make the game too easy because they
1170      * only have one orientation).
1171      * 
1172      * The slightly worrying thing is the avoidance of full-cross
1173      * squares. Can this cause our unsophisticated construction
1174      * algorithm to paint itself into a corner, by getting into a
1175      * situation where there are some unreached squares and the
1176      * only way to reach any of them is to extend a T-piece into a
1177      * full cross?
1178      * 
1179      * Answer: no it can't, and here's a proof.
1180      * 
1181      * Any contiguous group of such unreachable squares must be
1182      * surrounded on _all_ sides by T-pieces pointing away from the
1183      * group. (If not, then there is a square which can be extended
1184      * into one of the `unreachable' ones, and so it wasn't
1185      * unreachable after all.) In particular, this implies that
1186      * each contiguous group of unreachable squares must be
1187      * rectangular in shape (any deviation from that yields a
1188      * non-T-piece next to an `unreachable' square).
1189      * 
1190      * So we have a rectangle of unreachable squares, with T-pieces
1191      * forming a solid border around the rectangle. The corners of
1192      * that border must be connected (since every tile connects all
1193      * the lines arriving in it), and therefore the border must
1194      * form a closed loop around the rectangle.
1195      * 
1196      * But this can't have happened in the first place, since we
1197      * _know_ we've avoided creating closed loops! Hence, no such
1198      * situation can ever arise, and the naive grid construction
1199      * algorithm will guaranteeably result in a complete grid
1200      * containing no unreached squares, no full crosses _and_ no
1201      * closed loops. []
1202      */
1203     possibilities = newtree234(xyd_cmp_nc);
1204
1205     if (cx+1 < w)
1206         add234(possibilities, new_xyd(cx, cy, R));
1207     if (cy-1 >= 0)
1208         add234(possibilities, new_xyd(cx, cy, U));
1209     if (cx-1 >= 0)
1210         add234(possibilities, new_xyd(cx, cy, L));
1211     if (cy+1 < h)
1212         add234(possibilities, new_xyd(cx, cy, D));
1213
1214     while (count234(possibilities) > 0) {
1215         int i;
1216         struct xyd *xyd;
1217         int x1, y1, d1, x2, y2, d2, d;
1218
1219         /*
1220          * Extract a randomly chosen possibility from the list.
1221          */
1222         i = random_upto(rs, count234(possibilities));
1223         xyd = delpos234(possibilities, i);
1224         x1 = xyd->x;
1225         y1 = xyd->y;
1226         d1 = xyd->direction;
1227         sfree(xyd);
1228
1229         OFFSET(x2, y2, x1, y1, d1, params);
1230         d2 = F(d1);
1231 #ifdef GENERATION_DIAGNOSTICS
1232         printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
1233                x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
1234 #endif
1235
1236         /*
1237          * Make the connection. (We should be moving to an as yet
1238          * unused tile.)
1239          */
1240         index(params, tiles, x1, y1) |= d1;
1241         assert(index(params, tiles, x2, y2) == 0);
1242         index(params, tiles, x2, y2) |= d2;
1243
1244         /*
1245          * If we have created a T-piece, remove its last
1246          * possibility.
1247          */
1248         if (COUNT(index(params, tiles, x1, y1)) == 3) {
1249             struct xyd xyd1, *xydp;
1250
1251             xyd1.x = x1;
1252             xyd1.y = y1;
1253             xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
1254
1255             xydp = find234(possibilities, &xyd1, NULL);
1256
1257             if (xydp) {
1258 #ifdef GENERATION_DIAGNOSTICS
1259                 printf("T-piece; removing (%d,%d,%c)\n",
1260                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1261 #endif
1262                 del234(possibilities, xydp);
1263                 sfree(xydp);
1264             }
1265         }
1266
1267         /*
1268          * Remove all other possibilities that were pointing at the
1269          * tile we've just moved into.
1270          */
1271         for (d = 1; d < 0x10; d <<= 1) {
1272             int x3, y3, d3;
1273             struct xyd xyd1, *xydp;
1274
1275             OFFSET(x3, y3, x2, y2, d, params);
1276             d3 = F(d);
1277
1278             xyd1.x = x3;
1279             xyd1.y = y3;
1280             xyd1.direction = d3;
1281
1282             xydp = find234(possibilities, &xyd1, NULL);
1283
1284             if (xydp) {
1285 #ifdef GENERATION_DIAGNOSTICS
1286                 printf("Loop avoidance; removing (%d,%d,%c)\n",
1287                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1288 #endif
1289                 del234(possibilities, xydp);
1290                 sfree(xydp);
1291             }
1292         }
1293
1294         /*
1295          * Add new possibilities to the list for moving _out_ of
1296          * the tile we have just moved into.
1297          */
1298         for (d = 1; d < 0x10; d <<= 1) {
1299             int x3, y3;
1300
1301             if (d == d2)
1302                 continue;              /* we've got this one already */
1303
1304             if (!params->wrapping) {
1305                 if (d == U && y2 == 0)
1306                     continue;
1307                 if (d == D && y2 == h-1)
1308                     continue;
1309                 if (d == L && x2 == 0)
1310                     continue;
1311                 if (d == R && x2 == w-1)
1312                     continue;
1313             }
1314
1315             OFFSET(x3, y3, x2, y2, d, params);
1316
1317             if (index(params, tiles, x3, y3))
1318                 continue;              /* this would create a loop */
1319
1320 #ifdef GENERATION_DIAGNOSTICS
1321             printf("New frontier; adding (%d,%d,%c)\n",
1322                    x2, y2, "0RU3L567D9abcdef"[d]);
1323 #endif
1324             add234(possibilities, new_xyd(x2, y2, d));
1325         }
1326     }
1327     /* Having done that, we should have no possibilities remaining. */
1328     assert(count234(possibilities) == 0);
1329     freetree234(possibilities);
1330
1331     if (params->unique) {
1332         int prevn = -1;
1333
1334         /*
1335          * Run the solver to check unique solubility.
1336          */
1337         while (net_solver(w, h, tiles, NULL, params->wrapping) != 1) {
1338             int n = 0;
1339
1340             /*
1341              * We expect (in most cases) that most of the grid will
1342              * be uniquely specified already, and the remaining
1343              * ambiguous sections will be small and separate. So
1344              * our strategy is to find each individual such
1345              * section, and perform a perturbation on the network
1346              * in that area.
1347              */
1348             for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1349                 if (x+1 < w && ((tiles[y*w+x] ^ tiles[y*w+x+1]) & LOCKED)) {
1350                     n++;
1351                     if (tiles[y*w+x] & LOCKED)
1352                         perturb(w, h, tiles, params->wrapping, rs, x+1, y, L);
1353                     else
1354                         perturb(w, h, tiles, params->wrapping, rs, x, y, R);
1355                 }
1356                 if (y+1 < h && ((tiles[y*w+x] ^ tiles[(y+1)*w+x]) & LOCKED)) {
1357                     n++;
1358                     if (tiles[y*w+x] & LOCKED)
1359                         perturb(w, h, tiles, params->wrapping, rs, x, y+1, U);
1360                     else
1361                         perturb(w, h, tiles, params->wrapping, rs, x, y, D);
1362                 }
1363             }
1364
1365             /*
1366              * Now n counts the number of ambiguous sections we
1367              * have fiddled with. If we haven't managed to decrease
1368              * it from the last time we ran the solver, give up and
1369              * regenerate the entire grid.
1370              */
1371             if (prevn != -1 && prevn <= n)
1372                 goto begin_generation; /* (sorry) */
1373
1374             prevn = n;
1375         }
1376
1377         /*
1378          * The solver will have left a lot of LOCKED bits lying
1379          * around in the tiles array. Remove them.
1380          */
1381         for (x = 0; x < w*h; x++)
1382             tiles[x] &= ~LOCKED;
1383     }
1384
1385     /*
1386      * Now compute a list of the possible barrier locations.
1387      */
1388     barriertree = newtree234(xyd_cmp_nc);
1389     for (y = 0; y < h; y++) {
1390         for (x = 0; x < w; x++) {
1391
1392             if (!(index(params, tiles, x, y) & R) &&
1393                 (params->wrapping || x < w-1))
1394                 add234(barriertree, new_xyd(x, y, R));
1395             if (!(index(params, tiles, x, y) & D) &&
1396                 (params->wrapping || y < h-1))
1397                 add234(barriertree, new_xyd(x, y, D));
1398         }
1399     }
1400
1401     /*
1402      * Save the unshuffled grid in aux.
1403      */
1404     {
1405         char *solution;
1406         int i;
1407
1408         solution = snewn(w * h + 1, char);
1409         for (i = 0; i < w * h; i++)
1410             solution[i] = "0123456789abcdef"[tiles[i] & 0xF];
1411         solution[w*h] = '\0';
1412
1413         *aux = solution;
1414     }
1415
1416     /*
1417      * Now shuffle the grid.
1418      * 
1419      * In order to avoid accidentally generating an already-solved
1420      * grid, we will reshuffle as necessary to ensure that at least
1421      * one edge has a mismatched connection.
1422      *
1423      * This can always be done, since validate_params() enforces a
1424      * grid area of at least 2 and our generator never creates
1425      * either type of rotationally invariant tile (cross and
1426      * blank). Hence there must be at least one edge separating
1427      * distinct tiles, and it must be possible to find orientations
1428      * of those tiles such that one tile is trying to connect
1429      * through that edge and the other is not.
1430      * 
1431      * (We could be more subtle, and allow the shuffle to generate
1432      * a grid in which all tiles match up locally and the only
1433      * criterion preventing the grid from being already solved is
1434      * connectedness. However, that would take more effort, and
1435      * it's easier to simply make sure every grid is _obviously_
1436      * not solved.)
1437      *
1438      * We also require that our shuffle produces no loops in the
1439      * initial grid state, because it's a bit rude to light up a 'HEY,
1440      * YOU DID SOMETHING WRONG!' indicator when the user hasn't even
1441      * had a chance to do _anything_ yet. This also is possible just
1442      * by retrying the whole shuffle on failure, because it's clear
1443      * that at least one non-solved shuffle with no loops must exist.
1444      * (Proof: take the _solved_ state of the puzzle, and rotate one
1445      * endpoint.)
1446      */
1447     while (1) {
1448         int mismatches, prev_loopsquares, this_loopsquares, i;
1449         int *loops;
1450
1451       shuffle:
1452         for (y = 0; y < h; y++) {
1453             for (x = 0; x < w; x++) {
1454                 int orig = index(params, tiles, x, y);
1455                 int rot = random_upto(rs, 4);
1456                 index(params, tiles, x, y) = ROT(orig, rot);
1457             }
1458         }
1459
1460         /*
1461          * Check for loops, and try to fix them by reshuffling just
1462          * the squares involved.
1463          */
1464         prev_loopsquares = w*h+1;
1465         while (1) {
1466             loops = compute_loops_inner(w, h, params->wrapping, tiles, NULL);
1467             this_loopsquares = 0;
1468             for (i = 0; i < w*h; i++) {
1469                 if (loops[i]) {
1470                     int orig = tiles[i];
1471                     int rot = random_upto(rs, 4);
1472                     tiles[i] = ROT(orig, rot);
1473                     this_loopsquares++;
1474                 }
1475             }
1476             sfree(loops);
1477             if (this_loopsquares > prev_loopsquares) {
1478                 /*
1479                  * We're increasing rather than reducing the number of
1480                  * loops. Give up and go back to the full shuffle.
1481                  */
1482                 goto shuffle;
1483             }
1484             if (this_loopsquares == 0)
1485                 break;
1486             prev_loopsquares = this_loopsquares;
1487         }
1488
1489         mismatches = 0;
1490         /*
1491          * I can't even be bothered to check for mismatches across
1492          * a wrapping edge, so I'm just going to enforce that there
1493          * must be a mismatch across a non-wrapping edge, which is
1494          * still always possible.
1495          */
1496         for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1497             if (x+1 < w && ((ROT(index(params, tiles, x, y), 2) ^ 
1498                              index(params, tiles, x+1, y)) & L))
1499                 mismatches++;
1500             if (y+1 < h && ((ROT(index(params, tiles, x, y), 2) ^ 
1501                              index(params, tiles, x, y+1)) & U))
1502                 mismatches++;
1503         }
1504
1505         if (mismatches == 0)
1506             continue;
1507
1508         /* OK. */
1509         break;
1510     }
1511
1512     /*
1513      * And now choose barrier locations. (We carefully do this
1514      * _after_ shuffling, so that changing the barrier rate in the
1515      * params while keeping the random seed the same will give the
1516      * same shuffled grid and _only_ change the barrier locations.
1517      * Also the way we choose barrier locations, by repeatedly
1518      * choosing one possibility from the list until we have enough,
1519      * is designed to ensure that raising the barrier rate while
1520      * keeping the seed the same will provide a superset of the
1521      * previous barrier set - i.e. if you ask for 10 barriers, and
1522      * then decide that's still too hard and ask for 20, you'll get
1523      * the original 10 plus 10 more, rather than getting 20 new
1524      * ones and the chance of remembering your first 10.)
1525      */
1526     nbarriers = (int)(params->barrier_probability * count234(barriertree));
1527     assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
1528
1529     while (nbarriers > 0) {
1530         int i;
1531         struct xyd *xyd;
1532         int x1, y1, d1, x2, y2, d2;
1533
1534         /*
1535          * Extract a randomly chosen barrier from the list.
1536          */
1537         i = random_upto(rs, count234(barriertree));
1538         xyd = delpos234(barriertree, i);
1539
1540         assert(xyd != NULL);
1541
1542         x1 = xyd->x;
1543         y1 = xyd->y;
1544         d1 = xyd->direction;
1545         sfree(xyd);
1546
1547         OFFSET(x2, y2, x1, y1, d1, params);
1548         d2 = F(d1);
1549
1550         index(params, barriers, x1, y1) |= d1;
1551         index(params, barriers, x2, y2) |= d2;
1552
1553         nbarriers--;
1554     }
1555
1556     /*
1557      * Clean up the rest of the barrier list.
1558      */
1559     {
1560         struct xyd *xyd;
1561
1562         while ( (xyd = delpos234(barriertree, 0)) != NULL)
1563             sfree(xyd);
1564
1565         freetree234(barriertree);
1566     }
1567
1568     /*
1569      * Finally, encode the grid into a string game description.
1570      * 
1571      * My syntax is extremely simple: each square is encoded as a
1572      * hex digit in which bit 0 means a connection on the right,
1573      * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
1574      * encoding as used internally). Each digit is followed by
1575      * optional barrier indicators: `v' means a vertical barrier to
1576      * the right of it, and `h' means a horizontal barrier below
1577      * it.
1578      */
1579     desc = snewn(w * h * 3 + 1, char);
1580     p = desc;
1581     for (y = 0; y < h; y++) {
1582         for (x = 0; x < w; x++) {
1583             *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
1584             if ((params->wrapping || x < w-1) &&
1585                 (index(params, barriers, x, y) & R))
1586                 *p++ = 'v';
1587             if ((params->wrapping || y < h-1) &&
1588                 (index(params, barriers, x, y) & D))
1589                 *p++ = 'h';
1590         }
1591     }
1592     assert(p - desc <= w*h*3);
1593     *p = '\0';
1594
1595     sfree(tiles);
1596     sfree(barriers);
1597
1598     return desc;
1599 }
1600
1601 static char *validate_desc(const game_params *params, const char *desc)
1602 {
1603     int w = params->width, h = params->height;
1604     int i;
1605
1606     for (i = 0; i < w*h; i++) {
1607         if (*desc >= '0' && *desc <= '9')
1608             /* OK */;
1609         else if (*desc >= 'a' && *desc <= 'f')
1610             /* OK */;
1611         else if (*desc >= 'A' && *desc <= 'F')
1612             /* OK */;
1613         else if (!*desc)
1614             return "Game description shorter than expected";
1615         else
1616             return "Game description contained unexpected character";
1617         desc++;
1618         while (*desc == 'h' || *desc == 'v')
1619             desc++;
1620     }
1621     if (*desc)
1622         return "Game description longer than expected";
1623
1624     return NULL;
1625 }
1626
1627 /* ----------------------------------------------------------------------
1628  * Construct an initial game state, given a description and parameters.
1629  */
1630
1631 static game_state *new_game(midend *me, const game_params *params,
1632                             const char *desc)
1633 {
1634     game_state *state;
1635     int w, h, x, y;
1636
1637     assert(params->width > 0 && params->height > 0);
1638     assert(params->width > 1 || params->height > 1);
1639
1640     /*
1641      * Create a blank game state.
1642      */
1643     state = snew(game_state);
1644     w = state->width = params->width;
1645     h = state->height = params->height;
1646     state->wrapping = params->wrapping;
1647     state->imm = snew(game_immutable_state);
1648     state->imm->refcount = 1;
1649     state->last_rotate_dir = state->last_rotate_x = state->last_rotate_y = 0;
1650     state->completed = state->used_solve = FALSE;
1651     state->tiles = snewn(state->width * state->height, unsigned char);
1652     memset(state->tiles, 0, state->width * state->height);
1653     state->imm->barriers = snewn(state->width * state->height, unsigned char);
1654     memset(state->imm->barriers, 0, state->width * state->height);
1655
1656     /*
1657      * Parse the game description into the grid.
1658      */
1659     for (y = 0; y < h; y++) {
1660         for (x = 0; x < w; x++) {
1661             if (*desc >= '0' && *desc <= '9')
1662                 tile(state, x, y) = *desc - '0';
1663             else if (*desc >= 'a' && *desc <= 'f')
1664                 tile(state, x, y) = *desc - 'a' + 10;
1665             else if (*desc >= 'A' && *desc <= 'F')
1666                 tile(state, x, y) = *desc - 'A' + 10;
1667             if (*desc)
1668                 desc++;
1669             while (*desc == 'h' || *desc == 'v') {
1670                 int x2, y2, d1, d2;
1671                 if (*desc == 'v')
1672                     d1 = R;
1673                 else
1674                     d1 = D;
1675
1676                 OFFSET(x2, y2, x, y, d1, state);
1677                 d2 = F(d1);
1678
1679                 barrier(state, x, y) |= d1;
1680                 barrier(state, x2, y2) |= d2;
1681
1682                 desc++;
1683             }
1684         }
1685     }
1686
1687     /*
1688      * Set up border barriers if this is a non-wrapping game.
1689      */
1690     if (!state->wrapping) {
1691         for (x = 0; x < state->width; x++) {
1692             barrier(state, x, 0) |= U;
1693             barrier(state, x, state->height-1) |= D;
1694         }
1695         for (y = 0; y < state->height; y++) {
1696             barrier(state, 0, y) |= L;
1697             barrier(state, state->width-1, y) |= R;
1698         }
1699     } else {
1700         /*
1701          * We check whether this is de-facto a non-wrapping game
1702          * despite the parameters, in case we were passed the
1703          * description of a non-wrapping game. This is so that we
1704          * can change some aspects of the UI behaviour.
1705          */
1706         state->wrapping = FALSE;
1707         for (x = 0; x < state->width; x++)
1708             if (!(barrier(state, x, 0) & U) ||
1709                 !(barrier(state, x, state->height-1) & D))
1710                 state->wrapping = TRUE;
1711         for (y = 0; y < state->height; y++)
1712             if (!(barrier(state, 0, y) & L) ||
1713                 !(barrier(state, state->width-1, y) & R))
1714                 state->wrapping = TRUE;
1715     }
1716
1717     return state;
1718 }
1719
1720 static game_state *dup_game(const game_state *state)
1721 {
1722     game_state *ret;
1723
1724     ret = snew(game_state);
1725     ret->imm = state->imm;
1726     ret->imm->refcount++;
1727     ret->width = state->width;
1728     ret->height = state->height;
1729     ret->wrapping = state->wrapping;
1730     ret->completed = state->completed;
1731     ret->used_solve = state->used_solve;
1732     ret->last_rotate_dir = state->last_rotate_dir;
1733     ret->last_rotate_x = state->last_rotate_x;
1734     ret->last_rotate_y = state->last_rotate_y;
1735     ret->tiles = snewn(state->width * state->height, unsigned char);
1736     memcpy(ret->tiles, state->tiles, state->width * state->height);
1737
1738     return ret;
1739 }
1740
1741 static void free_game(game_state *state)
1742 {
1743     if (--state->imm->refcount == 0) {
1744         sfree(state->imm->barriers);
1745         sfree(state->imm);
1746     }
1747     sfree(state->tiles);
1748     sfree(state);
1749 }
1750
1751 static char *solve_game(const game_state *state, const game_state *currstate,
1752                         const char *aux, char **error)
1753 {
1754     unsigned char *tiles;
1755     char *ret;
1756     int retlen, retsize;
1757     int i;
1758
1759     tiles = snewn(state->width * state->height, unsigned char);
1760
1761     if (!aux) {
1762         /*
1763          * Run the internal solver on the provided grid. This might
1764          * not yield a complete solution.
1765          */
1766         int solver_result;
1767
1768         memcpy(tiles, state->tiles, state->width * state->height);
1769         solver_result = net_solver(state->width, state->height, tiles,
1770                                    state->imm->barriers, state->wrapping);
1771
1772         if (solver_result < 0) {
1773             *error = "No solution exists for this puzzle";
1774             sfree(tiles);
1775             return NULL;
1776         }
1777     } else {
1778         for (i = 0; i < state->width * state->height; i++) {
1779             int c = aux[i];
1780
1781             if (c >= '0' && c <= '9')
1782                 tiles[i] = c - '0';
1783             else if (c >= 'a' && c <= 'f')
1784                 tiles[i] = c - 'a' + 10;
1785             else if (c >= 'A' && c <= 'F')
1786                 tiles[i] = c - 'A' + 10;
1787
1788             tiles[i] |= LOCKED;
1789         }
1790     }
1791
1792     /*
1793      * Now construct a string which can be passed to execute_move()
1794      * to transform the current grid into the solved one.
1795      */
1796     retsize = 256;
1797     ret = snewn(retsize, char);
1798     retlen = 0;
1799     ret[retlen++] = 'S';
1800
1801     for (i = 0; i < state->width * state->height; i++) {
1802         int from = currstate->tiles[i], to = tiles[i];
1803         int ft = from & (R|L|U|D), tt = to & (R|L|U|D);
1804         int x = i % state->width, y = i / state->width;
1805         int chr = '\0';
1806         char buf[80], *p = buf;
1807
1808         if (from == to)
1809             continue;                  /* nothing needs doing at all */
1810
1811         /*
1812          * To transform this tile into the desired tile: first
1813          * unlock the tile if it's locked, then rotate it if
1814          * necessary, then lock it if necessary.
1815          */
1816         if (from & LOCKED)
1817             p += sprintf(p, ";L%d,%d", x, y);
1818
1819         if (tt == A(ft))
1820             chr = 'A';
1821         else if (tt == C(ft))
1822             chr = 'C';
1823         else if (tt == F(ft))
1824             chr = 'F';
1825         else {
1826             assert(tt == ft);
1827             chr = '\0';
1828         }
1829         if (chr)
1830             p += sprintf(p, ";%c%d,%d", chr, x, y);
1831
1832         if (to & LOCKED)
1833             p += sprintf(p, ";L%d,%d", x, y);
1834
1835         if (p > buf) {
1836             if (retlen + (p - buf) >= retsize) {
1837                 retsize = retlen + (p - buf) + 512;
1838                 ret = sresize(ret, retsize, char);
1839             }
1840             memcpy(ret+retlen, buf, p - buf);
1841             retlen += p - buf;
1842         }
1843     }
1844
1845     assert(retlen < retsize);
1846     ret[retlen] = '\0';
1847     ret = sresize(ret, retlen+1, char);
1848
1849     sfree(tiles);
1850
1851     return ret;
1852 }
1853
1854 static int game_can_format_as_text_now(const game_params *params)
1855 {
1856     return TRUE;
1857 }
1858
1859 static char *game_text_format(const game_state *state)
1860 {
1861     return NULL;
1862 }
1863
1864 /* ----------------------------------------------------------------------
1865  * Utility routine.
1866  */
1867
1868 /*
1869  * Compute which squares are reachable from the centre square, as a
1870  * quick visual aid to determining how close the game is to
1871  * completion. This is also a simple way to tell if the game _is_
1872  * completed - just call this function and see whether every square
1873  * is marked active.
1874  */
1875 static unsigned char *compute_active(const game_state *state, int cx, int cy)
1876 {
1877     unsigned char *active;
1878     tree234 *todo;
1879     struct xyd *xyd;
1880
1881     active = snewn(state->width * state->height, unsigned char);
1882     memset(active, 0, state->width * state->height);
1883
1884     /*
1885      * We only store (x,y) pairs in todo, but it's easier to reuse
1886      * xyd_cmp and just store direction 0 every time.
1887      */
1888     todo = newtree234(xyd_cmp_nc);
1889     index(state, active, cx, cy) = ACTIVE;
1890     add234(todo, new_xyd(cx, cy, 0));
1891
1892     while ( (xyd = delpos234(todo, 0)) != NULL) {
1893         int x1, y1, d1, x2, y2, d2;
1894
1895         x1 = xyd->x;
1896         y1 = xyd->y;
1897         sfree(xyd);
1898
1899         for (d1 = 1; d1 < 0x10; d1 <<= 1) {
1900             OFFSET(x2, y2, x1, y1, d1, state);
1901             d2 = F(d1);
1902
1903             /*
1904              * If the next tile in this direction is connected to
1905              * us, and there isn't a barrier in the way, and it
1906              * isn't already marked active, then mark it active and
1907              * add it to the to-examine list.
1908              */
1909             if ((tile(state, x1, y1) & d1) &&
1910                 (tile(state, x2, y2) & d2) &&
1911                 !(barrier(state, x1, y1) & d1) &&
1912                 !index(state, active, x2, y2)) {
1913                 index(state, active, x2, y2) = ACTIVE;
1914                 add234(todo, new_xyd(x2, y2, 0));
1915             }
1916         }
1917     }
1918     /* Now we expect the todo list to have shrunk to zero size. */
1919     assert(count234(todo) == 0);
1920     freetree234(todo);
1921
1922     return active;
1923 }
1924
1925 struct net_neighbour_ctx {
1926     int w, h;
1927     const unsigned char *tiles, *barriers;
1928     int i, n, neighbours[4];
1929 };
1930 static int net_neighbour(int vertex, void *vctx)
1931 {
1932     struct net_neighbour_ctx *ctx = (struct net_neighbour_ctx *)vctx;
1933
1934     if (vertex >= 0) {
1935         int x = vertex % ctx->w, y = vertex / ctx->w;
1936         int tile, dir, x1, y1, v1;
1937
1938         ctx->i = ctx->n = 0;
1939
1940         tile = ctx->tiles[vertex];
1941         if (ctx->barriers)
1942             tile &= ~ctx->barriers[vertex];
1943
1944         for (dir = 1; dir < 0x10; dir <<= 1) {
1945             if (!(tile & dir))
1946                 continue;
1947             OFFSETWH(x1, y1, x, y, dir, ctx->w, ctx->h);
1948             v1 = y1 * ctx->w + x1;
1949             if (ctx->tiles[v1] & F(dir))
1950                 ctx->neighbours[ctx->n++] = v1;
1951         }
1952     }
1953
1954     if (ctx->i < ctx->n)
1955         return ctx->neighbours[ctx->i++];
1956     else
1957         return -1;
1958 }
1959
1960 static int *compute_loops_inner(int w, int h, int wrapping,
1961                                 const unsigned char *tiles,
1962                                 const unsigned char *barriers)
1963 {
1964     struct net_neighbour_ctx ctx;
1965     struct findloopstate *fls;
1966     int *loops;
1967     int x, y;
1968
1969     fls = findloop_new_state(w*h);
1970     ctx.w = w;
1971     ctx.h = h;
1972     ctx.tiles = tiles;
1973     ctx.barriers = barriers;
1974     findloop_run(fls, w*h, net_neighbour, &ctx);
1975
1976     loops = snewn(w*h, int);
1977
1978     for (y = 0; y < h; y++) {
1979         for (x = 0; x < w; x++) {
1980             int x1, y1, dir;
1981             int flags = 0;
1982
1983             for (dir = 1; dir < 0x10; dir <<= 1) {
1984                 if ((tiles[y*w+x] & dir) &&
1985                     !(barriers && (barriers[y*w+x] & dir))) {
1986                     OFFSETWH(x1, y1, x, y, dir, w, h);
1987                     if ((tiles[y1*w+x1] & F(dir)) &&
1988                         findloop_is_loop_edge(fls, y*w+x, y1*w+x1))
1989                         flags |= LOOP(dir);
1990                 }
1991             }
1992             loops[y*w+x] = flags;
1993         }
1994     }
1995
1996     findloop_free_state(fls);
1997     return loops;
1998 }
1999
2000 static int *compute_loops(const game_state *state)
2001 {
2002     return compute_loops_inner(state->width, state->height, state->wrapping,
2003                                state->tiles, state->imm->barriers);
2004 }
2005
2006 struct game_ui {
2007     int org_x, org_y; /* origin */
2008     int cx, cy;       /* source tile (game coordinates) */
2009     int cur_x, cur_y;
2010     int cur_visible;
2011     random_state *rs; /* used for jumbling */
2012 #ifdef USE_DRAGGING
2013     int dragtilex, dragtiley, dragstartx, dragstarty, dragged;
2014 #endif
2015 };
2016
2017 static game_ui *new_ui(const game_state *state)
2018 {
2019     void *seed;
2020     int seedsize;
2021     game_ui *ui = snew(game_ui);
2022     ui->org_x = ui->org_y = 0;
2023     ui->cur_x = ui->cx = state->width / 2;
2024     ui->cur_y = ui->cy = state->height / 2;
2025     ui->cur_visible = FALSE;
2026     get_random_seed(&seed, &seedsize);
2027     ui->rs = random_new(seed, seedsize);
2028     sfree(seed);
2029
2030     return ui;
2031 }
2032
2033 static void free_ui(game_ui *ui)
2034 {
2035     random_free(ui->rs);
2036     sfree(ui);
2037 }
2038
2039 static char *encode_ui(const game_ui *ui)
2040 {
2041     char buf[120];
2042     /*
2043      * We preserve the origin and centre-point coordinates over a
2044      * serialise.
2045      */
2046     sprintf(buf, "O%d,%d;C%d,%d", ui->org_x, ui->org_y, ui->cx, ui->cy);
2047     return dupstr(buf);
2048 }
2049
2050 static void decode_ui(game_ui *ui, const char *encoding)
2051 {
2052     sscanf(encoding, "O%d,%d;C%d,%d",
2053            &ui->org_x, &ui->org_y, &ui->cx, &ui->cy);
2054 }
2055
2056 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2057                                const game_state *newstate)
2058 {
2059 }
2060
2061 struct game_drawstate {
2062     int started;
2063     int width, height;
2064     int tilesize;
2065     unsigned long *visible, *to_draw;
2066 };
2067
2068 /* ----------------------------------------------------------------------
2069  * Process a move.
2070  */
2071 static char *interpret_move(const game_state *state, game_ui *ui,
2072                             const game_drawstate *ds,
2073                             int x, int y, int button)
2074 {
2075     char *nullret;
2076     int tx = -1, ty = -1, dir = 0;
2077     int shift = button & MOD_SHFT, ctrl = button & MOD_CTRL;
2078     enum {
2079         NONE, ROTATE_LEFT, ROTATE_180, ROTATE_RIGHT, TOGGLE_LOCK, JUMBLE,
2080         MOVE_ORIGIN, MOVE_SOURCE, MOVE_ORIGIN_AND_SOURCE, MOVE_CURSOR
2081     } action;
2082
2083     button &= ~MOD_MASK;
2084     nullret = NULL;
2085     action = NONE;
2086
2087     if (button == LEFT_BUTTON ||
2088         button == MIDDLE_BUTTON ||
2089 #ifdef USE_DRAGGING
2090         button == LEFT_DRAG ||
2091         button == LEFT_RELEASE ||
2092         button == RIGHT_DRAG ||
2093         button == RIGHT_RELEASE ||
2094 #endif
2095         button == RIGHT_BUTTON) {
2096
2097         if (ui->cur_visible) {
2098             ui->cur_visible = FALSE;
2099             nullret = "";
2100         }
2101
2102         /*
2103          * The button must have been clicked on a valid tile.
2104          */
2105         x -= WINDOW_OFFSET + LINE_THICK;
2106         y -= WINDOW_OFFSET + LINE_THICK;
2107         if (x < 0 || y < 0)
2108             return nullret;
2109         tx = x / TILE_SIZE;
2110         ty = y / TILE_SIZE;
2111         if (tx >= state->width || ty >= state->height)
2112             return nullret;
2113         /* Transform from physical to game coords */
2114         tx = (tx + ui->org_x) % state->width;
2115         ty = (ty + ui->org_y) % state->height;
2116         if (x % TILE_SIZE >= TILE_SIZE - LINE_THICK ||
2117             y % TILE_SIZE >= TILE_SIZE - LINE_THICK)
2118             return nullret;
2119
2120 #ifdef USE_DRAGGING
2121
2122         if (button == MIDDLE_BUTTON
2123 #ifdef STYLUS_BASED
2124             || button == RIGHT_BUTTON  /* with a stylus, `right-click' locks */
2125 #endif
2126             ) {
2127             /*
2128              * Middle button never drags: it only toggles the lock.
2129              */
2130             action = TOGGLE_LOCK;
2131         } else if (button == LEFT_BUTTON
2132 #ifndef STYLUS_BASED
2133                    || button == RIGHT_BUTTON /* (see above) */
2134 #endif
2135                   ) {
2136             /*
2137              * Otherwise, we note down the start point for a drag.
2138              */
2139             ui->dragtilex = tx;
2140             ui->dragtiley = ty;
2141             ui->dragstartx = x % TILE_SIZE;
2142             ui->dragstarty = y % TILE_SIZE;
2143             ui->dragged = FALSE;
2144             return nullret;            /* no actual action */
2145         } else if (button == LEFT_DRAG
2146 #ifndef STYLUS_BASED
2147                    || button == RIGHT_DRAG
2148 #endif
2149                   ) {
2150             /*
2151              * Find the new drag point and see if it necessitates a
2152              * rotation.
2153              */
2154             int x0,y0, xA,yA, xC,yC, xF,yF;
2155             int mx, my;
2156             int d0, dA, dC, dF, dmin;
2157
2158             tx = ui->dragtilex;
2159             ty = ui->dragtiley;
2160
2161             mx = x - (ui->dragtilex * TILE_SIZE);
2162             my = y - (ui->dragtiley * TILE_SIZE);
2163
2164             x0 = ui->dragstartx;
2165             y0 = ui->dragstarty;
2166             xA = ui->dragstarty;
2167             yA = TILE_SIZE-1 - ui->dragstartx;
2168             xF = TILE_SIZE-1 - ui->dragstartx;
2169             yF = TILE_SIZE-1 - ui->dragstarty;
2170             xC = TILE_SIZE-1 - ui->dragstarty;
2171             yC = ui->dragstartx;
2172
2173             d0 = (mx-x0)*(mx-x0) + (my-y0)*(my-y0);
2174             dA = (mx-xA)*(mx-xA) + (my-yA)*(my-yA);
2175             dF = (mx-xF)*(mx-xF) + (my-yF)*(my-yF);
2176             dC = (mx-xC)*(mx-xC) + (my-yC)*(my-yC);
2177
2178             dmin = min(min(d0,dA),min(dF,dC));
2179
2180             if (d0 == dmin) {
2181                 return nullret;
2182             } else if (dF == dmin) {
2183                 action = ROTATE_180;
2184                 ui->dragstartx = xF;
2185                 ui->dragstarty = yF;
2186                 ui->dragged = TRUE;
2187             } else if (dA == dmin) {
2188                 action = ROTATE_LEFT;
2189                 ui->dragstartx = xA;
2190                 ui->dragstarty = yA;
2191                 ui->dragged = TRUE;
2192             } else /* dC == dmin */ {
2193                 action = ROTATE_RIGHT;
2194                 ui->dragstartx = xC;
2195                 ui->dragstarty = yC;
2196                 ui->dragged = TRUE;
2197             }
2198         } else if (button == LEFT_RELEASE
2199 #ifndef STYLUS_BASED
2200                    || button == RIGHT_RELEASE
2201 #endif
2202                   ) {
2203             if (!ui->dragged) {
2204                 /*
2205                  * There was a click but no perceptible drag:
2206                  * revert to single-click behaviour.
2207                  */
2208                 tx = ui->dragtilex;
2209                 ty = ui->dragtiley;
2210
2211                 if (button == LEFT_RELEASE)
2212                     action = ROTATE_LEFT;
2213                 else
2214                     action = ROTATE_RIGHT;
2215             } else
2216                 return nullret;        /* no action */
2217         }
2218
2219 #else /* USE_DRAGGING */
2220
2221         action = (button == LEFT_BUTTON ? ROTATE_LEFT :
2222                   button == RIGHT_BUTTON ? ROTATE_RIGHT : TOGGLE_LOCK);
2223
2224 #endif /* USE_DRAGGING */
2225
2226     } else if (IS_CURSOR_MOVE(button)) {
2227         switch (button) {
2228           case CURSOR_UP:       dir = U; break;
2229           case CURSOR_DOWN:     dir = D; break;
2230           case CURSOR_LEFT:     dir = L; break;
2231           case CURSOR_RIGHT:    dir = R; break;
2232           default:              return nullret;
2233         }
2234         if (shift && ctrl) action = MOVE_ORIGIN_AND_SOURCE;
2235         else if (shift)    action = MOVE_ORIGIN;
2236         else if (ctrl)     action = MOVE_SOURCE;
2237         else               action = MOVE_CURSOR;
2238     } else if (button == 'a' || button == 's' || button == 'd' ||
2239                button == 'A' || button == 'S' || button == 'D' ||
2240                button == 'f' || button == 'F' ||
2241                IS_CURSOR_SELECT(button)) {
2242         tx = ui->cur_x;
2243         ty = ui->cur_y;
2244         if (button == 'a' || button == 'A' || button == CURSOR_SELECT)
2245             action = ROTATE_LEFT;
2246         else if (button == 's' || button == 'S' || button == CURSOR_SELECT2)
2247             action = TOGGLE_LOCK;
2248         else if (button == 'd' || button == 'D')
2249             action = ROTATE_RIGHT;
2250         else if (button == 'f' || button == 'F')
2251             action = ROTATE_180;
2252         ui->cur_visible = TRUE;
2253     } else if (button == 'j' || button == 'J') {
2254         /* XXX should we have some mouse control for this? */
2255         action = JUMBLE;
2256     } else
2257         return nullret;
2258
2259     /*
2260      * The middle button locks or unlocks a tile. (A locked tile
2261      * cannot be turned, and is visually marked as being locked.
2262      * This is a convenience for the player, so that once they are
2263      * sure which way round a tile goes, they can lock it and thus
2264      * avoid forgetting later on that they'd already done that one;
2265      * and the locking also prevents them turning the tile by
2266      * accident. If they change their mind, another middle click
2267      * unlocks it.)
2268      */
2269     if (action == TOGGLE_LOCK) {
2270         char buf[80];
2271         sprintf(buf, "L%d,%d", tx, ty);
2272         return dupstr(buf);
2273     } else if (action == ROTATE_LEFT || action == ROTATE_RIGHT ||
2274                action == ROTATE_180) {
2275         char buf[80];
2276
2277         /*
2278          * The left and right buttons have no effect if clicked on a
2279          * locked tile.
2280          */
2281         if (tile(state, tx, ty) & LOCKED)
2282             return nullret;
2283
2284         /*
2285          * Otherwise, turn the tile one way or the other. Left button
2286          * turns anticlockwise; right button turns clockwise.
2287          */
2288         sprintf(buf, "%c%d,%d", (int)(action == ROTATE_LEFT ? 'A' :
2289                                       action == ROTATE_RIGHT ? 'C' : 'F'), tx, ty);
2290         return dupstr(buf);
2291     } else if (action == JUMBLE) {
2292         /*
2293          * Jumble all unlocked tiles to random orientations.
2294          */
2295
2296         int jx, jy, maxlen;
2297         char *ret, *p;
2298
2299         /*
2300          * Maximum string length assumes no int can be converted to
2301          * decimal and take more than 11 digits!
2302          */
2303         maxlen = state->width * state->height * 25 + 3;
2304
2305         ret = snewn(maxlen, char);
2306         p = ret;
2307         *p++ = 'J';
2308
2309         for (jy = 0; jy < state->height; jy++) {
2310             for (jx = 0; jx < state->width; jx++) {
2311                 if (!(tile(state, jx, jy) & LOCKED)) {
2312                     int rot = random_upto(ui->rs, 4);
2313                     if (rot) {
2314                         p += sprintf(p, ";%c%d,%d", "AFC"[rot-1], jx, jy);
2315                     }
2316                 }
2317             }
2318         }
2319         *p++ = '\0';
2320         assert(p - ret < maxlen);
2321         ret = sresize(ret, p - ret, char);
2322
2323         return ret;
2324     } else if (action == MOVE_ORIGIN || action == MOVE_SOURCE ||
2325                action == MOVE_ORIGIN_AND_SOURCE || action == MOVE_CURSOR) {
2326         assert(dir != 0);
2327         if (action == MOVE_ORIGIN || action == MOVE_ORIGIN_AND_SOURCE) {
2328             if (state->wrapping) {
2329                  OFFSET(ui->org_x, ui->org_y, ui->org_x, ui->org_y, dir, state);
2330             } else return nullret; /* disallowed for non-wrapping grids */
2331         }
2332         if (action == MOVE_SOURCE || action == MOVE_ORIGIN_AND_SOURCE) {
2333             OFFSET(ui->cx, ui->cy, ui->cx, ui->cy, dir, state);
2334         }
2335         if (action == MOVE_CURSOR) {
2336             OFFSET(ui->cur_x, ui->cur_y, ui->cur_x, ui->cur_y, dir, state);
2337             ui->cur_visible = TRUE;
2338         }
2339         return "";
2340     } else {
2341         return NULL;
2342     }
2343 }
2344
2345 static game_state *execute_move(const game_state *from, const char *move)
2346 {
2347     game_state *ret;
2348     int tx = -1, ty = -1, n, noanim, orig;
2349
2350     ret = dup_game(from);
2351
2352     if (move[0] == 'J' || move[0] == 'S') {
2353         if (move[0] == 'S')
2354             ret->used_solve = TRUE;
2355
2356         move++;
2357         if (*move == ';')
2358             move++;
2359         noanim = TRUE;
2360     } else
2361         noanim = FALSE;
2362
2363     ret->last_rotate_dir = 0;          /* suppress animation */
2364     ret->last_rotate_x = ret->last_rotate_y = 0;
2365
2366     while (*move) {
2367         if ((move[0] == 'A' || move[0] == 'C' ||
2368              move[0] == 'F' || move[0] == 'L') &&
2369             sscanf(move+1, "%d,%d%n", &tx, &ty, &n) >= 2 &&
2370             tx >= 0 && tx < from->width && ty >= 0 && ty < from->height) {
2371             orig = tile(ret, tx, ty);
2372             if (move[0] == 'A') {
2373                 tile(ret, tx, ty) = A(orig);
2374                 if (!noanim)
2375                     ret->last_rotate_dir = +1;
2376             } else if (move[0] == 'F') {
2377                 tile(ret, tx, ty) = F(orig);
2378                 if (!noanim)
2379                     ret->last_rotate_dir = +2; /* + for sake of argument */
2380             } else if (move[0] == 'C') {
2381                 tile(ret, tx, ty) = C(orig);
2382                 if (!noanim)
2383                     ret->last_rotate_dir = -1;
2384             } else {
2385                 assert(move[0] == 'L');
2386                 tile(ret, tx, ty) ^= LOCKED;
2387             }
2388
2389             move += 1 + n;
2390             if (*move == ';') move++;
2391         } else {
2392             free_game(ret);
2393             return NULL;
2394         }
2395     }
2396     if (!noanim) {
2397         if (tx == -1 || ty == -1) { free_game(ret); return NULL; }
2398         ret->last_rotate_x = tx;
2399         ret->last_rotate_y = ty;
2400     }
2401
2402     /*
2403      * Check whether the game has been completed.
2404      * 
2405      * For this purpose it doesn't matter where the source square is,
2406      * because we can start from anywhere (or, at least, any square
2407      * that's non-empty!), and correctly determine whether the game is
2408      * completed.
2409      */
2410     {
2411         unsigned char *active;
2412         int pos;
2413         int complete = TRUE;
2414
2415         for (pos = 0; pos < ret->width * ret->height; pos++)
2416             if (ret->tiles[pos] & 0xF)
2417                 break;
2418
2419         if (pos < ret->width * ret->height) {
2420             active = compute_active(ret, pos % ret->width, pos / ret->width);
2421
2422             for (pos = 0; pos < ret->width * ret->height; pos++)
2423                 if ((ret->tiles[pos] & 0xF) && !active[pos]) {
2424                     complete = FALSE;
2425                     break;
2426                 }
2427
2428             sfree(active);
2429         }
2430
2431         if (complete)
2432             ret->completed = TRUE;
2433     }
2434
2435     return ret;
2436 }
2437
2438
2439 /* ----------------------------------------------------------------------
2440  * Routines for drawing the game position on the screen.
2441  */
2442
2443 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2444 {
2445     game_drawstate *ds = snew(game_drawstate);
2446     int i, ncells;
2447
2448     ds->started = FALSE;
2449     ds->width = state->width;
2450     ds->height = state->height;
2451     ncells = (state->width+2) * (state->height+2);
2452     ds->visible = snewn(ncells, unsigned long);
2453     ds->to_draw = snewn(ncells, unsigned long);
2454     ds->tilesize = 0;                  /* undecided yet */
2455     for (i = 0; i < ncells; i++)
2456         ds->visible[i] = -1;
2457
2458     return ds;
2459 }
2460
2461 #define dsindex(ds, field, x, y) ((ds)->field[((y)+1)*((ds)->width+2)+((x)+1)])
2462 #define visible(ds, x, y) dsindex(ds, visible, x, y)
2463 #define todraw(ds, x, y) dsindex(ds, to_draw, x, y)
2464
2465 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2466 {
2467     sfree(ds->visible);
2468     sfree(ds);
2469 }
2470
2471 static void game_compute_size(const game_params *params, int tilesize,
2472                               int *x, int *y)
2473 {
2474     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2475     struct { int tilesize; } ads, *ds = &ads;
2476     ads.tilesize = tilesize;
2477
2478     *x = WINDOW_OFFSET * 2 + TILE_SIZE * params->width + LINE_THICK;
2479     *y = WINDOW_OFFSET * 2 + TILE_SIZE * params->height + LINE_THICK;
2480 }
2481
2482 static void game_set_size(drawing *dr, game_drawstate *ds,
2483                           const game_params *params, int tilesize)
2484 {
2485     ds->tilesize = tilesize;
2486 }
2487
2488 static float *game_colours(frontend *fe, int *ncolours)
2489 {
2490     float *ret;
2491
2492     ret = snewn(NCOLOURS * 3, float);
2493     *ncolours = NCOLOURS;
2494
2495     /*
2496      * Basic background colour is whatever the front end thinks is
2497      * a sensible default.
2498      */
2499     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2500
2501     /*
2502      * Wires are black.
2503      */
2504     ret[COL_WIRE * 3 + 0] = 0.0F;
2505     ret[COL_WIRE * 3 + 1] = 0.0F;
2506     ret[COL_WIRE * 3 + 2] = 0.0F;
2507
2508     /*
2509      * Powered wires and powered endpoints are cyan.
2510      */
2511     ret[COL_POWERED * 3 + 0] = 0.0F;
2512     ret[COL_POWERED * 3 + 1] = 1.0F;
2513     ret[COL_POWERED * 3 + 2] = 1.0F;
2514
2515     /*
2516      * Barriers are red.
2517      */
2518     ret[COL_BARRIER * 3 + 0] = 1.0F;
2519     ret[COL_BARRIER * 3 + 1] = 0.0F;
2520     ret[COL_BARRIER * 3 + 2] = 0.0F;
2521
2522     /*
2523      * Highlighted loops are red as well.
2524      */
2525     ret[COL_LOOP * 3 + 0] = 1.0F;
2526     ret[COL_LOOP * 3 + 1] = 0.0F;
2527     ret[COL_LOOP * 3 + 2] = 0.0F;
2528
2529     /*
2530      * Unpowered endpoints are blue.
2531      */
2532     ret[COL_ENDPOINT * 3 + 0] = 0.0F;
2533     ret[COL_ENDPOINT * 3 + 1] = 0.0F;
2534     ret[COL_ENDPOINT * 3 + 2] = 1.0F;
2535
2536     /*
2537      * Tile borders are a darker grey than the background.
2538      */
2539     ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2540     ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2541     ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2542
2543     /*
2544      * Locked tiles are a grey in between those two.
2545      */
2546     ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2547     ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2548     ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2549
2550     return ret;
2551 }
2552
2553 static void rotated_coords(float *ox, float *oy, const float matrix[4],
2554                            float cx, float cy, float ix, float iy)
2555 {
2556     *ox = matrix[0] * ix + matrix[2] * iy + cx;
2557     *oy = matrix[1] * ix + matrix[3] * iy + cy;
2558 }
2559
2560 /* Flags describing the visible features of a tile. */
2561 #define TILE_BARRIER_SHIFT            0  /* 4 bits: R U L D */
2562 #define TILE_BARRIER_CORNER_SHIFT     4  /* 4 bits: RU UL LD DR */
2563 #define TILE_KEYBOARD_CURSOR      (1<<8) /* 1 bit if cursor is here */
2564 #define TILE_WIRE_SHIFT               9  /* 8 bits: RR UU LL DD
2565                                           * Each pair: 0=no wire, 1=unpowered,
2566                                           * 2=powered, 3=loop err highlight */
2567 #define TILE_ENDPOINT_SHIFT          17  /* 2 bits: 0=no endpoint, 1=unpowered,
2568                                           * 2=powered, 3=power-source square */
2569 #define TILE_WIRE_ON_EDGE_SHIFT      19  /* 8 bits: RR UU LL DD,
2570                                           * same encoding as TILE_WIRE_SHIFT */
2571 #define TILE_ROTATING          (1UL<<27) /* 1 bit if tile is rotating */
2572 #define TILE_LOCKED            (1UL<<28) /* 1 bit if tile is locked */
2573
2574 static void draw_wires(drawing *dr, int cx, int cy, int radius,
2575                        unsigned long tile, int bitmap,
2576                        int colour, int halfwidth, const float matrix[4])
2577 {
2578     float fpoints[12*2];
2579     int points[12*2];
2580     int npoints, d, dsh, i;
2581     int any_wire_this_colour = FALSE;
2582     float xf, yf;
2583
2584     npoints = 0;
2585     for (d = 1, dsh = 0; d < 16; d *= 2, dsh++) {
2586         int wiretype = (tile >> (TILE_WIRE_SHIFT + 2*dsh)) & 3;
2587
2588         fpoints[2*npoints+0] = halfwidth * (X(d) + X(C(d)));
2589         fpoints[2*npoints+1] = halfwidth * (Y(d) + Y(C(d)));
2590         npoints++;
2591
2592         if (bitmap & (1 << wiretype)) {
2593             fpoints[2*npoints+0] = radius * X(d) + halfwidth * X(C(d));
2594             fpoints[2*npoints+1] = radius * Y(d) + halfwidth * Y(C(d));
2595             npoints++;
2596             fpoints[2*npoints+0] = radius * X(d) + halfwidth * X(A(d));
2597             fpoints[2*npoints+1] = radius * Y(d) + halfwidth * Y(A(d));
2598             npoints++;
2599
2600             any_wire_this_colour = TRUE;
2601         }
2602     }
2603
2604     if (!any_wire_this_colour)
2605         return;
2606
2607     for (i = 0; i < npoints; i++) {
2608         rotated_coords(&xf, &yf, matrix, cx, cy, fpoints[2*i], fpoints[2*i+1]);
2609         points[2*i] = 0.5 + xf;
2610         points[2*i+1] = 0.5 + yf;
2611     }
2612
2613     draw_polygon(dr, points, npoints, colour, colour);
2614 }
2615
2616 static void draw_tile(drawing *dr, game_drawstate *ds, int x, int y,
2617                       unsigned long tile, float angle)
2618 {
2619     int tx, ty;
2620     int clipx, clipy, clipX, clipY, clipw, cliph;
2621     int border_br = LINE_THICK/2, border_tl = LINE_THICK - border_br;
2622     int barrier_outline_thick = (LINE_THICK+1)/2;
2623     int bg, d, dsh, pass;
2624     int cx, cy, radius;
2625     float matrix[4];
2626
2627     tx = WINDOW_OFFSET + TILE_SIZE * x + border_br;
2628     ty = WINDOW_OFFSET + TILE_SIZE * y + border_br;
2629
2630     /*
2631      * Clip to the tile boundary, with adjustments if we're drawing
2632      * just outside the grid.
2633      */
2634     clipx = tx; clipX = tx + TILE_SIZE;
2635     clipy = ty; clipY = ty + TILE_SIZE;
2636     if (x == -1) {
2637         clipx = clipX - border_br - barrier_outline_thick;
2638     } else if (x == ds->width) {
2639         clipX = clipx + border_tl + barrier_outline_thick;
2640     }
2641     if (y == -1) {
2642         clipy = clipY - border_br - barrier_outline_thick;
2643     } else if (y == ds->height) {
2644         clipY = clipy + border_tl + barrier_outline_thick;
2645     }
2646     clipw = clipX - clipx;
2647     cliph = clipY - clipy;
2648     clip(dr, clipx, clipy, clipw, cliph);
2649
2650     /*
2651      * Clear the clip region.
2652      */
2653     bg = (tile & TILE_LOCKED) ? COL_LOCKED : COL_BACKGROUND;
2654     draw_rect(dr, clipx, clipy, clipw, cliph, bg);
2655
2656     /*
2657      * Draw the grid lines.
2658      */
2659     {
2660         int gridl = (x == -1 ? tx+TILE_SIZE-border_br : tx);
2661         int gridr = (x == ds->width ? tx+border_tl : tx+TILE_SIZE);
2662         int gridu = (y == -1 ? ty+TILE_SIZE-border_br : ty);
2663         int gridd = (y == ds->height ? ty+border_tl : ty+TILE_SIZE);
2664         if (x >= 0)
2665             draw_rect(dr, tx, gridu, border_tl, gridd-gridu, COL_BORDER);
2666         if (y >= 0)
2667             draw_rect(dr, gridl, ty, gridr-gridl, border_tl, COL_BORDER);
2668         if (x < ds->width)
2669             draw_rect(dr, tx+TILE_SIZE-border_br, gridu,
2670                       border_br, gridd-gridu, COL_BORDER);
2671         if (y < ds->height)
2672             draw_rect(dr, gridl, ty+TILE_SIZE-border_br,
2673                       gridr-gridl, border_br, COL_BORDER);
2674     }
2675
2676     /*
2677      * Draw the keyboard cursor.
2678      */
2679     if (tile & TILE_KEYBOARD_CURSOR) {
2680         int cursorcol = (tile & TILE_LOCKED) ? COL_BACKGROUND : COL_LOCKED;
2681         int inset_outer = TILE_SIZE/8, inset_inner = inset_outer + LINE_THICK;
2682         draw_rect(dr, tx + inset_outer, ty + inset_outer,
2683                   TILE_SIZE - 2*inset_outer, TILE_SIZE - 2*inset_outer,
2684                   cursorcol);
2685         draw_rect(dr, tx + inset_inner, ty + inset_inner,
2686                   TILE_SIZE - 2*inset_inner, TILE_SIZE - 2*inset_inner,
2687                   bg);
2688     }
2689
2690     radius = (TILE_SIZE+1)/2;
2691     cx = tx + radius;
2692     cy = ty + radius;
2693     radius++;
2694
2695     /*
2696      * Draw protrusions into this cell's edges of wires in
2697      * neighbouring cells, as given by the TILE_WIRE_ON_EDGE_SHIFT
2698      * flags. We only draw each of these if there _isn't_ a wire of
2699      * our own that's going to overlap it, which means either the
2700      * corresponding TILE_WIRE_SHIFT flag is zero, or else the
2701      * TILE_ROTATING flag is set (so that our main wire won't be drawn
2702      * in quite that place anyway).
2703      */
2704     for (d = 1, dsh = 0; d < 16; d *= 2, dsh++) {
2705         int edgetype = ((tile >> (TILE_WIRE_ON_EDGE_SHIFT + 2*dsh)) & 3);
2706         if (edgetype == 0)
2707             continue;             /* there isn't a wire on the edge */
2708         if (!(tile & TILE_ROTATING) &&
2709             ((tile >> (TILE_WIRE_SHIFT + 2*dsh)) & 3) != 0)
2710             continue;     /* wire on edge would be overdrawn anyway */
2711
2712         for (pass = 0; pass < 2; pass++) {
2713             int x, y, w, h;
2714             int col = (pass == 0 || edgetype == 1 ? COL_WIRE :
2715                        edgetype == 2 ? COL_POWERED : COL_LOOP);
2716             int halfwidth = pass == 0 ? 2*LINE_THICK-1 : LINE_THICK-1;
2717
2718             if (X(d) < 0) {
2719                 x = tx;
2720                 w = border_tl;
2721             } else if (X(d) > 0) {
2722                 x = tx + TILE_SIZE - border_br;
2723                 w = border_br;
2724             } else {
2725                 x = cx - halfwidth;
2726                 w = 2 * halfwidth + 1;
2727             }
2728
2729             if (Y(d) < 0) {
2730                 y = ty;
2731                 h = border_tl;
2732             } else if (Y(d) > 0) {
2733                 y = ty + TILE_SIZE - border_br;
2734                 h = border_br;
2735             } else {
2736                 y = cy - halfwidth;
2737                 h = 2 * halfwidth + 1;
2738             }
2739
2740             draw_rect(dr, x, y, w, h, col);
2741         }
2742     }
2743
2744     /*
2745      * Set up the rotation matrix for the main cell contents, i.e.
2746      * everything that is centred in the grid square and optionally
2747      * rotated by an arbitrary angle about that centre point.
2748      */
2749     if (tile & TILE_ROTATING) {
2750         matrix[0] = (float)cos(angle * PI / 180.0);
2751         matrix[2] = (float)sin(angle * PI / 180.0);
2752     } else {
2753         matrix[0] = 1.0F;
2754         matrix[2] = 0.0F;
2755     }
2756     matrix[3] = matrix[0];
2757     matrix[1] = -matrix[2];
2758
2759     /*
2760      * Draw the wires.
2761      */
2762     draw_wires(dr, cx, cy, radius, tile,
2763                0xE, COL_WIRE, 2*LINE_THICK-1, matrix);
2764     draw_wires(dr, cx, cy, radius, tile,
2765                0x4, COL_POWERED, LINE_THICK-1, matrix);
2766     draw_wires(dr, cx, cy, radius, tile,
2767                0x8, COL_LOOP, LINE_THICK-1, matrix);
2768
2769     /*
2770      * Draw the central box.
2771      */
2772     for (pass = 0; pass < 2; pass++) {
2773         int endtype = (tile >> TILE_ENDPOINT_SHIFT) & 3;
2774         if (endtype) {
2775             int i, points[8], col;
2776             float boxr = TILE_SIZE * 0.24F + (pass == 0 ? LINE_THICK-1 : 0);
2777
2778             col = (pass == 0 || endtype == 3 ? COL_WIRE :
2779                    endtype == 2 ? COL_POWERED : COL_ENDPOINT);
2780
2781             points[0] = +1; points[1] = +1;
2782             points[2] = +1; points[3] = -1;
2783             points[4] = -1; points[5] = -1;
2784             points[6] = -1; points[7] = +1;
2785
2786             for (i = 0; i < 8; i += 2) {
2787                 float x, y;
2788                 rotated_coords(&x, &y, matrix, cx, cy,
2789                                boxr * points[i], boxr * points[i+1]);
2790                 points[i] = x + 0.5;
2791                 points[i+1] = y + 0.5;
2792             }
2793
2794             draw_polygon(dr, points, 4, col, COL_WIRE);
2795         }
2796     }
2797
2798     /*
2799      * Draw barriers along grid edges.
2800      */
2801     for (pass = 0; pass < 2; pass++) {
2802         int btl = border_tl, bbr = border_br, col = COL_BARRIER;
2803         if (pass == 0) {
2804             btl += barrier_outline_thick;
2805             bbr += barrier_outline_thick;
2806             col = COL_WIRE;
2807         }
2808
2809         if (tile & (L << TILE_BARRIER_SHIFT))
2810             draw_rect(dr, tx, ty, btl, TILE_SIZE, col);
2811         if (tile & (R << TILE_BARRIER_SHIFT))
2812             draw_rect(dr, tx+TILE_SIZE-bbr, ty, bbr, TILE_SIZE, col);
2813         if (tile & (U << TILE_BARRIER_SHIFT))
2814             draw_rect(dr, tx, ty, TILE_SIZE, btl, col);
2815         if (tile & (D << TILE_BARRIER_SHIFT))
2816             draw_rect(dr, tx, ty+TILE_SIZE-bbr, TILE_SIZE, bbr, col);
2817
2818         if (tile & (R << TILE_BARRIER_CORNER_SHIFT))
2819             draw_rect(dr, tx+TILE_SIZE-bbr, ty, bbr, btl, col);
2820         if (tile & (U << TILE_BARRIER_CORNER_SHIFT))
2821             draw_rect(dr, tx, ty, btl, btl, col);
2822         if (tile & (L << TILE_BARRIER_CORNER_SHIFT))
2823             draw_rect(dr, tx, ty+TILE_SIZE-bbr, btl, bbr, col);
2824         if (tile & (D << TILE_BARRIER_CORNER_SHIFT))
2825             draw_rect(dr, tx+TILE_SIZE-bbr, ty+TILE_SIZE-bbr, bbr, bbr, col);
2826     }
2827
2828     /*
2829      * Unclip and draw update, to finish.
2830      */
2831     unclip(dr);
2832     draw_update(dr, clipx, clipy, clipw, cliph);
2833 }
2834
2835 static void game_redraw(drawing *dr, game_drawstate *ds,
2836                         const game_state *oldstate, const game_state *state,
2837                         int dir, const game_ui *ui,
2838                         float t, float ft)
2839 {
2840     int tx, ty, dx, dy, d, dsh, last_rotate_dir, frame;
2841     unsigned char *active;
2842     int *loops;
2843     float angle = 0.0;
2844
2845     /*
2846      * Clear the screen on our first call.
2847      */
2848     if (!ds->started) {
2849         int w, h;
2850         game_params params;
2851
2852         ds->started = TRUE;
2853
2854         params.width = ds->width;
2855         params.height = ds->height;
2856         game_compute_size(&params, TILE_SIZE, &w, &h);
2857
2858         draw_rect(dr, 0, 0, w, h, COL_BACKGROUND);
2859         draw_update(dr, 0, 0, w, h);
2860     }
2861
2862     tx = ty = -1;
2863     last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2864                                 state->last_rotate_dir;
2865     if (oldstate && (t < ROTATE_TIME) && last_rotate_dir) {
2866         /*
2867          * We're animating a single tile rotation. Find the turning
2868          * tile.
2869          */
2870         tx = (dir==-1 ? oldstate->last_rotate_x : state->last_rotate_x);
2871         ty = (dir==-1 ? oldstate->last_rotate_y : state->last_rotate_y);
2872         angle = last_rotate_dir * dir * 90.0F * (t / ROTATE_TIME);
2873         state = oldstate;
2874     }
2875
2876     if (ft > 0) {
2877         /*
2878          * We're animating a completion flash. Find which frame
2879          * we're at.
2880          */
2881         frame = (int)(ft / FLASH_FRAME);
2882     } else {
2883         frame = 0;
2884     }
2885
2886     /*
2887      * Build up a map of what we want every tile to look like. We
2888      * include tiles one square outside the grid, for the outer edges
2889      * of barriers.
2890      */
2891     active = compute_active(state, ui->cx, ui->cy);
2892     loops = compute_loops(state);
2893
2894     for (dy = -1; dy < ds->height+1; dy++) {
2895         for (dx = -1; dx < ds->width+1; dx++) {
2896             todraw(ds, dx, dy) = 0;
2897         }
2898     }
2899
2900     for (dy = 0; dy < ds->height; dy++) {
2901         int gy = (dy + ui->org_y) % ds->height;
2902         for (dx = 0; dx < ds->width; dx++) {
2903             int gx = (dx + ui->org_x) % ds->width;
2904             int t = (tile(state, gx, gy) |
2905                      index(state, loops, gx, gy) |
2906                      index(state, active, gx, gy));
2907
2908             for (d = 1, dsh = 0; d < 16; d *= 2, dsh++) {
2909                 if (barrier(state, gx, gy) & d) {
2910                     todraw(ds, dx, dy) |=
2911                         d << TILE_BARRIER_SHIFT;
2912                     todraw(ds, dx + X(d), dy + Y(d)) |=
2913                         F(d) << TILE_BARRIER_SHIFT;
2914                     todraw(ds, dx + X(A(d)), dy + Y(A(d))) |=
2915                         C(d) << TILE_BARRIER_CORNER_SHIFT;
2916                     todraw(ds, dx + X(A(d)) + X(d), dy + Y(A(d)) + Y(d)) |=
2917                         F(d) << TILE_BARRIER_CORNER_SHIFT;
2918                     todraw(ds, dx + X(C(d)), dy + Y(C(d))) |=
2919                         d << TILE_BARRIER_CORNER_SHIFT;
2920                     todraw(ds, dx + X(C(d)) + X(d), dy + Y(C(d)) + Y(d)) |=
2921                         A(d) << TILE_BARRIER_CORNER_SHIFT;
2922                 }
2923
2924                 if (t & d) {
2925                     int edgeval = (t & LOOP(d) ? 3 : t & ACTIVE ? 2 : 1);
2926                     todraw(ds, dx, dy) |= edgeval << (TILE_WIRE_SHIFT + dsh*2);
2927                     if (!(gx == tx && gy == ty)) {
2928                         todraw(ds, dx + X(d), dy + Y(d)) |=
2929                             edgeval << (TILE_WIRE_ON_EDGE_SHIFT + (dsh ^ 2)*2);
2930                     }
2931                 }
2932             }
2933
2934             if (ui->cur_visible && gx == ui->cur_x && gy == ui->cur_y)
2935                 todraw(ds, dx, dy) |= TILE_KEYBOARD_CURSOR;
2936
2937             if (gx == tx && gy == ty)
2938                 todraw(ds, dx, dy) |= TILE_ROTATING;
2939
2940             if (gx == ui->cx && gy == ui->cy) {
2941                 todraw(ds, dx, dy) |= 3 << TILE_ENDPOINT_SHIFT;
2942             } else if ((t & 0xF) != R && (t & 0xF) != U && 
2943                        (t & 0xF) != L && (t & 0xF) != D) {
2944                 /* this is not an endpoint tile */
2945             } else if (t & ACTIVE) {
2946                 todraw(ds, dx, dy) |= 2 << TILE_ENDPOINT_SHIFT;
2947             } else {
2948                 todraw(ds, dx, dy) |= 1 << TILE_ENDPOINT_SHIFT;
2949             }
2950
2951             if (t & LOCKED)
2952                 todraw(ds, dx, dy) |= TILE_LOCKED;
2953
2954             /*
2955              * In a completion flash, we adjust the LOCKED bit
2956              * depending on our distance from the centre point and
2957              * the frame number.
2958              */
2959             if (frame >= 0) {
2960                 int rcx = (ui->cx + ds->width - ui->org_x) % ds->width;
2961                 int rcy = (ui->cy + ds->height - ui->org_y) % ds->height;
2962                 int xdist, ydist, dist;
2963                 xdist = (dx < rcx ? rcx - dx : dx - rcx);
2964                 ydist = (dy < rcy ? rcy - dy : dy - rcy);
2965                 dist = (xdist > ydist ? xdist : ydist);
2966
2967                 if (frame >= dist && frame < dist+4 &&
2968                     ((frame - dist) & 1))
2969                     todraw(ds, dx, dy) ^= TILE_LOCKED;
2970             }
2971         }
2972     }
2973
2974     /*
2975      * Now draw any tile that differs from the way it was last drawn.
2976      * An exception is that if either the previous _or_ current state
2977      * has the TILE_ROTATING bit set, we must draw it regardless,
2978      * because it will have rotated to a different angle.q
2979      */
2980     for (dy = -1; dy < ds->height+1; dy++) {
2981         for (dx = -1; dx < ds->width+1; dx++) {
2982             int prev = visible(ds, dx, dy);
2983             int curr = todraw(ds, dx, dy);
2984             if (prev != curr || ((prev | curr) & TILE_ROTATING) != 0) {
2985                 draw_tile(dr, ds, dx, dy, curr, angle);
2986                 visible(ds, dx, dy) = curr;
2987             }
2988         }
2989     }
2990
2991     /*
2992      * Update the status bar.
2993      */
2994     {
2995         char statusbuf[256], *p;
2996         int i, n, n2, a;
2997         int complete = FALSE;
2998
2999         p = statusbuf;
3000         *p = '\0';     /* ensure even an empty status string is terminated */
3001
3002         if (state->used_solve) {
3003             p += sprintf(p, "Auto-solved. ");
3004             complete = TRUE;
3005         } else if (state->completed) {
3006             p += sprintf(p, "COMPLETED! ");
3007             complete = TRUE;
3008         }
3009
3010         /*
3011          * Omit the 'Active: n/N' counter completely if the source
3012          * tile is a completely empty one, because then the active
3013          * count can't help but read '1'.
3014          */
3015         if (tile(state, ui->cx, ui->cy) & 0xF) {
3016             n = state->width * state->height;
3017             for (i = a = n2 = 0; i < n; i++) {
3018                 if (active[i])
3019                     a++;
3020                 if (state->tiles[i] & 0xF)
3021                     n2++;
3022             }
3023
3024             /*
3025              * Also, if we're displaying a completion indicator and
3026              * the game is still in its completed state (i.e. every
3027              * tile is active), we might as well omit this too.
3028              */
3029             if (!complete || a < n2)
3030                 p += sprintf(p, "Active: %d/%d", a, n2);
3031         }
3032
3033         status_bar(dr, statusbuf);
3034     }
3035
3036     sfree(active);
3037     sfree(loops);
3038 }
3039
3040 static float game_anim_length(const game_state *oldstate,
3041                               const game_state *newstate, int dir, game_ui *ui)
3042 {
3043     int last_rotate_dir;
3044
3045     /*
3046      * Don't animate if last_rotate_dir is zero.
3047      */
3048     last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
3049                                 newstate->last_rotate_dir;
3050     if (last_rotate_dir)
3051         return ROTATE_TIME;
3052
3053     return 0.0F;
3054 }
3055
3056 static float game_flash_length(const game_state *oldstate,
3057                                const game_state *newstate, int dir, game_ui *ui)
3058 {
3059     /*
3060      * If the game has just been completed, we display a completion
3061      * flash.
3062      */
3063     if (!oldstate->completed && newstate->completed &&
3064         !oldstate->used_solve && !newstate->used_solve) {
3065         int size = 0;
3066         if (size < newstate->width)
3067             size = newstate->width;
3068         if (size < newstate->height)
3069             size = newstate->height;
3070         return FLASH_FRAME * (size+4);
3071     }
3072
3073     return 0.0F;
3074 }
3075
3076 static int game_status(const game_state *state)
3077 {
3078     return state->completed ? +1 : 0;
3079 }
3080
3081 static int game_timing_state(const game_state *state, game_ui *ui)
3082 {
3083     return TRUE;
3084 }
3085
3086 static void game_print_size(const game_params *params, float *x, float *y)
3087 {
3088     int pw, ph;
3089
3090     /*
3091      * I'll use 8mm squares by default.
3092      */
3093     game_compute_size(params, 800, &pw, &ph);
3094     *x = pw / 100.0F;
3095     *y = ph / 100.0F;
3096 }
3097
3098 static void draw_diagram(drawing *dr, game_drawstate *ds, int x, int y,
3099                          int topleft, int v, int drawlines, int ink)
3100 {
3101     int tx, ty, cx, cy, r, br, k, thick;
3102
3103     tx = WINDOW_OFFSET + TILE_SIZE * x;
3104     ty = WINDOW_OFFSET + TILE_SIZE * y;
3105
3106     /*
3107      * Find our centre point.
3108      */
3109     if (topleft) {
3110         cx = tx + (v & L ? TILE_SIZE / 4 : TILE_SIZE / 6);
3111         cy = ty + (v & U ? TILE_SIZE / 4 : TILE_SIZE / 6);
3112         r = TILE_SIZE / 8;
3113         br = TILE_SIZE / 32;
3114     } else {
3115         cx = tx + TILE_SIZE / 2;
3116         cy = ty + TILE_SIZE / 2;
3117         r = TILE_SIZE / 2;
3118         br = TILE_SIZE / 8;
3119     }
3120     thick = r / 20;
3121
3122     /*
3123      * Draw the square block if we have an endpoint.
3124      */
3125     if (v == 1 || v == 2 || v == 4 || v == 8)
3126         draw_rect(dr, cx - br, cy - br, br*2, br*2, ink);
3127
3128     /*
3129      * Draw each radial line.
3130      */
3131     if (drawlines) {
3132         for (k = 1; k < 16; k *= 2)
3133             if (v & k) {
3134                 int x1 = min(cx, cx + (r-thick) * X(k));
3135                 int x2 = max(cx, cx + (r-thick) * X(k));
3136                 int y1 = min(cy, cy + (r-thick) * Y(k));
3137                 int y2 = max(cy, cy + (r-thick) * Y(k));
3138                 draw_rect(dr, x1 - thick, y1 - thick,
3139                           (x2 - x1) + 2*thick, (y2 - y1) + 2*thick, ink);
3140             }
3141     }
3142 }
3143
3144 static void game_print(drawing *dr, const game_state *state, int tilesize)
3145 {
3146     int w = state->width, h = state->height;
3147     int ink = print_mono_colour(dr, 0);
3148     int x, y;
3149
3150     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3151     game_drawstate ads, *ds = &ads;
3152     game_set_size(dr, ds, NULL, tilesize);
3153
3154     /*
3155      * Border.
3156      */
3157     print_line_width(dr, TILE_SIZE / (state->wrapping ? 128 : 12));
3158     draw_rect_outline(dr, WINDOW_OFFSET, WINDOW_OFFSET,
3159                       TILE_SIZE * w, TILE_SIZE * h, ink);
3160
3161     /*
3162      * Grid.
3163      */
3164     print_line_width(dr, TILE_SIZE / 128);
3165     for (x = 1; x < w; x++)
3166         draw_line(dr, WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET,
3167                   WINDOW_OFFSET + TILE_SIZE * x, WINDOW_OFFSET + TILE_SIZE * h,
3168                   ink);
3169     for (y = 1; y < h; y++)
3170         draw_line(dr, WINDOW_OFFSET, WINDOW_OFFSET + TILE_SIZE * y,
3171                   WINDOW_OFFSET + TILE_SIZE * w, WINDOW_OFFSET + TILE_SIZE * y,
3172                   ink);
3173
3174     /*
3175      * Barriers.
3176      */
3177     for (y = 0; y <= h; y++)
3178         for (x = 0; x <= w; x++) {
3179             int b = barrier(state, x % w, y % h);
3180             if (x < w && (b & U))
3181                 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
3182                           WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
3183                           TILE_SIZE + TILE_SIZE/24 * 2, TILE_SIZE/24 * 2, ink);
3184             if (y < h && (b & L))
3185                 draw_rect(dr, WINDOW_OFFSET + TILE_SIZE * x - TILE_SIZE/24,
3186                           WINDOW_OFFSET + TILE_SIZE * y - TILE_SIZE/24,
3187                           TILE_SIZE/24 * 2, TILE_SIZE + TILE_SIZE/24 * 2, ink);
3188         }
3189
3190     /*
3191      * Grid contents.
3192      */
3193     for (y = 0; y < h; y++)
3194         for (x = 0; x < w; x++) {
3195             int vx, v = tile(state, x, y);
3196             int locked = v & LOCKED;
3197
3198             v &= 0xF;
3199
3200             /*
3201              * Rotate into a standard orientation for the top left
3202              * corner diagram.
3203              */
3204             vx = v;
3205             while (vx != 0 && vx != 15 && vx != 1 && vx != 9 && vx != 13 &&
3206                    vx != 5)
3207                 vx = A(vx);
3208
3209             /*
3210              * Draw the top left corner diagram.
3211              */
3212             draw_diagram(dr, ds, x, y, TRUE, vx, TRUE, ink);
3213
3214             /*
3215              * Draw the real solution diagram, if we're doing so.
3216              */
3217             draw_diagram(dr, ds, x, y, FALSE, v, locked, ink);
3218         }
3219 }
3220
3221 #ifdef COMBINED
3222 #define thegame net
3223 #endif
3224
3225 const struct game thegame = {
3226     "Net", "games.net", "net",
3227     default_params,
3228     game_fetch_preset, NULL,
3229     decode_params,
3230     encode_params,
3231     free_params,
3232     dup_params,
3233     TRUE, game_configure, custom_params,
3234     validate_params,
3235     new_game_desc,
3236     validate_desc,
3237     new_game,
3238     dup_game,
3239     free_game,
3240     TRUE, solve_game,
3241     FALSE, game_can_format_as_text_now, game_text_format,
3242     new_ui,
3243     free_ui,
3244     encode_ui,
3245     decode_ui,
3246     game_changed_state,
3247     interpret_move,
3248     execute_move,
3249     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3250     game_colours,
3251     game_new_drawstate,
3252     game_free_drawstate,
3253     game_redraw,
3254     game_anim_length,
3255     game_flash_length,
3256     game_status,
3257     TRUE, FALSE, game_print_size, game_print,
3258     TRUE,                              /* wants_statusbar */
3259     FALSE, game_timing_state,
3260     0,                                 /* flags */
3261 };