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