chiark / gitweb /
Cleanups:
[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 #define PI 3.141592653589793238462643383279502884197169399
16
17 #define MATMUL(xr,yr,m,x,y) do { \
18     float rx, ry, xx = (x), yy = (y), *mat = (m); \
19     rx = mat[0] * xx + mat[2] * yy; \
20     ry = mat[1] * xx + mat[3] * yy; \
21     (xr) = rx; (yr) = ry; \
22 } while (0)
23
24 /* Direction and other bitfields */
25 #define R 0x01
26 #define U 0x02
27 #define L 0x04
28 #define D 0x08
29 #define LOCKED 0x10
30 #define ACTIVE 0x20
31 /* Corner flags go in the barriers array */
32 #define RU 0x10
33 #define UL 0x20
34 #define LD 0x40
35 #define DR 0x80
36
37 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
38 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
39 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
40 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
41 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
42                     ((n)&3) == 1 ? A(x) : \
43                     ((n)&3) == 2 ? F(x) : C(x) )
44
45 /* X and Y displacements */
46 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
47 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
48
49 /* Bit count */
50 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
51                    (((x) & 0x02) >> 1) + ((x) & 0x01) )
52
53 #define TILE_SIZE 32
54 #define TILE_BORDER 1
55 #define WINDOW_OFFSET 16
56
57 #define ROTATE_TIME 0.13F
58 #define FLASH_FRAME 0.07F
59
60 enum {
61     COL_BACKGROUND,
62     COL_LOCKED,
63     COL_BORDER,
64     COL_WIRE,
65     COL_ENDPOINT,
66     COL_POWERED,
67     COL_BARRIER,
68     NCOLOURS
69 };
70
71 struct game_params {
72     int width;
73     int height;
74     int wrapping;
75     int unique;
76     float barrier_probability;
77 };
78
79 struct game_aux_info {
80     int width, height;
81     unsigned char *tiles;
82 };
83
84 struct game_state {
85     int width, height, cx, cy, wrapping, completed;
86     int last_rotate_x, last_rotate_y, last_rotate_dir;
87     int used_solve, just_used_solve;
88     unsigned char *tiles;
89     unsigned char *barriers;
90 };
91
92 #define OFFSETWH(x2,y2,x1,y1,dir,width,height) \
93     ( (x2) = ((x1) + width + X((dir))) % width, \
94       (y2) = ((y1) + height + Y((dir))) % height)
95
96 #define OFFSET(x2,y2,x1,y1,dir,state) \
97         OFFSETWH(x2,y2,x1,y1,dir,(state)->width,(state)->height)
98
99 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
100 #define tile(state, x, y)     index(state, (state)->tiles, x, y)
101 #define barrier(state, x, y)  index(state, (state)->barriers, x, y)
102
103 struct xyd {
104     int x, y, direction;
105 };
106
107 static int xyd_cmp(const void *av, const void *bv) {
108     const struct xyd *a = (const struct xyd *)av;
109     const struct xyd *b = (const struct xyd *)bv;
110     if (a->x < b->x)
111         return -1;
112     if (a->x > b->x)
113         return +1;
114     if (a->y < b->y)
115         return -1;
116     if (a->y > b->y)
117         return +1;
118     if (a->direction < b->direction)
119         return -1;
120     if (a->direction > b->direction)
121         return +1;
122     return 0;
123 };
124
125 static int xyd_cmp_nc(void *av, void *bv) { return xyd_cmp(av, bv); }
126
127 static struct xyd *new_xyd(int x, int y, int direction)
128 {
129     struct xyd *xyd = snew(struct xyd);
130     xyd->x = x;
131     xyd->y = y;
132     xyd->direction = direction;
133     return xyd;
134 }
135
136 /* ----------------------------------------------------------------------
137  * Manage game parameters.
138  */
139 static game_params *default_params(void)
140 {
141     game_params *ret = snew(game_params);
142
143     ret->width = 5;
144     ret->height = 5;
145     ret->wrapping = FALSE;
146     ret->unique = TRUE;
147     ret->barrier_probability = 0.0;
148
149     return ret;
150 }
151
152 static int game_fetch_preset(int i, char **name, game_params **params)
153 {
154     game_params *ret;
155     char str[80];
156     static const struct { int x, y, wrap; } values[] = {
157         {5, 5, FALSE},
158         {7, 7, FALSE},
159         {9, 9, FALSE},
160         {11, 11, FALSE},
161         {13, 11, FALSE},
162         {5, 5, TRUE},
163         {7, 7, TRUE},
164         {9, 9, TRUE},
165         {11, 11, TRUE},
166         {13, 11, TRUE},
167     };
168
169     if (i < 0 || i >= lenof(values))
170         return FALSE;
171
172     ret = snew(game_params);
173     ret->width = values[i].x;
174     ret->height = values[i].y;
175     ret->wrapping = values[i].wrap;
176     ret->unique = TRUE;
177     ret->barrier_probability = 0.0;
178
179     sprintf(str, "%dx%d%s", ret->width, ret->height,
180             ret->wrapping ? " wrapping" : "");
181
182     *name = dupstr(str);
183     *params = ret;
184     return TRUE;
185 }
186
187 static void free_params(game_params *params)
188 {
189     sfree(params);
190 }
191
192 static game_params *dup_params(game_params *params)
193 {
194     game_params *ret = snew(game_params);
195     *ret = *params;                    /* structure copy */
196     return ret;
197 }
198
199 static void decode_params(game_params *ret, char const *string)
200 {
201     char const *p = string;
202
203     ret->width = atoi(p);
204     while (*p && isdigit((unsigned char)*p)) p++;
205     if (*p == 'x') {
206         p++;
207         ret->height = atoi(p);
208         while (*p && isdigit((unsigned char)*p)) p++;
209     } else {
210         ret->height = ret->width;
211     }
212
213     while (*p) {
214         if (*p == 'w') {
215             p++;
216             ret->wrapping = TRUE;
217         } else if (*p == 'b') {
218             p++;
219             ret->barrier_probability = atof(p);
220             while (*p && (*p == '.' || isdigit((unsigned char)*p))) p++;
221         } else if (*p == 'a') {
222             p++;
223             ret->unique = FALSE;
224         } else
225             p++;                       /* skip any other gunk */
226     }
227 }
228
229 static char *encode_params(game_params *params, int full)
230 {
231     char ret[400];
232     int len;
233
234     len = sprintf(ret, "%dx%d", params->width, params->height);
235     if (params->wrapping)
236         ret[len++] = 'w';
237     if (full && params->barrier_probability)
238         len += sprintf(ret+len, "b%g", params->barrier_probability);
239     if (full && !params->unique)
240         ret[len++] = 'a';
241     assert(len < lenof(ret));
242     ret[len] = '\0';
243
244     return dupstr(ret);
245 }
246
247 static config_item *game_configure(game_params *params)
248 {
249     config_item *ret;
250     char buf[80];
251
252     ret = snewn(6, config_item);
253
254     ret[0].name = "Width";
255     ret[0].type = C_STRING;
256     sprintf(buf, "%d", params->width);
257     ret[0].sval = dupstr(buf);
258     ret[0].ival = 0;
259
260     ret[1].name = "Height";
261     ret[1].type = C_STRING;
262     sprintf(buf, "%d", params->height);
263     ret[1].sval = dupstr(buf);
264     ret[1].ival = 0;
265
266     ret[2].name = "Walls wrap around";
267     ret[2].type = C_BOOLEAN;
268     ret[2].sval = NULL;
269     ret[2].ival = params->wrapping;
270
271     ret[3].name = "Barrier probability";
272     ret[3].type = C_STRING;
273     sprintf(buf, "%g", params->barrier_probability);
274     ret[3].sval = dupstr(buf);
275     ret[3].ival = 0;
276
277     ret[4].name = "Ensure unique solution";
278     ret[4].type = C_BOOLEAN;
279     ret[4].sval = NULL;
280     ret[4].ival = params->unique;
281
282     ret[5].name = NULL;
283     ret[5].type = C_END;
284     ret[5].sval = NULL;
285     ret[5].ival = 0;
286
287     return ret;
288 }
289
290 static game_params *custom_params(config_item *cfg)
291 {
292     game_params *ret = snew(game_params);
293
294     ret->width = atoi(cfg[0].sval);
295     ret->height = atoi(cfg[1].sval);
296     ret->wrapping = cfg[2].ival;
297     ret->barrier_probability = (float)atof(cfg[3].sval);
298     ret->unique = cfg[4].ival;
299
300     return ret;
301 }
302
303 static char *validate_params(game_params *params)
304 {
305     if (params->width <= 0 && params->height <= 0)
306         return "Width and height must both be greater than zero";
307     if (params->width <= 0)
308         return "Width must be greater than zero";
309     if (params->height <= 0)
310         return "Height must be greater than zero";
311     if (params->width <= 1 && params->height <= 1)
312         return "At least one of width and height must be greater than one";
313     if (params->barrier_probability < 0)
314         return "Barrier probability may not be negative";
315     if (params->barrier_probability > 1)
316         return "Barrier probability may not be greater than 1";
317     return NULL;
318 }
319
320 /* ----------------------------------------------------------------------
321  * Solver used to assure solution uniqueness during generation. 
322  */
323
324 /*
325  * Test cases I used while debugging all this were
326  * 
327  *   ./net --generate 1 13x11w#12300
328  * which expands under the non-unique grid generation rules to
329  *   13x11w:5eaade1bd222664436d5e2965c12656b1129dd825219e3274d558d5eb2dab5da18898e571d5a2987be79746bd95726c597447d6da96188c513add829da7681da954db113d3cd244
330  * and has two ambiguous areas.
331  * 
332  * An even better one is
333  *   13x11w#507896411361192
334  * which expands to
335  *   13x11w:b7125b1aec598eb31bd58d82572bc11494e5dee4e8db2bdd29b88d41a16bdd996d2996ddec8c83741a1e8674e78328ba71737b8894a9271b1cd1399453d1952e43951d9b712822e
336  * and has an ambiguous area _and_ a situation where loop avoidance
337  * is a necessary deductive technique.
338  * 
339  * Then there's
340  *   48x25w#820543338195187
341  * becoming
342  *   48x25w:255989d14cdd185deaa753a93821a12edc1ab97943ac127e2685d7b8b3c48861b2192416139212b316eddd35de43714ebc7628d753db32e596284d9ec52c5a7dc1b4c811a655117d16dc28921b2b4161352cab1d89d18bc836b8b891d55ea4622a1251861b5bc9a8aa3e5bcd745c95229ca6c3b5e21d5832d397e917325793d7eb442dc351b2db2a52ba8e1651642275842d8871d5534aabc6d5b741aaa2d48ed2a7dbbb3151ddb49d5b9a7ed1ab98ee75d613d656dbba347bc514c84556b43a9bc65a3256ead792488b862a9d2a8a39b4255a4949ed7dbd79443292521265896b4399c95ede89d7c8c797a6a57791a849adea489359a158aa12e5dacce862b8333b7ebea7d344d1a3c53198864b73a9dedde7b663abb1b539e1e8853b1b7edb14a2a17ebaae4dbe63598a2e7e9a2dbdad415bc1d8cb88cbab5a8c82925732cd282e641ea3bd7d2c6e776de9117a26be86deb7c82c89524b122cb9397cd1acd2284e744ea62b9279bae85479ababe315c3ac29c431333395b24e6a1e3c43a2da42d4dce84aadd5b154aea555eaddcbd6e527d228c19388d9b424d94214555a7edbdeebe569d4a56dc51a86bd9963e377bb74752bd5eaa5761ba545e297b62a1bda46ab4aee423ad6c661311783cc18786d4289236563cb4a75ec67d481c14814994464cd1b87396dee63e5ab6e952cc584baa1d4c47cb557ec84dbb63d487c8728118673a166846dd3a4ebc23d6cb9c5827d96b4556e91899db32b517eda815ae271a8911bd745447121dc8d321557bc2a435ebec1bbac35b1a291669451174e6aa2218a4a9c5a6ca31ebc45d84e3a82c121e9ced7d55e9a
343  * which has a spot (far right) where slightly more complex loop
344  * avoidance is required.
345  */
346
347 static int dsf_canonify(int *dsf, int val)
348 {
349     int v2 = val;
350
351     while (dsf[val] != val)
352         val = dsf[val];
353
354     while (v2 != val) {
355         int tmp = dsf[v2];
356         dsf[v2] = val;
357         v2 = tmp;
358     }
359
360     return val;
361 }
362
363 static void dsf_merge(int *dsf, int v1, int v2)
364 {
365     v1 = dsf_canonify(dsf, v1);
366     v2 = dsf_canonify(dsf, v2);
367     dsf[v2] = v1;
368 }
369
370 struct todo {
371     unsigned char *marked;
372     int *buffer;
373     int buflen;
374     int head, tail;
375 };
376
377 static struct todo *todo_new(int maxsize)
378 {
379     struct todo *todo = snew(struct todo);
380     todo->marked = snewn(maxsize, unsigned char);
381     memset(todo->marked, 0, maxsize);
382     todo->buflen = maxsize + 1;
383     todo->buffer = snewn(todo->buflen, int);
384     todo->head = todo->tail = 0;
385     return todo;
386 }
387
388 static void todo_free(struct todo *todo)
389 {
390     sfree(todo->marked);
391     sfree(todo->buffer);
392     sfree(todo);
393 }
394
395 static void todo_add(struct todo *todo, int index)
396 {
397     if (todo->marked[index])
398         return;                        /* already on the list */
399     todo->marked[index] = TRUE;
400     todo->buffer[todo->tail++] = index;
401     if (todo->tail == todo->buflen)
402         todo->tail = 0;
403 }
404
405 static int todo_get(struct todo *todo) {
406     int ret;
407
408     if (todo->head == todo->tail)
409         return -1;                     /* list is empty */
410     ret = todo->buffer[todo->head++];
411     if (todo->head == todo->buflen)
412         todo->head = 0;
413     todo->marked[ret] = FALSE;
414
415     return ret;
416 }
417
418 static int net_solver(int w, int h, unsigned char *tiles, int wrapping)
419 {
420     unsigned char *tilestate;
421     unsigned char *edgestate;
422     int *deadends;
423     int *equivalence;
424     struct todo *todo;
425     int i, j, x, y;
426     int area;
427     int done_something;
428
429     /*
430      * Set up the solver's data structures.
431      */
432     
433     /*
434      * tilestate stores the possible orientations of each tile.
435      * There are up to four of these, so we'll index the array in
436      * fours. tilestate[(y * w + x) * 4] and its three successive
437      * members give the possible orientations, clearing to 255 from
438      * the end as things are ruled out.
439      * 
440      * In this loop we also count up the area of the grid (which is
441      * not _necessarily_ equal to w*h, because there might be one
442      * or more blank squares present. This will never happen in a
443      * grid generated _by_ this program, but it's worth keeping the
444      * solver as general as possible.)
445      */
446     tilestate = snewn(w * h * 4, unsigned char);
447     area = 0;
448     for (i = 0; i < w*h; i++) {
449         tilestate[i * 4] = tiles[i] & 0xF;
450         for (j = 1; j < 4; j++) {
451             if (tilestate[i * 4 + j - 1] == 255 ||
452                 A(tilestate[i * 4 + j - 1]) == tilestate[i * 4])
453                 tilestate[i * 4 + j] = 255;
454             else
455                 tilestate[i * 4 + j] = A(tilestate[i * 4 + j - 1]);
456         }
457         if (tiles[i] != 0)
458             area++;
459     }
460
461     /*
462      * edgestate stores the known state of each edge. It is 0 for
463      * unknown, 1 for open (connected) and 2 for closed (not
464      * connected).
465      * 
466      * In principle we need only worry about each edge once each,
467      * but in fact it's easier to track each edge twice so that we
468      * can reference it from either side conveniently. Also I'm
469      * going to allocate _five_ bytes per tile, rather than the
470      * obvious four, so that I can index edgestate[(y*w+x) * 5 + d]
471      * where d is 1,2,4,8 and they never overlap.
472      */
473     edgestate = snewn((w * h - 1) * 5 + 9, unsigned char);
474     memset(edgestate, 0, (w * h - 1) * 5 + 9);
475
476     /*
477      * deadends tracks which edges have dead ends on them. It is
478      * indexed by tile and direction: deadends[(y*w+x) * 5 + d]
479      * tells you whether heading out of tile (x,y) in direction d
480      * can reach a limited amount of the grid. Values are area+1
481      * (no dead end known) or less than that (can reach _at most_
482      * this many other tiles by heading this way out of this tile).
483      */
484     deadends = snewn((w * h - 1) * 5 + 9, int);
485     for (i = 0; i < (w * h - 1) * 5 + 9; i++)
486         deadends[i] = area+1;
487
488     /*
489      * equivalence tracks which sets of tiles are known to be
490      * connected to one another, so we can avoid creating loops by
491      * linking together tiles which are already linked through
492      * another route.
493      * 
494      * This is a disjoint set forest structure: equivalence[i]
495      * contains the index of another member of the equivalence
496      * class containing i, or contains i itself for precisely one
497      * member in each such class. To find a representative member
498      * of the equivalence class containing i, you keep replacing i
499      * with equivalence[i] until it stops changing; then you go
500      * _back_ along the same path and point everything on it
501      * directly at the representative member so as to speed up
502      * future searches. Then you test equivalence between tiles by
503      * finding the representative of each tile and seeing if
504      * they're the same; and you create new equivalence (merge
505      * classes) by finding the representative of each tile and
506      * setting equivalence[one]=the_other.
507      */
508     equivalence = snewn(w * h, int);
509     for (i = 0; i < w*h; i++)
510         equivalence[i] = i;            /* initially all distinct */
511
512     /*
513      * On a non-wrapping grid, we instantly know that all the edges
514      * round the edge are closed.
515      */
516     if (!wrapping) {
517         for (i = 0; i < w; i++) {
518             edgestate[i * 5 + 2] = edgestate[((h-1) * w + i) * 5 + 8] = 2;
519         }
520         for (i = 0; i < h; i++) {
521             edgestate[(i * w + w-1) * 5 + 1] = edgestate[(i * w) * 5 + 4] = 2;
522         }
523     }
524
525     /*
526      * Since most deductions made by this solver are local (the
527      * exception is loop avoidance, where joining two tiles
528      * together on one side of the grid can theoretically permit a
529      * fresh deduction on the other), we can address the scaling
530      * problem inherent in iterating repeatedly over the entire
531      * grid by instead working with a to-do list.
532      */
533     todo = todo_new(w * h);
534
535     /*
536      * Main deductive loop.
537      */
538     done_something = TRUE;             /* prevent instant termination! */
539     while (1) {
540         int index;
541
542         /*
543          * Take a tile index off the todo list and process it.
544          */
545         index = todo_get(todo);
546         if (index == -1) {
547             /*
548              * If we have run out of immediate things to do, we
549              * have no choice but to scan the whole grid for
550              * longer-range things we've missed. Hence, I now add
551              * every square on the grid back on to the to-do list.
552              * I also set `done_something' to FALSE at this point;
553              * if we later come back here and find it still FALSE,
554              * we will know we've scanned the entire grid without
555              * finding anything new to do, and we can terminate.
556              */
557             if (!done_something)
558                 break;
559             for (i = 0; i < w*h; i++)
560                 todo_add(todo, i);
561             done_something = FALSE;
562
563             index = todo_get(todo);
564         }
565
566         y = index / w;
567         x = index % w;
568         {
569             int d, ourclass = dsf_canonify(equivalence, y*w+x);
570             int deadendmax[9];
571
572             deadendmax[1] = deadendmax[2] = deadendmax[4] = deadendmax[8] = 0;
573
574             for (i = j = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
575                 int valid;
576                 int nnondeadends, nondeadends[4], deadendtotal;
577                 int nequiv, equiv[5];
578                 int val = tilestate[(y*w+x) * 4 + i];
579
580                 valid = TRUE;
581                 nnondeadends = deadendtotal = 0;
582                 equiv[0] = ourclass;
583                 nequiv = 1;
584                 for (d = 1; d <= 8; d += d) {
585                     /*
586                      * Immediately rule out this orientation if it
587                      * conflicts with any known edge.
588                      */
589                     if ((edgestate[(y*w+x) * 5 + d] == 1 && !(val & d)) ||
590                         (edgestate[(y*w+x) * 5 + d] == 2 && (val & d)))
591                         valid = FALSE;
592
593                     if (val & d) {
594                         /*
595                          * Count up the dead-end statistics.
596                          */
597                         if (deadends[(y*w+x) * 5 + d] <= area) {
598                             deadendtotal += deadends[(y*w+x) * 5 + d];
599                         } else {
600                             nondeadends[nnondeadends++] = d;
601                         }
602
603                         /*
604                          * Ensure we aren't linking to any tiles,
605                          * through edges not already known to be
606                          * open, which create a loop.
607                          */
608                         if (edgestate[(y*w+x) * 5 + d] == 0) {
609                             int c, k, x2, y2;
610                             
611                             OFFSETWH(x2, y2, x, y, d, w, h);
612                             c = dsf_canonify(equivalence, y2*w+x2);
613                             for (k = 0; k < nequiv; k++)
614                                 if (c == equiv[k])
615                                     break;
616                             if (k == nequiv)
617                                 equiv[nequiv++] = c;
618                             else
619                                 valid = FALSE;
620                         }
621                     }
622                 }
623
624                 if (nnondeadends == 0) {
625                     /*
626                      * If this orientation links together dead-ends
627                      * with a total area of less than the entire
628                      * grid, it is invalid.
629                      *
630                      * (We add 1 to deadendtotal because of the
631                      * tile itself, of course; one tile linking
632                      * dead ends of size 2 and 3 forms a subnetwork
633                      * with a total area of 6, not 5.)
634                      */
635                     if (deadendtotal+1 < area)
636                         valid = FALSE;
637                 } else if (nnondeadends == 1) {
638                     /*
639                      * If this orientation links together one or
640                      * more dead-ends with precisely one
641                      * non-dead-end, then we may have to mark that
642                      * non-dead-end as a dead end going the other
643                      * way. However, it depends on whether all
644                      * other orientations share the same property.
645                      */
646                     deadendtotal++;
647                     if (deadendmax[nondeadends[0]] < deadendtotal)
648                         deadendmax[nondeadends[0]] = deadendtotal;
649                 } else {
650                     /*
651                      * If this orientation links together two or
652                      * more non-dead-ends, then we can rule out the
653                      * possibility of putting in new dead-end
654                      * markings in those directions.
655                      */
656                     int k;
657                     for (k = 0; k < nnondeadends; k++)
658                         deadendmax[nondeadends[k]] = area+1;
659                 }
660
661                 if (valid)
662                     tilestate[(y*w+x) * 4 + j++] = val;
663 #ifdef SOLVER_DIAGNOSTICS
664                 else
665                     printf("ruling out orientation %x at %d,%d\n", val, x, y);
666 #endif
667             }
668
669             assert(j > 0);             /* we can't lose _all_ possibilities! */
670
671             if (j < i) {
672                 int a, o;
673                 done_something = TRUE;
674
675                 /*
676                  * We have ruled out at least one tile orientation.
677                  * Make sure the rest are blanked.
678                  */
679                 while (j < 4)
680                     tilestate[(y*w+x) * 4 + j++] = 255;
681
682                 /*
683                  * Now go through them again and see if we've
684                  * deduced anything new about any edges.
685                  */
686                 a = 0xF; o = 0;
687                 for (i = 0; i < 4 && tilestate[(y*w+x) * 4 + i] != 255; i++) {
688                     a &= tilestate[(y*w+x) * 4 + i];
689                     o |= tilestate[(y*w+x) * 4 + i];
690                 }
691                 for (d = 1; d <= 8; d += d)
692                     if (edgestate[(y*w+x) * 5 + d] == 0) {
693                         int x2, y2, d2;
694                         OFFSETWH(x2, y2, x, y, d, w, h);
695                         d2 = F(d);
696                         if (a & d) {
697                             /* This edge is open in all orientations. */
698 #ifdef SOLVER_DIAGNOSTICS
699                             printf("marking edge %d,%d:%d open\n", x, y, d);
700 #endif
701                             edgestate[(y*w+x) * 5 + d] = 1;
702                             edgestate[(y2*w+x2) * 5 + d2] = 1;
703                             dsf_merge(equivalence, y*w+x, y2*w+x2);
704                             done_something = TRUE;
705                             todo_add(todo, y2*w+x2);
706                         } else if (!(o & d)) {
707                             /* This edge is closed in all orientations. */
708 #ifdef SOLVER_DIAGNOSTICS
709                             printf("marking edge %d,%d:%d closed\n", x, y, d);
710 #endif
711                             edgestate[(y*w+x) * 5 + d] = 2;
712                             edgestate[(y2*w+x2) * 5 + d2] = 2;
713                             done_something = TRUE;
714                             todo_add(todo, y2*w+x2);
715                         }
716                     }
717
718             }
719
720             /*
721              * Now check the dead-end markers and see if any of
722              * them has lowered from the real ones.
723              */
724             for (d = 1; d <= 8; d += d) {
725                 int x2, y2, d2;
726                 OFFSETWH(x2, y2, x, y, d, w, h);
727                 d2 = F(d);
728                 if (deadendmax[d] > 0 &&
729                     deadends[(y2*w+x2) * 5 + d2] > deadendmax[d]) {
730 #ifdef SOLVER_DIAGNOSTICS
731                     printf("setting dead end value %d,%d:%d to %d\n",
732                            x2, y2, d2, deadendmax[d]);
733 #endif
734                     deadends[(y2*w+x2) * 5 + d2] = deadendmax[d];
735                     done_something = TRUE;
736                     todo_add(todo, y2*w+x2);
737                 }
738             }
739
740         }
741     }
742
743     /*
744      * Mark all completely determined tiles as locked.
745      */
746     j = TRUE;
747     for (i = 0; i < w*h; i++) {
748         if (tilestate[i * 4 + 1] == 255) {
749             assert(tilestate[i * 4 + 0] != 255);
750             tiles[i] = tilestate[i * 4] | LOCKED;
751         } else {
752             tiles[i] &= ~LOCKED;
753             j = FALSE;
754         }
755     }
756
757     /*
758      * Free up working space.
759      */
760     todo_free(todo);
761     sfree(tilestate);
762     sfree(edgestate);
763     sfree(deadends);
764     sfree(equivalence);
765
766     return j;
767 }
768
769 /* ----------------------------------------------------------------------
770  * Randomly select a new game description.
771  */
772
773 /*
774  * Function to randomly perturb an ambiguous section in a grid, to
775  * attempt to ensure unique solvability.
776  */
777 static void perturb(int w, int h, unsigned char *tiles, int wrapping,
778                     random_state *rs, int startx, int starty, int startd)
779 {
780     struct xyd *perimeter, *perim2, *loop[2], looppos[2];
781     int nperim, perimsize, nloop[2], loopsize[2];
782     int x, y, d, i;
783
784     /*
785      * We know that the tile at (startx,starty) is part of an
786      * ambiguous section, and we also know that its neighbour in
787      * direction startd is fully specified. We begin by tracing all
788      * the way round the ambiguous area.
789      */
790     nperim = perimsize = 0;
791     perimeter = NULL;
792     x = startx;
793     y = starty;
794     d = startd;
795 #ifdef PERTURB_DIAGNOSTICS
796     printf("perturb %d,%d:%d\n", x, y, d);
797 #endif
798     do {
799         int x2, y2, d2;
800
801         if (nperim >= perimsize) {
802             perimsize = perimsize * 3 / 2 + 32;
803             perimeter = sresize(perimeter, perimsize, struct xyd);
804         }
805         perimeter[nperim].x = x;
806         perimeter[nperim].y = y;
807         perimeter[nperim].direction = d;
808         nperim++;
809 #ifdef PERTURB_DIAGNOSTICS
810         printf("perimeter: %d,%d:%d\n", x, y, d);
811 #endif
812
813         /*
814          * First, see if we can simply turn left from where we are
815          * and find another locked square.
816          */
817         d2 = A(d);
818         OFFSETWH(x2, y2, x, y, d2, w, h);
819         if ((!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1)) ||
820             (tiles[y2*w+x2] & LOCKED)) {
821             d = d2;
822         } else {
823             /*
824              * Failing that, step left into the new square and look
825              * in front of us.
826              */
827             x = x2;
828             y = y2;
829             OFFSETWH(x2, y2, x, y, d, w, h);
830             if ((wrapping || (abs(x2-x) <= 1 && abs(y2-y) <= 1)) &&
831                 !(tiles[y2*w+x2] & LOCKED)) {
832                 /*
833                  * And failing _that_, we're going to have to step
834                  * forward into _that_ square and look right at the
835                  * same locked square as we started with.
836                  */
837                 x = x2;
838                 y = y2;
839                 d = C(d);
840             }
841         }
842
843     } while (x != startx || y != starty || d != startd);
844
845     /*
846      * Our technique for perturbing this ambiguous area is to
847      * search round its edge for a join we can make: that is, an
848      * edge on the perimeter which is (a) not currently connected,
849      * and (b) connecting it would not yield a full cross on either
850      * side. Then we make that join, search round the network to
851      * find the loop thus constructed, and sever the loop at a
852      * randomly selected other point.
853      */
854     perim2 = snewn(nperim, struct xyd);
855     memcpy(perim2, perimeter, nperim * sizeof(struct xyd));
856     /* Shuffle the perimeter, so as to search it without directional bias. */
857     for (i = nperim; --i ;) {
858         int j = random_upto(rs, i+1);
859         struct xyd t;
860
861         t = perim2[j];
862         perim2[j] = perim2[i];
863         perim2[i] = t;
864     }
865     for (i = 0; i < nperim; i++) {
866         int x2, y2;
867
868         x = perim2[i].x;
869         y = perim2[i].y;
870         d = perim2[i].direction;
871
872         OFFSETWH(x2, y2, x, y, d, w, h);
873         if (!wrapping && (abs(x2-x) > 1 || abs(y2-y) > 1))
874             continue;            /* can't link across non-wrapping border */
875         if (tiles[y*w+x] & d)
876             continue;                  /* already linked in this direction! */
877         if (((tiles[y*w+x] | d) & 15) == 15)
878             continue;                  /* can't turn this tile into a cross */
879         if (((tiles[y2*w+x2] | F(d)) & 15) == 15)
880             continue;                  /* can't turn other tile into a cross */
881
882         /*
883          * We've found the point at which we're going to make a new
884          * link.
885          */
886 #ifdef PERTURB_DIAGNOSTICS      
887         printf("linking %d,%d:%d\n", x, y, d);
888 #endif
889         tiles[y*w+x] |= d;
890         tiles[y2*w+x2] |= F(d);
891
892         break;
893     }
894
895     if (i == nperim)
896         return;                        /* nothing we can do! */
897
898     /*
899      * Now we've constructed a new link, we need to find the entire
900      * loop of which it is a part.
901      * 
902      * In principle, this involves doing a complete search round
903      * the network. However, I anticipate that in the vast majority
904      * of cases the loop will be quite small, so what I'm going to
905      * do is make _two_ searches round the network in parallel, one
906      * keeping its metaphorical hand on the left-hand wall while
907      * the other keeps its hand on the right. As soon as one of
908      * them gets back to its starting point, I abandon the other.
909      */
910     for (i = 0; i < 2; i++) {
911         loopsize[i] = nloop[i] = 0;
912         loop[i] = NULL;
913         looppos[i].x = x;
914         looppos[i].y = y;
915         looppos[i].direction = d;
916     }
917     while (1) {
918         for (i = 0; i < 2; i++) {
919             int x2, y2, j;
920
921             x = looppos[i].x;
922             y = looppos[i].y;
923             d = looppos[i].direction;
924
925             OFFSETWH(x2, y2, x, y, d, w, h);
926
927             /*
928              * Add this path segment to the loop, unless it exactly
929              * reverses the previous one on the loop in which case
930              * we take it away again.
931              */
932 #ifdef PERTURB_DIAGNOSTICS
933             printf("looppos[%d] = %d,%d:%d\n", i, x, y, d);
934 #endif
935             if (nloop[i] > 0 &&
936                 loop[i][nloop[i]-1].x == x2 &&
937                 loop[i][nloop[i]-1].y == y2 &&
938                 loop[i][nloop[i]-1].direction == F(d)) {
939 #ifdef PERTURB_DIAGNOSTICS
940                 printf("removing path segment %d,%d:%d from loop[%d]\n",
941                        x2, y2, F(d), i);
942 #endif
943                 nloop[i]--;
944             } else {
945                 if (nloop[i] >= loopsize[i]) {
946                     loopsize[i] = loopsize[i] * 3 / 2 + 32;
947                     loop[i] = sresize(loop[i], loopsize[i], struct xyd);
948                 }
949 #ifdef PERTURB_DIAGNOSTICS
950                 printf("adding path segment %d,%d:%d to loop[%d]\n",
951                        x, y, d, i);
952 #endif
953                 loop[i][nloop[i]++] = looppos[i];
954             }
955
956 #ifdef PERTURB_DIAGNOSTICS
957             printf("tile at new location is %x\n", tiles[y2*w+x2] & 0xF);
958 #endif
959             d = F(d);
960             for (j = 0; j < 4; j++) {
961                 if (i == 0)
962                     d = A(d);
963                 else
964                     d = C(d);
965 #ifdef PERTURB_DIAGNOSTICS
966                 printf("trying dir %d\n", d);
967 #endif
968                 if (tiles[y2*w+x2] & d) {
969                     looppos[i].x = x2;
970                     looppos[i].y = y2;
971                     looppos[i].direction = d;
972                     break;
973                 }
974             }
975
976             assert(j < 4);
977             assert(nloop[i] > 0);
978
979             if (looppos[i].x == loop[i][0].x &&
980                 looppos[i].y == loop[i][0].y &&
981                 looppos[i].direction == loop[i][0].direction) {
982 #ifdef PERTURB_DIAGNOSTICS
983                 printf("loop %d finished tracking\n", i);
984 #endif
985
986                 /*
987                  * Having found our loop, we now sever it at a
988                  * randomly chosen point - absolutely any will do -
989                  * which is not the one we joined it at to begin
990                  * with. Conveniently, the one we joined it at is
991                  * loop[i][0], so we just avoid that one.
992                  */
993                 j = random_upto(rs, nloop[i]-1) + 1;
994                 x = loop[i][j].x;
995                 y = loop[i][j].y;
996                 d = loop[i][j].direction;
997                 OFFSETWH(x2, y2, x, y, d, w, h);
998                 tiles[y*w+x] &= ~d;
999                 tiles[y2*w+x2] &= ~F(d);
1000
1001                 break;
1002             }
1003         }
1004         if (i < 2)
1005             break;
1006     }
1007     sfree(loop[0]);
1008     sfree(loop[1]);
1009
1010     /*
1011      * Finally, we must mark the entire disputed section as locked,
1012      * to prevent the perturb function being called on it multiple
1013      * times.
1014      * 
1015      * To do this, we _sort_ the perimeter of the area. The
1016      * existing xyd_cmp function will arrange things into columns
1017      * for us, in such a way that each column has the edges in
1018      * vertical order. Then we can work down each column and fill
1019      * in all the squares between an up edge and a down edge.
1020      */
1021     qsort(perimeter, nperim, sizeof(struct xyd), xyd_cmp);
1022     x = y = -1;
1023     for (i = 0; i <= nperim; i++) {
1024         if (i == nperim || perimeter[i].x > x) {
1025             /*
1026              * Fill in everything from the last Up edge to the
1027              * bottom of the grid, if necessary.
1028              */
1029             if (x != -1) {
1030                 while (y < h) {
1031 #ifdef PERTURB_DIAGNOSTICS
1032                     printf("resolved: locking tile %d,%d\n", x, y);
1033 #endif
1034                     tiles[y * w + x] |= LOCKED;
1035                     y++;
1036                 }
1037                 x = y = -1;
1038             }
1039
1040             if (i == nperim)
1041                 break;
1042
1043             x = perimeter[i].x;
1044             y = 0;
1045         }
1046
1047         if (perimeter[i].direction == U) {
1048             x = perimeter[i].x;
1049             y = perimeter[i].y;
1050         } else if (perimeter[i].direction == D) {
1051             /*
1052              * Fill in everything from the last Up edge to here.
1053              */
1054             assert(x == perimeter[i].x && y <= perimeter[i].y);
1055             while (y <= perimeter[i].y) {
1056 #ifdef PERTURB_DIAGNOSTICS
1057                 printf("resolved: locking tile %d,%d\n", x, y);
1058 #endif
1059                 tiles[y * w + x] |= LOCKED;
1060                 y++;
1061             }
1062             x = y = -1;
1063         }
1064     }
1065
1066     sfree(perimeter);
1067 }
1068
1069 static char *new_game_desc(game_params *params, random_state *rs,
1070                            game_aux_info **aux)
1071 {
1072     tree234 *possibilities, *barriertree;
1073     int w, h, x, y, cx, cy, nbarriers;
1074     unsigned char *tiles, *barriers;
1075     char *desc, *p;
1076
1077     w = params->width;
1078     h = params->height;
1079
1080     cx = w / 2;
1081     cy = h / 2;
1082
1083     tiles = snewn(w * h, unsigned char);
1084     barriers = snewn(w * h, unsigned char);
1085
1086     begin_generation:
1087
1088     memset(tiles, 0, w * h);
1089     memset(barriers, 0, w * h);
1090
1091     /*
1092      * Construct the unshuffled grid.
1093      * 
1094      * To do this, we simply start at the centre point, repeatedly
1095      * choose a random possibility out of the available ways to
1096      * extend a used square into an unused one, and do it. After
1097      * extending the third line out of a square, we remove the
1098      * fourth from the possibilities list to avoid any full-cross
1099      * squares (which would make the game too easy because they
1100      * only have one orientation).
1101      * 
1102      * The slightly worrying thing is the avoidance of full-cross
1103      * squares. Can this cause our unsophisticated construction
1104      * algorithm to paint itself into a corner, by getting into a
1105      * situation where there are some unreached squares and the
1106      * only way to reach any of them is to extend a T-piece into a
1107      * full cross?
1108      * 
1109      * Answer: no it can't, and here's a proof.
1110      * 
1111      * Any contiguous group of such unreachable squares must be
1112      * surrounded on _all_ sides by T-pieces pointing away from the
1113      * group. (If not, then there is a square which can be extended
1114      * into one of the `unreachable' ones, and so it wasn't
1115      * unreachable after all.) In particular, this implies that
1116      * each contiguous group of unreachable squares must be
1117      * rectangular in shape (any deviation from that yields a
1118      * non-T-piece next to an `unreachable' square).
1119      * 
1120      * So we have a rectangle of unreachable squares, with T-pieces
1121      * forming a solid border around the rectangle. The corners of
1122      * that border must be connected (since every tile connects all
1123      * the lines arriving in it), and therefore the border must
1124      * form a closed loop around the rectangle.
1125      * 
1126      * But this can't have happened in the first place, since we
1127      * _know_ we've avoided creating closed loops! Hence, no such
1128      * situation can ever arise, and the naive grid construction
1129      * algorithm will guaranteeably result in a complete grid
1130      * containing no unreached squares, no full crosses _and_ no
1131      * closed loops. []
1132      */
1133     possibilities = newtree234(xyd_cmp_nc);
1134
1135     if (cx+1 < w)
1136         add234(possibilities, new_xyd(cx, cy, R));
1137     if (cy-1 >= 0)
1138         add234(possibilities, new_xyd(cx, cy, U));
1139     if (cx-1 >= 0)
1140         add234(possibilities, new_xyd(cx, cy, L));
1141     if (cy+1 < h)
1142         add234(possibilities, new_xyd(cx, cy, D));
1143
1144     while (count234(possibilities) > 0) {
1145         int i;
1146         struct xyd *xyd;
1147         int x1, y1, d1, x2, y2, d2, d;
1148
1149         /*
1150          * Extract a randomly chosen possibility from the list.
1151          */
1152         i = random_upto(rs, count234(possibilities));
1153         xyd = delpos234(possibilities, i);
1154         x1 = xyd->x;
1155         y1 = xyd->y;
1156         d1 = xyd->direction;
1157         sfree(xyd);
1158
1159         OFFSET(x2, y2, x1, y1, d1, params);
1160         d2 = F(d1);
1161 #ifdef DEBUG
1162         printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
1163                x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
1164 #endif
1165
1166         /*
1167          * Make the connection. (We should be moving to an as yet
1168          * unused tile.)
1169          */
1170         index(params, tiles, x1, y1) |= d1;
1171         assert(index(params, tiles, x2, y2) == 0);
1172         index(params, tiles, x2, y2) |= d2;
1173
1174         /*
1175          * If we have created a T-piece, remove its last
1176          * possibility.
1177          */
1178         if (COUNT(index(params, tiles, x1, y1)) == 3) {
1179             struct xyd xyd1, *xydp;
1180
1181             xyd1.x = x1;
1182             xyd1.y = y1;
1183             xyd1.direction = 0x0F ^ index(params, tiles, x1, y1);
1184
1185             xydp = find234(possibilities, &xyd1, NULL);
1186
1187             if (xydp) {
1188 #ifdef DEBUG
1189                 printf("T-piece; removing (%d,%d,%c)\n",
1190                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1191 #endif
1192                 del234(possibilities, xydp);
1193                 sfree(xydp);
1194             }
1195         }
1196
1197         /*
1198          * Remove all other possibilities that were pointing at the
1199          * tile we've just moved into.
1200          */
1201         for (d = 1; d < 0x10; d <<= 1) {
1202             int x3, y3, d3;
1203             struct xyd xyd1, *xydp;
1204
1205             OFFSET(x3, y3, x2, y2, d, params);
1206             d3 = F(d);
1207
1208             xyd1.x = x3;
1209             xyd1.y = y3;
1210             xyd1.direction = d3;
1211
1212             xydp = find234(possibilities, &xyd1, NULL);
1213
1214             if (xydp) {
1215 #ifdef DEBUG
1216                 printf("Loop avoidance; removing (%d,%d,%c)\n",
1217                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
1218 #endif
1219                 del234(possibilities, xydp);
1220                 sfree(xydp);
1221             }
1222         }
1223
1224         /*
1225          * Add new possibilities to the list for moving _out_ of
1226          * the tile we have just moved into.
1227          */
1228         for (d = 1; d < 0x10; d <<= 1) {
1229             int x3, y3;
1230
1231             if (d == d2)
1232                 continue;              /* we've got this one already */
1233
1234             if (!params->wrapping) {
1235                 if (d == U && y2 == 0)
1236                     continue;
1237                 if (d == D && y2 == h-1)
1238                     continue;
1239                 if (d == L && x2 == 0)
1240                     continue;
1241                 if (d == R && x2 == w-1)
1242                     continue;
1243             }
1244
1245             OFFSET(x3, y3, x2, y2, d, params);
1246
1247             if (index(params, tiles, x3, y3))
1248                 continue;              /* this would create a loop */
1249
1250 #ifdef DEBUG
1251             printf("New frontier; adding (%d,%d,%c)\n",
1252                    x2, y2, "0RU3L567D9abcdef"[d]);
1253 #endif
1254             add234(possibilities, new_xyd(x2, y2, d));
1255         }
1256     }
1257     /* Having done that, we should have no possibilities remaining. */
1258     assert(count234(possibilities) == 0);
1259     freetree234(possibilities);
1260
1261     if (params->unique) {
1262         int prevn = -1;
1263
1264         /*
1265          * Run the solver to check unique solubility.
1266          */
1267         while (!net_solver(w, h, tiles, params->wrapping)) {
1268             int n = 0;
1269
1270             /*
1271              * We expect (in most cases) that most of the grid will
1272              * be uniquely specified already, and the remaining
1273              * ambiguous sections will be small and separate. So
1274              * our strategy is to find each individual such
1275              * section, and perform a perturbation on the network
1276              * in that area.
1277              */
1278             for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
1279                 if (x+1 < w && ((tiles[y*w+x] ^ tiles[y*w+x+1]) & LOCKED)) {
1280                     n++;
1281                     if (tiles[y*w+x] & LOCKED)
1282                         perturb(w, h, tiles, params->wrapping, rs, x+1, y, L);
1283                     else
1284                         perturb(w, h, tiles, params->wrapping, rs, x, y, R);
1285                 }
1286                 if (y+1 < h && ((tiles[y*w+x] ^ tiles[(y+1)*w+x]) & LOCKED)) {
1287                     n++;
1288                     if (tiles[y*w+x] & LOCKED)
1289                         perturb(w, h, tiles, params->wrapping, rs, x, y+1, U);
1290                     else
1291                         perturb(w, h, tiles, params->wrapping, rs, x, y, D);
1292                 }
1293             }
1294
1295             /*
1296              * Now n counts the number of ambiguous sections we
1297              * have fiddled with. If we haven't managed to decrease
1298              * it from the last time we ran the solver, give up and
1299              * regenerate the entire grid.
1300              */
1301             if (prevn != -1 && prevn <= n)
1302                 goto begin_generation; /* (sorry) */
1303
1304             prevn = n;
1305         }
1306
1307         /*
1308          * The solver will have left a lot of LOCKED bits lying
1309          * around in the tiles array. Remove them.
1310          */
1311         for (x = 0; x < w*h; x++)
1312             tiles[x] &= ~LOCKED;
1313     }
1314
1315     /*
1316      * Now compute a list of the possible barrier locations.
1317      */
1318     barriertree = newtree234(xyd_cmp_nc);
1319     for (y = 0; y < h; y++) {
1320         for (x = 0; x < w; x++) {
1321
1322             if (!(index(params, tiles, x, y) & R) &&
1323                 (params->wrapping || x < w-1))
1324                 add234(barriertree, new_xyd(x, y, R));
1325             if (!(index(params, tiles, x, y) & D) &&
1326                 (params->wrapping || y < h-1))
1327                 add234(barriertree, new_xyd(x, y, D));
1328         }
1329     }
1330
1331     /*
1332      * Save the unshuffled grid in an aux_info.
1333      */
1334     {
1335         game_aux_info *solution;
1336
1337         solution = snew(game_aux_info);
1338         solution->width = w;
1339         solution->height = h;
1340         solution->tiles = snewn(w * h, unsigned char);
1341         memcpy(solution->tiles, tiles, w * h);
1342
1343         *aux = solution;
1344     }
1345
1346     /*
1347      * Now shuffle the grid.
1348      */
1349     for (y = 0; y < h; y++) {
1350         for (x = 0; x < w; x++) {
1351             int orig = index(params, tiles, x, y);
1352             int rot = random_upto(rs, 4);
1353             index(params, tiles, x, y) = ROT(orig, rot);
1354         }
1355     }
1356
1357     /*
1358      * And now choose barrier locations. (We carefully do this
1359      * _after_ shuffling, so that changing the barrier rate in the
1360      * params while keeping the random seed the same will give the
1361      * same shuffled grid and _only_ change the barrier locations.
1362      * Also the way we choose barrier locations, by repeatedly
1363      * choosing one possibility from the list until we have enough,
1364      * is designed to ensure that raising the barrier rate while
1365      * keeping the seed the same will provide a superset of the
1366      * previous barrier set - i.e. if you ask for 10 barriers, and
1367      * then decide that's still too hard and ask for 20, you'll get
1368      * the original 10 plus 10 more, rather than getting 20 new
1369      * ones and the chance of remembering your first 10.)
1370      */
1371     nbarriers = (int)(params->barrier_probability * count234(barriertree));
1372     assert(nbarriers >= 0 && nbarriers <= count234(barriertree));
1373
1374     while (nbarriers > 0) {
1375         int i;
1376         struct xyd *xyd;
1377         int x1, y1, d1, x2, y2, d2;
1378
1379         /*
1380          * Extract a randomly chosen barrier from the list.
1381          */
1382         i = random_upto(rs, count234(barriertree));
1383         xyd = delpos234(barriertree, i);
1384
1385         assert(xyd != NULL);
1386
1387         x1 = xyd->x;
1388         y1 = xyd->y;
1389         d1 = xyd->direction;
1390         sfree(xyd);
1391
1392         OFFSET(x2, y2, x1, y1, d1, params);
1393         d2 = F(d1);
1394
1395         index(params, barriers, x1, y1) |= d1;
1396         index(params, barriers, x2, y2) |= d2;
1397
1398         nbarriers--;
1399     }
1400
1401     /*
1402      * Clean up the rest of the barrier list.
1403      */
1404     {
1405         struct xyd *xyd;
1406
1407         while ( (xyd = delpos234(barriertree, 0)) != NULL)
1408             sfree(xyd);
1409
1410         freetree234(barriertree);
1411     }
1412
1413     /*
1414      * Finally, encode the grid into a string game description.
1415      * 
1416      * My syntax is extremely simple: each square is encoded as a
1417      * hex digit in which bit 0 means a connection on the right,
1418      * bit 1 means up, bit 2 left and bit 3 down. (i.e. the same
1419      * encoding as used internally). Each digit is followed by
1420      * optional barrier indicators: `v' means a vertical barrier to
1421      * the right of it, and `h' means a horizontal barrier below
1422      * it.
1423      */
1424     desc = snewn(w * h * 3 + 1, char);
1425     p = desc;
1426     for (y = 0; y < h; y++) {
1427         for (x = 0; x < w; x++) {
1428             *p++ = "0123456789abcdef"[index(params, tiles, x, y)];
1429             if ((params->wrapping || x < w-1) &&
1430                 (index(params, barriers, x, y) & R))
1431                 *p++ = 'v';
1432             if ((params->wrapping || y < h-1) &&
1433                 (index(params, barriers, x, y) & D))
1434                 *p++ = 'h';
1435         }
1436     }
1437     assert(p - desc <= w*h*3);
1438     *p = '\0';
1439
1440     sfree(tiles);
1441     sfree(barriers);
1442
1443     return desc;
1444 }
1445
1446 static void game_free_aux_info(game_aux_info *aux)
1447 {
1448     sfree(aux->tiles);
1449     sfree(aux);
1450 }
1451
1452 static char *validate_desc(game_params *params, char *desc)
1453 {
1454     int w = params->width, h = params->height;
1455     int i;
1456
1457     for (i = 0; i < w*h; i++) {
1458         if (*desc >= '0' && *desc <= '9')
1459             /* OK */;
1460         else if (*desc >= 'a' && *desc <= 'f')
1461             /* OK */;
1462         else if (*desc >= 'A' && *desc <= 'F')
1463             /* OK */;
1464         else if (!*desc)
1465             return "Game description shorter than expected";
1466         else
1467             return "Game description contained unexpected character";
1468         desc++;
1469         while (*desc == 'h' || *desc == 'v')
1470             desc++;
1471     }
1472     if (*desc)
1473         return "Game description longer than expected";
1474
1475     return NULL;
1476 }
1477
1478 /* ----------------------------------------------------------------------
1479  * Construct an initial game state, given a description and parameters.
1480  */
1481
1482 static game_state *new_game(game_params *params, char *desc)
1483 {
1484     game_state *state;
1485     int w, h, x, y;
1486
1487     assert(params->width > 0 && params->height > 0);
1488     assert(params->width > 1 || params->height > 1);
1489
1490     /*
1491      * Create a blank game state.
1492      */
1493     state = snew(game_state);
1494     w = state->width = params->width;
1495     h = state->height = params->height;
1496     state->cx = state->width / 2;
1497     state->cy = state->height / 2;
1498     state->wrapping = params->wrapping;
1499     state->last_rotate_dir = state->last_rotate_x = state->last_rotate_y = 0;
1500     state->completed = state->used_solve = state->just_used_solve = FALSE;
1501     state->tiles = snewn(state->width * state->height, unsigned char);
1502     memset(state->tiles, 0, state->width * state->height);
1503     state->barriers = snewn(state->width * state->height, unsigned char);
1504     memset(state->barriers, 0, state->width * state->height);
1505
1506     /*
1507      * Parse the game description into the grid.
1508      */
1509     for (y = 0; y < h; y++) {
1510         for (x = 0; x < w; x++) {
1511             if (*desc >= '0' && *desc <= '9')
1512                 tile(state, x, y) = *desc - '0';
1513             else if (*desc >= 'a' && *desc <= 'f')
1514                 tile(state, x, y) = *desc - 'a' + 10;
1515             else if (*desc >= 'A' && *desc <= 'F')
1516                 tile(state, x, y) = *desc - 'A' + 10;
1517             if (*desc)
1518                 desc++;
1519             while (*desc == 'h' || *desc == 'v') {
1520                 int x2, y2, d1, d2;
1521                 if (*desc == 'v')
1522                     d1 = R;
1523                 else
1524                     d1 = D;
1525
1526                 OFFSET(x2, y2, x, y, d1, state);
1527                 d2 = F(d1);
1528
1529                 barrier(state, x, y) |= d1;
1530                 barrier(state, x2, y2) |= d2;
1531
1532                 desc++;
1533             }
1534         }
1535     }
1536
1537     /*
1538      * Set up border barriers if this is a non-wrapping game.
1539      */
1540     if (!state->wrapping) {
1541         for (x = 0; x < state->width; x++) {
1542             barrier(state, x, 0) |= U;
1543             barrier(state, x, state->height-1) |= D;
1544         }
1545         for (y = 0; y < state->height; y++) {
1546             barrier(state, 0, y) |= L;
1547             barrier(state, state->width-1, y) |= R;
1548         }
1549     }
1550
1551     /*
1552      * Set up the barrier corner flags, for drawing barriers
1553      * prettily when they meet.
1554      */
1555     for (y = 0; y < state->height; y++) {
1556         for (x = 0; x < state->width; x++) {
1557             int dir;
1558
1559             for (dir = 1; dir < 0x10; dir <<= 1) {
1560                 int dir2 = A(dir);
1561                 int x1, y1, x2, y2, x3, y3;
1562                 int corner = FALSE;
1563
1564                 if (!(barrier(state, x, y) & dir))
1565                     continue;
1566
1567                 if (barrier(state, x, y) & dir2)
1568                     corner = TRUE;
1569
1570                 x1 = x + X(dir), y1 = y + Y(dir);
1571                 if (x1 >= 0 && x1 < state->width &&
1572                     y1 >= 0 && y1 < state->height &&
1573                     (barrier(state, x1, y1) & dir2))
1574                     corner = TRUE;
1575
1576                 x2 = x + X(dir2), y2 = y + Y(dir2);
1577                 if (x2 >= 0 && x2 < state->width &&
1578                     y2 >= 0 && y2 < state->height &&
1579                     (barrier(state, x2, y2) & dir))
1580                     corner = TRUE;
1581
1582                 if (corner) {
1583                     barrier(state, x, y) |= (dir << 4);
1584                     if (x1 >= 0 && x1 < state->width &&
1585                         y1 >= 0 && y1 < state->height)
1586                         barrier(state, x1, y1) |= (A(dir) << 4);
1587                     if (x2 >= 0 && x2 < state->width &&
1588                         y2 >= 0 && y2 < state->height)
1589                         barrier(state, x2, y2) |= (C(dir) << 4);
1590                     x3 = x + X(dir) + X(dir2), y3 = y + Y(dir) + Y(dir2);
1591                     if (x3 >= 0 && x3 < state->width &&
1592                         y3 >= 0 && y3 < state->height)
1593                         barrier(state, x3, y3) |= (F(dir) << 4);
1594                 }
1595             }
1596         }
1597     }
1598
1599     return state;
1600 }
1601
1602 static game_state *dup_game(game_state *state)
1603 {
1604     game_state *ret;
1605
1606     ret = snew(game_state);
1607     ret->width = state->width;
1608     ret->height = state->height;
1609     ret->cx = state->cx;
1610     ret->cy = state->cy;
1611     ret->wrapping = state->wrapping;
1612     ret->completed = state->completed;
1613     ret->used_solve = state->used_solve;
1614     ret->just_used_solve = state->just_used_solve;
1615     ret->last_rotate_dir = state->last_rotate_dir;
1616     ret->last_rotate_x = state->last_rotate_x;
1617     ret->last_rotate_y = state->last_rotate_y;
1618     ret->tiles = snewn(state->width * state->height, unsigned char);
1619     memcpy(ret->tiles, state->tiles, state->width * state->height);
1620     ret->barriers = snewn(state->width * state->height, unsigned char);
1621     memcpy(ret->barriers, state->barriers, state->width * state->height);
1622
1623     return ret;
1624 }
1625
1626 static void free_game(game_state *state)
1627 {
1628     sfree(state->tiles);
1629     sfree(state->barriers);
1630     sfree(state);
1631 }
1632
1633 static game_state *solve_game(game_state *state, game_aux_info *aux,
1634                               char **error)
1635 {
1636     game_state *ret;
1637
1638     if (!aux) {
1639         /*
1640          * Run the internal solver on the provided grid. This might
1641          * not yield a complete solution.
1642          */
1643         ret = dup_game(state);
1644         net_solver(ret->width, ret->height, ret->tiles, ret->wrapping);
1645     } else {
1646         assert(aux->width == state->width);
1647         assert(aux->height == state->height);
1648         ret = dup_game(state);
1649         memcpy(ret->tiles, aux->tiles, ret->width * ret->height);
1650         ret->used_solve = ret->just_used_solve = TRUE;
1651         ret->completed = TRUE;
1652     }
1653
1654     return ret;
1655 }
1656
1657 static char *game_text_format(game_state *state)
1658 {
1659     return NULL;
1660 }
1661
1662 /* ----------------------------------------------------------------------
1663  * Utility routine.
1664  */
1665
1666 /*
1667  * Compute which squares are reachable from the centre square, as a
1668  * quick visual aid to determining how close the game is to
1669  * completion. This is also a simple way to tell if the game _is_
1670  * completed - just call this function and see whether every square
1671  * is marked active.
1672  */
1673 static unsigned char *compute_active(game_state *state)
1674 {
1675     unsigned char *active;
1676     tree234 *todo;
1677     struct xyd *xyd;
1678
1679     active = snewn(state->width * state->height, unsigned char);
1680     memset(active, 0, state->width * state->height);
1681
1682     /*
1683      * We only store (x,y) pairs in todo, but it's easier to reuse
1684      * xyd_cmp and just store direction 0 every time.
1685      */
1686     todo = newtree234(xyd_cmp_nc);
1687     index(state, active, state->cx, state->cy) = ACTIVE;
1688     add234(todo, new_xyd(state->cx, state->cy, 0));
1689
1690     while ( (xyd = delpos234(todo, 0)) != NULL) {
1691         int x1, y1, d1, x2, y2, d2;
1692
1693         x1 = xyd->x;
1694         y1 = xyd->y;
1695         sfree(xyd);
1696
1697         for (d1 = 1; d1 < 0x10; d1 <<= 1) {
1698             OFFSET(x2, y2, x1, y1, d1, state);
1699             d2 = F(d1);
1700
1701             /*
1702              * If the next tile in this direction is connected to
1703              * us, and there isn't a barrier in the way, and it
1704              * isn't already marked active, then mark it active and
1705              * add it to the to-examine list.
1706              */
1707             if ((tile(state, x1, y1) & d1) &&
1708                 (tile(state, x2, y2) & d2) &&
1709                 !(barrier(state, x1, y1) & d1) &&
1710                 !index(state, active, x2, y2)) {
1711                 index(state, active, x2, y2) = ACTIVE;
1712                 add234(todo, new_xyd(x2, y2, 0));
1713             }
1714         }
1715     }
1716     /* Now we expect the todo list to have shrunk to zero size. */
1717     assert(count234(todo) == 0);
1718     freetree234(todo);
1719
1720     return active;
1721 }
1722
1723 struct game_ui {
1724     int cur_x, cur_y;
1725     int cur_visible;
1726     random_state *rs; /* used for jumbling */
1727 };
1728
1729 static game_ui *new_ui(game_state *state)
1730 {
1731     void *seed;
1732     int seedsize;
1733     game_ui *ui = snew(game_ui);
1734     ui->cur_x = state->width / 2;
1735     ui->cur_y = state->height / 2;
1736     ui->cur_visible = FALSE;
1737     get_random_seed(&seed, &seedsize);
1738     ui->rs = random_init(seed, seedsize);
1739     sfree(seed);
1740
1741     return ui;
1742 }
1743
1744 static void free_ui(game_ui *ui)
1745 {
1746     random_free(ui->rs);
1747     sfree(ui);
1748 }
1749
1750 /* ----------------------------------------------------------------------
1751  * Process a move.
1752  */
1753 static game_state *make_move(game_state *state, game_ui *ui,
1754                              int x, int y, int button)
1755 {
1756     game_state *ret, *nullret;
1757     int tx, ty, orig;
1758
1759     nullret = NULL;
1760
1761     if (button == LEFT_BUTTON ||
1762         button == MIDDLE_BUTTON ||
1763         button == RIGHT_BUTTON) {
1764
1765         if (ui->cur_visible) {
1766             ui->cur_visible = FALSE;
1767             nullret = state;
1768         }
1769
1770         /*
1771          * The button must have been clicked on a valid tile.
1772          */
1773         x -= WINDOW_OFFSET + TILE_BORDER;
1774         y -= WINDOW_OFFSET + TILE_BORDER;
1775         if (x < 0 || y < 0)
1776             return nullret;
1777         tx = x / TILE_SIZE;
1778         ty = y / TILE_SIZE;
1779         if (tx >= state->width || ty >= state->height)
1780             return nullret;
1781         if (x % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
1782             y % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
1783             return nullret;
1784     } else if (button == CURSOR_UP || button == CURSOR_DOWN ||
1785                button == CURSOR_RIGHT || button == CURSOR_LEFT) {
1786         if (button == CURSOR_UP && ui->cur_y > 0)
1787             ui->cur_y--;
1788         else if (button == CURSOR_DOWN && ui->cur_y < state->height-1)
1789             ui->cur_y++;
1790         else if (button == CURSOR_LEFT && ui->cur_x > 0)
1791             ui->cur_x--;
1792         else if (button == CURSOR_RIGHT && ui->cur_x < state->width-1)
1793             ui->cur_x++;
1794         else
1795             return nullret;            /* no cursor movement */
1796         ui->cur_visible = TRUE;
1797         return state;                  /* UI activity has occurred */
1798     } else if (button == 'a' || button == 's' || button == 'd' ||
1799                button == 'A' || button == 'S' || button == 'D') {
1800         tx = ui->cur_x;
1801         ty = ui->cur_y;
1802         if (button == 'a' || button == 'A')
1803             button = LEFT_BUTTON;
1804         else if (button == 's' || button == 'S')
1805             button = MIDDLE_BUTTON;
1806         else if (button == 'd' || button == 'D')
1807             button = RIGHT_BUTTON;
1808         ui->cur_visible = TRUE;
1809     } else if (button == 'j' || button == 'J') {
1810         /* XXX should we have some mouse control for this? */
1811         button = 'J';   /* canonify */
1812         tx = ty = -1;   /* shut gcc up :( */
1813     } else
1814         return nullret;
1815
1816     /*
1817      * The middle button locks or unlocks a tile. (A locked tile
1818      * cannot be turned, and is visually marked as being locked.
1819      * This is a convenience for the player, so that once they are
1820      * sure which way round a tile goes, they can lock it and thus
1821      * avoid forgetting later on that they'd already done that one;
1822      * and the locking also prevents them turning the tile by
1823      * accident. If they change their mind, another middle click
1824      * unlocks it.)
1825      */
1826     if (button == MIDDLE_BUTTON) {
1827
1828         ret = dup_game(state);
1829         ret->just_used_solve = FALSE;
1830         tile(ret, tx, ty) ^= LOCKED;
1831         ret->last_rotate_dir = ret->last_rotate_x = ret->last_rotate_y = 0;
1832         return ret;
1833
1834     } else if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1835
1836         /*
1837          * The left and right buttons have no effect if clicked on a
1838          * locked tile.
1839          */
1840         if (tile(state, tx, ty) & LOCKED)
1841             return nullret;
1842
1843         /*
1844          * Otherwise, turn the tile one way or the other. Left button
1845          * turns anticlockwise; right button turns clockwise.
1846          */
1847         ret = dup_game(state);
1848         ret->just_used_solve = FALSE;
1849         orig = tile(ret, tx, ty);
1850         if (button == LEFT_BUTTON) {
1851             tile(ret, tx, ty) = A(orig);
1852             ret->last_rotate_dir = +1;
1853         } else {
1854             tile(ret, tx, ty) = C(orig);
1855             ret->last_rotate_dir = -1;
1856         }
1857         ret->last_rotate_x = tx;
1858         ret->last_rotate_y = ty;
1859
1860     } else if (button == 'J') {
1861
1862         /*
1863          * Jumble all unlocked tiles to random orientations.
1864          */
1865         int jx, jy;
1866         ret = dup_game(state);
1867         ret->just_used_solve = FALSE;
1868         for (jy = 0; jy < ret->height; jy++) {
1869             for (jx = 0; jx < ret->width; jx++) {
1870                 if (!(tile(ret, jx, jy) & LOCKED)) {
1871                     int rot = random_upto(ui->rs, 4);
1872                     orig = tile(ret, jx, jy);
1873                     tile(ret, jx, jy) = ROT(orig, rot);
1874                 }
1875             }
1876         }
1877         ret->last_rotate_dir = 0; /* suppress animation */
1878         ret->last_rotate_x = ret->last_rotate_y = 0;
1879
1880     } else assert(0);
1881
1882     /*
1883      * Check whether the game has been completed.
1884      */
1885     {
1886         unsigned char *active = compute_active(ret);
1887         int x1, y1;
1888         int complete = TRUE;
1889
1890         for (x1 = 0; x1 < ret->width; x1++)
1891             for (y1 = 0; y1 < ret->height; y1++)
1892                 if ((tile(ret, x1, y1) & 0xF) && !index(ret, active, x1, y1)) {
1893                     complete = FALSE;
1894                     goto break_label;  /* break out of two loops at once */
1895                 }
1896         break_label:
1897
1898         sfree(active);
1899
1900         if (complete)
1901             ret->completed = TRUE;
1902     }
1903
1904     return ret;
1905 }
1906
1907 /* ----------------------------------------------------------------------
1908  * Routines for drawing the game position on the screen.
1909  */
1910
1911 struct game_drawstate {
1912     int started;
1913     int width, height;
1914     unsigned char *visible;
1915 };
1916
1917 static game_drawstate *game_new_drawstate(game_state *state)
1918 {
1919     game_drawstate *ds = snew(game_drawstate);
1920
1921     ds->started = FALSE;
1922     ds->width = state->width;
1923     ds->height = state->height;
1924     ds->visible = snewn(state->width * state->height, unsigned char);
1925     memset(ds->visible, 0xFF, state->width * state->height);
1926
1927     return ds;
1928 }
1929
1930 static void game_free_drawstate(game_drawstate *ds)
1931 {
1932     sfree(ds->visible);
1933     sfree(ds);
1934 }
1935
1936 static void game_size(game_params *params, int *x, int *y)
1937 {
1938     *x = WINDOW_OFFSET * 2 + TILE_SIZE * params->width + TILE_BORDER;
1939     *y = WINDOW_OFFSET * 2 + TILE_SIZE * params->height + TILE_BORDER;
1940 }
1941
1942 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1943 {
1944     float *ret;
1945
1946     ret = snewn(NCOLOURS * 3, float);
1947     *ncolours = NCOLOURS;
1948
1949     /*
1950      * Basic background colour is whatever the front end thinks is
1951      * a sensible default.
1952      */
1953     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1954
1955     /*
1956      * Wires are black.
1957      */
1958     ret[COL_WIRE * 3 + 0] = 0.0F;
1959     ret[COL_WIRE * 3 + 1] = 0.0F;
1960     ret[COL_WIRE * 3 + 2] = 0.0F;
1961
1962     /*
1963      * Powered wires and powered endpoints are cyan.
1964      */
1965     ret[COL_POWERED * 3 + 0] = 0.0F;
1966     ret[COL_POWERED * 3 + 1] = 1.0F;
1967     ret[COL_POWERED * 3 + 2] = 1.0F;
1968
1969     /*
1970      * Barriers are red.
1971      */
1972     ret[COL_BARRIER * 3 + 0] = 1.0F;
1973     ret[COL_BARRIER * 3 + 1] = 0.0F;
1974     ret[COL_BARRIER * 3 + 2] = 0.0F;
1975
1976     /*
1977      * Unpowered endpoints are blue.
1978      */
1979     ret[COL_ENDPOINT * 3 + 0] = 0.0F;
1980     ret[COL_ENDPOINT * 3 + 1] = 0.0F;
1981     ret[COL_ENDPOINT * 3 + 2] = 1.0F;
1982
1983     /*
1984      * Tile borders are a darker grey than the background.
1985      */
1986     ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
1987     ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
1988     ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
1989
1990     /*
1991      * Locked tiles are a grey in between those two.
1992      */
1993     ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
1994     ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
1995     ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
1996
1997     return ret;
1998 }
1999
2000 static void draw_thick_line(frontend *fe, int x1, int y1, int x2, int y2,
2001                             int colour)
2002 {
2003     draw_line(fe, x1-1, y1, x2-1, y2, COL_WIRE);
2004     draw_line(fe, x1+1, y1, x2+1, y2, COL_WIRE);
2005     draw_line(fe, x1, y1-1, x2, y2-1, COL_WIRE);
2006     draw_line(fe, x1, y1+1, x2, y2+1, COL_WIRE);
2007     draw_line(fe, x1, y1, x2, y2, colour);
2008 }
2009
2010 static void draw_rect_coords(frontend *fe, int x1, int y1, int x2, int y2,
2011                              int colour)
2012 {
2013     int mx = (x1 < x2 ? x1 : x2);
2014     int my = (y1 < y2 ? y1 : y2);
2015     int dx = (x2 + x1 - 2*mx + 1);
2016     int dy = (y2 + y1 - 2*my + 1);
2017
2018     draw_rect(fe, mx, my, dx, dy, colour);
2019 }
2020
2021 static void draw_barrier_corner(frontend *fe, int x, int y, int dir, int phase)
2022 {
2023     int bx = WINDOW_OFFSET + TILE_SIZE * x;
2024     int by = WINDOW_OFFSET + TILE_SIZE * y;
2025     int x1, y1, dx, dy, dir2;
2026
2027     dir >>= 4;
2028
2029     dir2 = A(dir);
2030     dx = X(dir) + X(dir2);
2031     dy = Y(dir) + Y(dir2);
2032     x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2033     y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
2034
2035     if (phase == 0) {
2036         draw_rect_coords(fe, bx+x1, by+y1,
2037                          bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
2038                          COL_WIRE);
2039         draw_rect_coords(fe, bx+x1, by+y1,
2040                          bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
2041                          COL_WIRE);
2042     } else {
2043         draw_rect_coords(fe, bx+x1, by+y1,
2044                          bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
2045                          COL_BARRIER);
2046     }
2047 }
2048
2049 static void draw_barrier(frontend *fe, int x, int y, int dir, int phase)
2050 {
2051     int bx = WINDOW_OFFSET + TILE_SIZE * x;
2052     int by = WINDOW_OFFSET + TILE_SIZE * y;
2053     int x1, y1, w, h;
2054
2055     x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
2056     y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
2057     w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2058     h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
2059
2060     if (phase == 0) {
2061         draw_rect(fe, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
2062     } else {
2063         draw_rect(fe, bx+x1, by+y1, w, h, COL_BARRIER);
2064     }
2065 }
2066
2067 static void draw_tile(frontend *fe, game_state *state, int x, int y, int tile,
2068                       float angle, int cursor)
2069 {
2070     int bx = WINDOW_OFFSET + TILE_SIZE * x;
2071     int by = WINDOW_OFFSET + TILE_SIZE * y;
2072     float matrix[4];
2073     float cx, cy, ex, ey, tx, ty;
2074     int dir, col, phase;
2075
2076     /*
2077      * When we draw a single tile, we must draw everything up to
2078      * and including the borders around the tile. This means that
2079      * if the neighbouring tiles have connections to those borders,
2080      * we must draw those connections on the borders themselves.
2081      *
2082      * This would be terribly fiddly if we ever had to draw a tile
2083      * while its neighbour was in mid-rotate, because we'd have to
2084      * arrange to _know_ that the neighbour was being rotated and
2085      * hence had an anomalous effect on the redraw of this tile.
2086      * Fortunately, the drawing algorithm avoids ever calling us in
2087      * this circumstance: we're either drawing lots of straight
2088      * tiles at game start or after a move is complete, or we're
2089      * repeatedly drawing only the rotating tile. So no problem.
2090      */
2091
2092     /*
2093      * So. First blank the tile out completely: draw a big
2094      * rectangle in border colour, and a smaller rectangle in
2095      * background colour to fill it in.
2096      */
2097     draw_rect(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
2098               COL_BORDER);
2099     draw_rect(fe, bx+TILE_BORDER, by+TILE_BORDER,
2100               TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
2101               tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
2102
2103     /*
2104      * Draw an inset outline rectangle as a cursor, in whichever of
2105      * COL_LOCKED and COL_BACKGROUND we aren't currently drawing
2106      * in.
2107      */
2108     if (cursor) {
2109         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2110                   bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2111                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2112         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE/8,
2113                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2114                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2115         draw_line(fe, bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE/8,
2116                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2117                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2118         draw_line(fe, bx+TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2119                   bx+TILE_SIZE-TILE_SIZE/8, by+TILE_SIZE-TILE_SIZE/8,
2120                   tile & LOCKED ? COL_BACKGROUND : COL_LOCKED);
2121     }
2122
2123     /*
2124      * Set up the rotation matrix.
2125      */
2126     matrix[0] = (float)cos(angle * PI / 180.0);
2127     matrix[1] = (float)-sin(angle * PI / 180.0);
2128     matrix[2] = (float)sin(angle * PI / 180.0);
2129     matrix[3] = (float)cos(angle * PI / 180.0);
2130
2131     /*
2132      * Draw the wires.
2133      */
2134     cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
2135     col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
2136     for (dir = 1; dir < 0x10; dir <<= 1) {
2137         if (tile & dir) {
2138             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2139             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2140             MATMUL(tx, ty, matrix, ex, ey);
2141             draw_thick_line(fe, bx+(int)cx, by+(int)cy,
2142                             bx+(int)(cx+tx), by+(int)(cy+ty),
2143                             COL_WIRE);
2144         }
2145     }
2146     for (dir = 1; dir < 0x10; dir <<= 1) {
2147         if (tile & dir) {
2148             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
2149             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
2150             MATMUL(tx, ty, matrix, ex, ey);
2151             draw_line(fe, bx+(int)cx, by+(int)cy,
2152                       bx+(int)(cx+tx), by+(int)(cy+ty), col);
2153         }
2154     }
2155
2156     /*
2157      * Draw the box in the middle. We do this in blue if the tile
2158      * is an unpowered endpoint, in cyan if the tile is a powered
2159      * endpoint, in black if the tile is the centrepiece, and
2160      * otherwise not at all.
2161      */
2162     col = -1;
2163     if (x == state->cx && y == state->cy)
2164         col = COL_WIRE;
2165     else if (COUNT(tile) == 1) {
2166         col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
2167     }
2168     if (col >= 0) {
2169         int i, points[8];
2170
2171         points[0] = +1; points[1] = +1;
2172         points[2] = +1; points[3] = -1;
2173         points[4] = -1; points[5] = -1;
2174         points[6] = -1; points[7] = +1;
2175
2176         for (i = 0; i < 8; i += 2) {
2177             ex = (TILE_SIZE * 0.24F) * points[i];
2178             ey = (TILE_SIZE * 0.24F) * points[i+1];
2179             MATMUL(tx, ty, matrix, ex, ey);
2180             points[i] = bx+(int)(cx+tx);
2181             points[i+1] = by+(int)(cy+ty);
2182         }
2183
2184         draw_polygon(fe, points, 4, TRUE, col);
2185         draw_polygon(fe, points, 4, FALSE, COL_WIRE);
2186     }
2187
2188     /*
2189      * Draw the points on the border if other tiles are connected
2190      * to us.
2191      */
2192     for (dir = 1; dir < 0x10; dir <<= 1) {
2193         int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
2194
2195         dx = X(dir);
2196         dy = Y(dir);
2197
2198         ox = x + dx;
2199         oy = y + dy;
2200
2201         if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
2202             continue;
2203
2204         if (!(tile(state, ox, oy) & F(dir)))
2205             continue;
2206
2207         px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
2208         py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
2209         lx = dx * (TILE_BORDER-1);
2210         ly = dy * (TILE_BORDER-1);
2211         vx = (dy ? 1 : 0);
2212         vy = (dx ? 1 : 0);
2213
2214         if (angle == 0.0 && (tile & dir)) {
2215             /*
2216              * If we are fully connected to the other tile, we must
2217              * draw right across the tile border. (We can use our
2218              * own ACTIVE state to determine what colour to do this
2219              * in: if we are fully connected to the other tile then
2220              * the two ACTIVE states will be the same.)
2221              */
2222             draw_rect_coords(fe, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
2223             draw_rect_coords(fe, px, py, px+lx, py+ly,
2224                              (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
2225         } else {
2226             /*
2227              * The other tile extends into our border, but isn't
2228              * actually connected to us. Just draw a single black
2229              * dot.
2230              */
2231             draw_rect_coords(fe, px, py, px, py, COL_WIRE);
2232         }
2233     }
2234
2235     /*
2236      * Draw barrier corners, and then barriers.
2237      */
2238     for (phase = 0; phase < 2; phase++) {
2239         for (dir = 1; dir < 0x10; dir <<= 1)
2240             if (barrier(state, x, y) & (dir << 4))
2241                 draw_barrier_corner(fe, x, y, dir << 4, phase);
2242         for (dir = 1; dir < 0x10; dir <<= 1)
2243             if (barrier(state, x, y) & dir)
2244                 draw_barrier(fe, x, y, dir, phase);
2245     }
2246
2247     draw_update(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
2248 }
2249
2250 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2251                  game_state *state, int dir, game_ui *ui, float t, float ft)
2252 {
2253     int x, y, tx, ty, frame, last_rotate_dir;
2254     unsigned char *active;
2255     float angle = 0.0;
2256
2257     /*
2258      * Clear the screen and draw the exterior barrier lines if this
2259      * is our first call.
2260      */
2261     if (!ds->started) {
2262         int phase;
2263
2264         ds->started = TRUE;
2265
2266         draw_rect(fe, 0, 0, 
2267                   WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
2268                   WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
2269                   COL_BACKGROUND);
2270         draw_update(fe, 0, 0, 
2271                     WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
2272                     WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
2273
2274         for (phase = 0; phase < 2; phase++) {
2275
2276             for (x = 0; x < ds->width; x++) {
2277                 if (barrier(state, x, 0) & UL)
2278                     draw_barrier_corner(fe, x, -1, LD, phase);
2279                 if (barrier(state, x, 0) & RU)
2280                     draw_barrier_corner(fe, x, -1, DR, phase);
2281                 if (barrier(state, x, 0) & U)
2282                     draw_barrier(fe, x, -1, D, phase);
2283                 if (barrier(state, x, ds->height-1) & DR)
2284                     draw_barrier_corner(fe, x, ds->height, RU, phase);
2285                 if (barrier(state, x, ds->height-1) & LD)
2286                     draw_barrier_corner(fe, x, ds->height, UL, phase);
2287                 if (barrier(state, x, ds->height-1) & D)
2288                     draw_barrier(fe, x, ds->height, U, phase);
2289             }
2290
2291             for (y = 0; y < ds->height; y++) {
2292                 if (barrier(state, 0, y) & UL)
2293                     draw_barrier_corner(fe, -1, y, RU, phase);
2294                 if (barrier(state, 0, y) & LD)
2295                     draw_barrier_corner(fe, -1, y, DR, phase);
2296                 if (barrier(state, 0, y) & L)
2297                     draw_barrier(fe, -1, y, R, phase);
2298                 if (barrier(state, ds->width-1, y) & RU)
2299                     draw_barrier_corner(fe, ds->width, y, UL, phase);
2300                 if (barrier(state, ds->width-1, y) & DR)
2301                     draw_barrier_corner(fe, ds->width, y, LD, phase);
2302                 if (barrier(state, ds->width-1, y) & R)
2303                     draw_barrier(fe, ds->width, y, L, phase);
2304             }
2305         }
2306     }
2307
2308     tx = ty = -1;
2309     last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2310                                 state->last_rotate_dir;
2311     if (oldstate && (t < ROTATE_TIME) && last_rotate_dir) {
2312         /*
2313          * We're animating a single tile rotation. Find the turning
2314          * tile.
2315          */
2316         tx = (dir==-1 ? oldstate->last_rotate_x : state->last_rotate_x);
2317         ty = (dir==-1 ? oldstate->last_rotate_y : state->last_rotate_y);
2318         angle = last_rotate_dir * dir * 90.0F * (t / ROTATE_TIME);
2319         state = oldstate;
2320     }
2321
2322     frame = -1;
2323     if (ft > 0) {
2324         /*
2325          * We're animating a completion flash. Find which frame
2326          * we're at.
2327          */
2328         frame = (int)(ft / FLASH_FRAME);
2329     }
2330
2331     /*
2332      * Draw any tile which differs from the way it was last drawn.
2333      */
2334     active = compute_active(state);
2335
2336     for (x = 0; x < ds->width; x++)
2337         for (y = 0; y < ds->height; y++) {
2338             unsigned char c = tile(state, x, y) | index(state, active, x, y);
2339
2340             /*
2341              * In a completion flash, we adjust the LOCKED bit
2342              * depending on our distance from the centre point and
2343              * the frame number.
2344              */
2345             if (frame >= 0) {
2346                 int xdist, ydist, dist;
2347                 xdist = (x < state->cx ? state->cx - x : x - state->cx);
2348                 ydist = (y < state->cy ? state->cy - y : y - state->cy);
2349                 dist = (xdist > ydist ? xdist : ydist);
2350
2351                 if (frame >= dist && frame < dist+4) {
2352                     int lock = (frame - dist) & 1;
2353                     lock = lock ? LOCKED : 0;
2354                     c = (c &~ LOCKED) | lock;
2355                 }
2356             }
2357
2358             if (index(state, ds->visible, x, y) != c ||
2359                 index(state, ds->visible, x, y) == 0xFF ||
2360                 (x == tx && y == ty) ||
2361                 (ui->cur_visible && x == ui->cur_x && y == ui->cur_y)) {
2362                 draw_tile(fe, state, x, y, c,
2363                           (x == tx && y == ty ? angle : 0.0F),
2364                           (ui->cur_visible && x == ui->cur_x && y == ui->cur_y));
2365                 if ((x == tx && y == ty) ||
2366                     (ui->cur_visible && x == ui->cur_x && y == ui->cur_y))
2367                     index(state, ds->visible, x, y) = 0xFF;
2368                 else
2369                     index(state, ds->visible, x, y) = c;
2370             }
2371         }
2372
2373     /*
2374      * Update the status bar.
2375      */
2376     {
2377         char statusbuf[256];
2378         int i, n, n2, a;
2379
2380         n = state->width * state->height;
2381         for (i = a = n2 = 0; i < n; i++) {
2382             if (active[i])
2383                 a++;
2384             if (state->tiles[i] & 0xF)
2385                 n2++;
2386         }
2387
2388         sprintf(statusbuf, "%sActive: %d/%d",
2389                 (state->used_solve ? "Auto-solved. " :
2390                  state->completed ? "COMPLETED! " : ""), a, n2);
2391
2392         status_bar(fe, statusbuf);
2393     }
2394
2395     sfree(active);
2396 }
2397
2398 static float game_anim_length(game_state *oldstate,
2399                               game_state *newstate, int dir)
2400 {
2401     int last_rotate_dir;
2402
2403     /*
2404      * Don't animate an auto-solve move.
2405      */
2406     if ((dir > 0 && newstate->just_used_solve) ||
2407        (dir < 0 && oldstate->just_used_solve))
2408        return 0.0F;
2409
2410     /*
2411      * Don't animate if last_rotate_dir is zero.
2412      */
2413     last_rotate_dir = dir==-1 ? oldstate->last_rotate_dir :
2414                                 newstate->last_rotate_dir;
2415     if (last_rotate_dir)
2416         return ROTATE_TIME;
2417
2418     return 0.0F;
2419 }
2420
2421 static float game_flash_length(game_state *oldstate,
2422                                game_state *newstate, int dir)
2423 {
2424     /*
2425      * If the game has just been completed, we display a completion
2426      * flash.
2427      */
2428     if (!oldstate->completed && newstate->completed &&
2429         !oldstate->used_solve && !newstate->used_solve) {
2430         int size;
2431         size = 0;
2432         if (size < newstate->cx+1)
2433             size = newstate->cx+1;
2434         if (size < newstate->cy+1)
2435             size = newstate->cy+1;
2436         if (size < newstate->width - newstate->cx)
2437             size = newstate->width - newstate->cx;
2438         if (size < newstate->height - newstate->cy)
2439             size = newstate->height - newstate->cy;
2440         return FLASH_FRAME * (size+4);
2441     }
2442
2443     return 0.0F;
2444 }
2445
2446 static int game_wants_statusbar(void)
2447 {
2448     return TRUE;
2449 }
2450
2451 #ifdef COMBINED
2452 #define thegame net
2453 #endif
2454
2455 const struct game thegame = {
2456     "Net", "games.net",
2457     default_params,
2458     game_fetch_preset,
2459     decode_params,
2460     encode_params,
2461     free_params,
2462     dup_params,
2463     TRUE, game_configure, custom_params,
2464     validate_params,
2465     new_game_desc,
2466     game_free_aux_info,
2467     validate_desc,
2468     new_game,
2469     dup_game,
2470     free_game,
2471     TRUE, solve_game,
2472     FALSE, game_text_format,
2473     new_ui,
2474     free_ui,
2475     make_move,
2476     game_size,
2477     game_colours,
2478     game_new_drawstate,
2479     game_free_drawstate,
2480     game_redraw,
2481     game_anim_length,
2482     game_flash_length,
2483     game_wants_statusbar,
2484 };