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