chiark / gitweb /
Add a new game concept called a `flash'. This is a graphical effect
[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 <math.h>
10
11 #include "puzzles.h"
12 #include "tree234.h"
13
14 const char *const game_name = "Net";
15
16 #define PI 3.141592653589793238462643383279502884197169399
17
18 #define MATMUL(xr,yr,m,x,y) do { \
19     float rx, ry, xx = (x), yy = (y), *mat = (m); \
20     rx = mat[0] * xx + mat[2] * yy; \
21     ry = mat[1] * xx + mat[3] * yy; \
22     (xr) = rx; (yr) = ry; \
23 } while (0)
24
25 /* Direction and other bitfields */
26 #define R 0x01
27 #define U 0x02
28 #define L 0x04
29 #define D 0x08
30 #define LOCKED 0x10
31 #define ACTIVE 0x20
32 /* Corner flags go in the barriers array */
33 #define RU 0x10
34 #define UL 0x20
35 #define LD 0x40
36 #define DR 0x80
37
38 /* Rotations: Anticlockwise, Clockwise, Flip, general rotate */
39 #define A(x) ( (((x) & 0x07) << 1) | (((x) & 0x08) >> 3) )
40 #define C(x) ( (((x) & 0x0E) >> 1) | (((x) & 0x01) << 3) )
41 #define F(x) ( (((x) & 0x0C) >> 2) | (((x) & 0x03) << 2) )
42 #define ROT(x, n) ( ((n)&3) == 0 ? (x) : \
43                     ((n)&3) == 1 ? A(x) : \
44                     ((n)&3) == 2 ? F(x) : C(x) )
45
46 /* X and Y displacements */
47 #define X(x) ( (x) == R ? +1 : (x) == L ? -1 : 0 )
48 #define Y(x) ( (x) == D ? +1 : (x) == U ? -1 : 0 )
49
50 /* Bit count */
51 #define COUNT(x) ( (((x) & 0x08) >> 3) + (((x) & 0x04) >> 2) + \
52                    (((x) & 0x02) >> 1) + ((x) & 0x01) )
53
54 #define TILE_SIZE 32
55 #define TILE_BORDER 1
56 #define WINDOW_OFFSET 16
57
58 #define ROTATE_TIME 0.1F
59 #define FLASH_FRAME 0.05F
60
61 enum {
62     COL_BACKGROUND,
63     COL_LOCKED,
64     COL_BORDER,
65     COL_WIRE,
66     COL_ENDPOINT,
67     COL_POWERED,
68     COL_BARRIER,
69     NCOLOURS
70 };
71
72 struct game_params {
73     int width;
74     int height;
75     int wrapping;
76     float barrier_probability;
77 };
78
79 struct game_state {
80     int width, height, cx, cy, wrapping, completed, last_rotate_dir;
81     unsigned char *tiles;
82     unsigned char *barriers;
83 };
84
85 #define OFFSET(x2,y2,x1,y1,dir,state) \
86     ( (x2) = ((x1) + (state)->width + X((dir))) % (state)->width, \
87       (y2) = ((y1) + (state)->height + Y((dir))) % (state)->height)
88
89 #define index(state, a, x, y) ( a[(y) * (state)->width + (x)] )
90 #define tile(state, x, y)     index(state, (state)->tiles, x, y)
91 #define barrier(state, x, y)  index(state, (state)->barriers, x, y)
92
93 struct xyd {
94     int x, y, direction;
95 };
96
97 static int xyd_cmp(void *av, void *bv) {
98     struct xyd *a = (struct xyd *)av;
99     struct xyd *b = (struct xyd *)bv;
100     if (a->x < b->x)
101         return -1;
102     if (a->x > b->x)
103         return +1;
104     if (a->y < b->y)
105         return -1;
106     if (a->y > b->y)
107         return +1;
108     if (a->direction < b->direction)
109         return -1;
110     if (a->direction > b->direction)
111         return +1;
112     return 0;
113 };
114
115 static struct xyd *new_xyd(int x, int y, int direction)
116 {
117     struct xyd *xyd = snew(struct xyd);
118     xyd->x = x;
119     xyd->y = y;
120     xyd->direction = direction;
121     return xyd;
122 }
123
124 /* ----------------------------------------------------------------------
125  * Manage game parameters.
126  */
127 game_params *default_params(void)
128 {
129     game_params *ret = snew(game_params);
130
131     ret->width = 5;
132     ret->height = 5;
133     ret->wrapping = FALSE;
134     ret->barrier_probability = 0.0;
135
136     return ret;
137 }
138
139 int game_fetch_preset(int i, char **name, game_params **params)
140 {
141     game_params *ret;
142     char str[80];
143     static const struct { int x, y, wrap; } values[] = {
144         {5, 5, FALSE},
145         {7, 7, FALSE},
146         {9, 9, FALSE},
147         {11, 11, FALSE},
148         {13, 11, FALSE},
149         {5, 5, TRUE},
150         {7, 7, TRUE},
151         {9, 9, TRUE},
152         {11, 11, TRUE},
153         {13, 11, TRUE},
154     };
155
156     if (i < 0 || i >= lenof(values))
157         return FALSE;
158
159     ret = snew(game_params);
160     ret->width = values[i].x;
161     ret->height = values[i].y;
162     ret->wrapping = values[i].wrap;
163     ret->barrier_probability = 0.0;
164
165     sprintf(str, "%dx%d%s", ret->width, ret->height,
166             ret->wrapping ? " wrapping" : "");
167
168     *name = dupstr(str);
169     *params = ret;
170     return TRUE;
171 }
172
173 void free_params(game_params *params)
174 {
175     sfree(params);
176 }
177
178 game_params *dup_params(game_params *params)
179 {
180     game_params *ret = snew(game_params);
181     *ret = *params;                    /* structure copy */
182     return ret;
183 }
184
185 /* ----------------------------------------------------------------------
186  * Randomly select a new game seed.
187  */
188
189 char *new_game_seed(game_params *params)
190 {
191     /*
192      * The full description of a Net game is far too large to
193      * encode directly in the seed, so by default we'll have to go
194      * for the simple approach of providing a random-number seed.
195      * 
196      * (This does not restrict me from _later on_ inventing a seed
197      * string syntax which can never be generated by this code -
198      * for example, strings beginning with a letter - allowing me
199      * to type in a precise game, and have new_game detect it and
200      * understand it and do something completely different.)
201      */
202     char buf[40];
203     sprintf(buf, "%d", rand());
204     return dupstr(buf);
205 }
206
207 /* ----------------------------------------------------------------------
208  * Construct an initial game state, given a seed and parameters.
209  */
210
211 game_state *new_game(game_params *params, char *seed)
212 {
213     random_state *rs;
214     game_state *state;
215     tree234 *possibilities, *barriers;
216     int w, h, x, y, nbarriers;
217
218     assert(params->width > 2);
219     assert(params->height > 2);
220
221     /*
222      * Create a blank game state.
223      */
224     state = snew(game_state);
225     w = state->width = params->width;
226     h = state->height = params->height;
227     state->cx = state->width / 2;
228     state->cy = state->height / 2;
229     state->wrapping = params->wrapping;
230     state->last_rotate_dir = +1;       /* *shrug* */
231     state->completed = FALSE;
232     state->tiles = snewn(state->width * state->height, unsigned char);
233     memset(state->tiles, 0, state->width * state->height);
234     state->barriers = snewn(state->width * state->height, unsigned char);
235     memset(state->barriers, 0, state->width * state->height);
236
237     /*
238      * Set up border barriers if this is a non-wrapping game.
239      */
240     if (!state->wrapping) {
241         for (x = 0; x < state->width; x++) {
242             barrier(state, x, 0) |= U;
243             barrier(state, x, state->height-1) |= D;
244         }
245         for (y = 0; y < state->height; y++) {
246             barrier(state, 0, y) |= L;
247             barrier(state, state->width-1, y) |= R;
248         }
249     }
250
251     /*
252      * Seed the internal random number generator.
253      */
254     rs = random_init(seed, strlen(seed));
255
256     /*
257      * Construct the unshuffled grid.
258      * 
259      * To do this, we simply start at the centre point, repeatedly
260      * choose a random possibility out of the available ways to
261      * extend a used square into an unused one, and do it. After
262      * extending the third line out of a square, we remove the
263      * fourth from the possibilities list to avoid any full-cross
264      * squares (which would make the game too easy because they
265      * only have one orientation).
266      * 
267      * The slightly worrying thing is the avoidance of full-cross
268      * squares. Can this cause our unsophisticated construction
269      * algorithm to paint itself into a corner, by getting into a
270      * situation where there are some unreached squares and the
271      * only way to reach any of them is to extend a T-piece into a
272      * full cross?
273      * 
274      * Answer: no it can't, and here's a proof.
275      * 
276      * Any contiguous group of such unreachable squares must be
277      * surrounded on _all_ sides by T-pieces pointing away from the
278      * group. (If not, then there is a square which can be extended
279      * into one of the `unreachable' ones, and so it wasn't
280      * unreachable after all.) In particular, this implies that
281      * each contiguous group of unreachable squares must be
282      * rectangular in shape (any deviation from that yields a
283      * non-T-piece next to an `unreachable' square).
284      * 
285      * So we have a rectangle of unreachable squares, with T-pieces
286      * forming a solid border around the rectangle. The corners of
287      * that border must be connected (since every tile connects all
288      * the lines arriving in it), and therefore the border must
289      * form a closed loop around the rectangle.
290      * 
291      * But this can't have happened in the first place, since we
292      * _know_ we've avoided creating closed loops! Hence, no such
293      * situation can ever arise, and the naive grid construction
294      * algorithm will guaranteeably result in a complete grid
295      * containing no unreached squares, no full crosses _and_ no
296      * closed loops. []
297      */
298     possibilities = newtree234(xyd_cmp);
299     
300     add234(possibilities, new_xyd(state->cx, state->cy, R));
301     add234(possibilities, new_xyd(state->cx, state->cy, U));
302     add234(possibilities, new_xyd(state->cx, state->cy, L));
303     add234(possibilities, new_xyd(state->cx, state->cy, D));
304
305     while (count234(possibilities) > 0) {
306         int i;
307         struct xyd *xyd;
308         int x1, y1, d1, x2, y2, d2, d;
309
310         /*
311          * Extract a randomly chosen possibility from the list.
312          */
313         i = random_upto(rs, count234(possibilities));
314         xyd = delpos234(possibilities, i);
315         x1 = xyd->x;
316         y1 = xyd->y;
317         d1 = xyd->direction;
318         sfree(xyd);
319
320         OFFSET(x2, y2, x1, y1, d1, state);
321         d2 = F(d1);
322 #ifdef DEBUG
323         printf("picked (%d,%d,%c) <-> (%d,%d,%c)\n",
324                x1, y1, "0RU3L567D9abcdef"[d1], x2, y2, "0RU3L567D9abcdef"[d2]);
325 #endif
326
327         /*
328          * Make the connection. (We should be moving to an as yet
329          * unused tile.)
330          */
331         tile(state, x1, y1) |= d1;
332         assert(tile(state, x2, y2) == 0);
333         tile(state, x2, y2) |= d2;
334
335         /*
336          * If we have created a T-piece, remove its last
337          * possibility.
338          */
339         if (COUNT(tile(state, x1, y1)) == 3) {
340             struct xyd xyd1, *xydp;
341
342             xyd1.x = x1;
343             xyd1.y = y1;
344             xyd1.direction = 0x0F ^ tile(state, x1, y1);
345
346             xydp = find234(possibilities, &xyd1, NULL);
347
348             if (xydp) {
349 #ifdef DEBUG
350                 printf("T-piece; removing (%d,%d,%c)\n",
351                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
352 #endif
353                 del234(possibilities, xydp);
354                 sfree(xydp);
355             }
356         }
357
358         /*
359          * Remove all other possibilities that were pointing at the
360          * tile we've just moved into.
361          */
362         for (d = 1; d < 0x10; d <<= 1) {
363             int x3, y3, d3;
364             struct xyd xyd1, *xydp;
365
366             OFFSET(x3, y3, x2, y2, d, state);
367             d3 = F(d);
368
369             xyd1.x = x3;
370             xyd1.y = y3;
371             xyd1.direction = d3;
372
373             xydp = find234(possibilities, &xyd1, NULL);
374
375             if (xydp) {
376 #ifdef DEBUG
377                 printf("Loop avoidance; removing (%d,%d,%c)\n",
378                        xydp->x, xydp->y, "0RU3L567D9abcdef"[xydp->direction]);
379 #endif
380                 del234(possibilities, xydp);
381                 sfree(xydp);
382             }
383         }
384
385         /*
386          * Add new possibilities to the list for moving _out_ of
387          * the tile we have just moved into.
388          */
389         for (d = 1; d < 0x10; d <<= 1) {
390             int x3, y3;
391
392             if (d == d2)
393                 continue;              /* we've got this one already */
394
395             if (!state->wrapping) {
396                 if (d == U && y2 == 0)
397                     continue;
398                 if (d == D && y2 == state->height-1)
399                     continue;
400                 if (d == L && x2 == 0)
401                     continue;
402                 if (d == R && x2 == state->width-1)
403                     continue;
404             }
405
406             OFFSET(x3, y3, x2, y2, d, state);
407
408             if (tile(state, x3, y3))
409                 continue;              /* this would create a loop */
410
411 #ifdef DEBUG
412             printf("New frontier; adding (%d,%d,%c)\n",
413                    x2, y2, "0RU3L567D9abcdef"[d]);
414 #endif
415             add234(possibilities, new_xyd(x2, y2, d));
416         }
417     }
418     /* Having done that, we should have no possibilities remaining. */
419     assert(count234(possibilities) == 0);
420     freetree234(possibilities);
421
422     /*
423      * Now compute a list of the possible barrier locations.
424      */
425     barriers = newtree234(xyd_cmp);
426     for (y = 0; y < state->height; y++) {
427         for (x = 0; x < state->width; x++) {
428
429             if (!(tile(state, x, y) & R) &&
430                 (state->wrapping || x < state->width-1))
431                 add234(barriers, new_xyd(x, y, R));
432             if (!(tile(state, x, y) & D) &&
433                 (state->wrapping || y < state->height-1))
434                 add234(barriers, new_xyd(x, y, D));
435         }
436     }
437
438     /*
439      * Now shuffle the grid.
440      */
441     for (y = 0; y < state->height; y++) {
442         for (x = 0; x < state->width; x++) {
443             int orig = tile(state, x, y);
444             int rot = random_upto(rs, 4);
445             tile(state, x, y) = ROT(orig, rot);
446         }
447     }
448
449     /*
450      * And now choose barrier locations. (We carefully do this
451      * _after_ shuffling, so that changing the barrier rate in the
452      * params while keeping the game seed the same will give the
453      * same shuffled grid and _only_ change the barrier locations.
454      * Also the way we choose barrier locations, by repeatedly
455      * choosing one possibility from the list until we have enough,
456      * is designed to ensure that raising the barrier rate while
457      * keeping the seed the same will provide a superset of the
458      * previous barrier set - i.e. if you ask for 10 barriers, and
459      * then decide that's still too hard and ask for 20, you'll get
460      * the original 10 plus 10 more, rather than getting 20 new
461      * ones and the chance of remembering your first 10.)
462      */
463     nbarriers = (int)(params->barrier_probability * count234(barriers));
464     assert(nbarriers >= 0 && nbarriers <= count234(barriers));
465
466     while (nbarriers > 0) {
467         int i;
468         struct xyd *xyd;
469         int x1, y1, d1, x2, y2, d2;
470
471         /*
472          * Extract a randomly chosen barrier from the list.
473          */
474         i = random_upto(rs, count234(barriers));
475         xyd = delpos234(barriers, i);
476
477         assert(xyd != NULL);
478
479         x1 = xyd->x;
480         y1 = xyd->y;
481         d1 = xyd->direction;
482         sfree(xyd);
483
484         OFFSET(x2, y2, x1, y1, d1, state);
485         d2 = F(d1);
486
487         barrier(state, x1, y1) |= d1;
488         barrier(state, x2, y2) |= d2;
489
490         nbarriers--;
491     }
492
493     /*
494      * Clean up the rest of the barrier list.
495      */
496     {
497         struct xyd *xyd;
498
499         while ( (xyd = delpos234(barriers, 0)) != NULL)
500             sfree(xyd);
501
502         freetree234(barriers);
503     }
504
505     /*
506      * Set up the barrier corner flags, for drawing barriers
507      * prettily when they meet.
508      */
509     for (y = 0; y < state->height; y++) {
510         for (x = 0; x < state->width; x++) {
511             int dir;
512
513             for (dir = 1; dir < 0x10; dir <<= 1) {
514                 int dir2 = A(dir);
515                 int x1, y1, x2, y2, x3, y3;
516                 int corner = FALSE;
517
518                 if (!(barrier(state, x, y) & dir))
519                     continue;
520
521                 if (barrier(state, x, y) & dir2)
522                     corner = TRUE;
523
524                 x1 = x + X(dir), y1 = y + Y(dir);
525                 if (x1 >= 0 && x1 < state->width &&
526                     y1 >= 0 && y1 < state->height &&
527                     (barrier(state, x1, y1) & dir2))
528                     corner = TRUE;
529
530                 x2 = x + X(dir2), y2 = y + Y(dir2);
531                 if (x2 >= 0 && x2 < state->width &&
532                     y2 >= 0 && y2 < state->height &&
533                     (barrier(state, x2, y2) & dir))
534                     corner = TRUE;
535
536                 if (corner) {
537                     barrier(state, x, y) |= (dir << 4);
538                     if (x1 >= 0 && x1 < state->width &&
539                         y1 >= 0 && y1 < state->height)
540                         barrier(state, x1, y1) |= (A(dir) << 4);
541                     if (x2 >= 0 && x2 < state->width &&
542                         y2 >= 0 && y2 < state->height)
543                         barrier(state, x2, y2) |= (C(dir) << 4);
544                     x3 = x + X(dir) + X(dir2), y3 = y + Y(dir) + Y(dir2);
545                     if (x3 >= 0 && x3 < state->width &&
546                         y3 >= 0 && y3 < state->height)
547                         barrier(state, x3, y3) |= (F(dir) << 4);
548                 }
549             }
550         }
551     }
552
553     random_free(rs);
554
555     return state;
556 }
557
558 game_state *dup_game(game_state *state)
559 {
560     game_state *ret;
561
562     ret = snew(game_state);
563     ret->width = state->width;
564     ret->height = state->height;
565     ret->cx = state->cx;
566     ret->cy = state->cy;
567     ret->wrapping = state->wrapping;
568     ret->completed = state->completed;
569     ret->last_rotate_dir = state->last_rotate_dir;
570     ret->tiles = snewn(state->width * state->height, unsigned char);
571     memcpy(ret->tiles, state->tiles, state->width * state->height);
572     ret->barriers = snewn(state->width * state->height, unsigned char);
573     memcpy(ret->barriers, state->barriers, state->width * state->height);
574
575     return ret;
576 }
577
578 void free_game(game_state *state)
579 {
580     sfree(state->tiles);
581     sfree(state->barriers);
582     sfree(state);
583 }
584
585 /* ----------------------------------------------------------------------
586  * Utility routine.
587  */
588
589 /*
590  * Compute which squares are reachable from the centre square, as a
591  * quick visual aid to determining how close the game is to
592  * completion. This is also a simple way to tell if the game _is_
593  * completed - just call this function and see whether every square
594  * is marked active.
595  */
596 static unsigned char *compute_active(game_state *state)
597 {
598     unsigned char *active;
599     tree234 *todo;
600     struct xyd *xyd;
601
602     active = snewn(state->width * state->height, unsigned char);
603     memset(active, 0, state->width * state->height);
604
605     /*
606      * We only store (x,y) pairs in todo, but it's easier to reuse
607      * xyd_cmp and just store direction 0 every time.
608      */
609     todo = newtree234(xyd_cmp);
610     index(state, active, state->cx, state->cy) = ACTIVE;
611     add234(todo, new_xyd(state->cx, state->cy, 0));
612
613     while ( (xyd = delpos234(todo, 0)) != NULL) {
614         int x1, y1, d1, x2, y2, d2;
615
616         x1 = xyd->x;
617         y1 = xyd->y;
618         sfree(xyd);
619
620         for (d1 = 1; d1 < 0x10; d1 <<= 1) {
621             OFFSET(x2, y2, x1, y1, d1, state);
622             d2 = F(d1);
623
624             /*
625              * If the next tile in this direction is connected to
626              * us, and there isn't a barrier in the way, and it
627              * isn't already marked active, then mark it active and
628              * add it to the to-examine list.
629              */
630             if ((tile(state, x1, y1) & d1) &&
631                 (tile(state, x2, y2) & d2) &&
632                 !(barrier(state, x1, y1) & d1) &&
633                 !index(state, active, x2, y2)) {
634                 index(state, active, x2, y2) = ACTIVE;
635                 add234(todo, new_xyd(x2, y2, 0));
636             }
637         }
638     }
639     /* Now we expect the todo list to have shrunk to zero size. */
640     assert(count234(todo) == 0);
641     freetree234(todo);
642
643     return active;
644 }
645
646 /* ----------------------------------------------------------------------
647  * Process a move.
648  */
649 game_state *make_move(game_state *state, int x, int y, int button)
650 {
651     game_state *ret;
652     int tx, ty, orig;
653
654     /*
655      * All moves in Net are made with the mouse.
656      */
657     if (button != LEFT_BUTTON &&
658         button != MIDDLE_BUTTON &&
659         button != RIGHT_BUTTON)
660         return NULL;
661
662     /*
663      * The button must have been clicked on a valid tile.
664      */
665     x -= WINDOW_OFFSET + TILE_BORDER;
666     y -= WINDOW_OFFSET + TILE_BORDER;
667     if (x < 0 || y < 0)
668         return NULL;
669     tx = x / TILE_SIZE;
670     ty = y / TILE_SIZE;
671     if (tx >= state->width || ty >= state->height)
672         return NULL;
673     if (tx % TILE_SIZE >= TILE_SIZE - TILE_BORDER ||
674         ty % TILE_SIZE >= TILE_SIZE - TILE_BORDER)
675         return NULL;
676
677     /*
678      * The middle button locks or unlocks a tile. (A locked tile
679      * cannot be turned, and is visually marked as being locked.
680      * This is a convenience for the player, so that once they are
681      * sure which way round a tile goes, they can lock it and thus
682      * avoid forgetting later on that they'd already done that one;
683      * and the locking also prevents them turning the tile by
684      * accident. If they change their mind, another middle click
685      * unlocks it.)
686      */
687     if (button == MIDDLE_BUTTON) {
688         ret = dup_game(state);
689         tile(ret, tx, ty) ^= LOCKED;
690         return ret;
691     }
692
693     /*
694      * The left and right buttons have no effect if clicked on a
695      * locked tile.
696      */
697     if (tile(state, tx, ty) & LOCKED)
698         return NULL;
699
700     /*
701      * Otherwise, turn the tile one way or the other. Left button
702      * turns anticlockwise; right button turns clockwise.
703      */
704     ret = dup_game(state);
705     orig = tile(ret, tx, ty);
706     if (button == LEFT_BUTTON) {
707         tile(ret, tx, ty) = A(orig);
708         ret->last_rotate_dir = +1;
709     } else {
710         tile(ret, tx, ty) = C(orig);
711         ret->last_rotate_dir = -1;
712     }
713
714     /*
715      * Check whether the game has been completed.
716      */
717     {
718         unsigned char *active = compute_active(ret);
719         int x1, y1;
720         int complete = TRUE;
721
722         for (x1 = 0; x1 < ret->width; x1++)
723             for (y1 = 0; y1 < ret->height; y1++)
724                 if (!index(ret, active, x1, y1)) {
725                     complete = FALSE;
726                     goto break_label;  /* break out of two loops at once */
727                 }
728         break_label:
729
730         sfree(active);
731
732         if (complete)
733             ret->completed = TRUE;
734     }
735
736     return ret;
737 }
738
739 /* ----------------------------------------------------------------------
740  * Routines for drawing the game position on the screen.
741  */
742
743 struct game_drawstate {
744     int started;
745     int width, height;
746     unsigned char *visible;
747 };
748
749 game_drawstate *game_new_drawstate(game_state *state)
750 {
751     game_drawstate *ds = snew(game_drawstate);
752
753     ds->started = FALSE;
754     ds->width = state->width;
755     ds->height = state->height;
756     ds->visible = snewn(state->width * state->height, unsigned char);
757     memset(ds->visible, 0xFF, state->width * state->height);
758
759     return ds;
760 }
761
762 void game_free_drawstate(game_drawstate *ds)
763 {
764     sfree(ds->visible);
765     sfree(ds);
766 }
767
768 void game_size(game_params *params, int *x, int *y)
769 {
770     *x = WINDOW_OFFSET * 2 + TILE_SIZE * params->width + TILE_BORDER;
771     *y = WINDOW_OFFSET * 2 + TILE_SIZE * params->height + TILE_BORDER;
772 }
773
774 float *game_colours(frontend *fe, game_state *state, int *ncolours)
775 {
776     float *ret;
777
778     ret = snewn(NCOLOURS * 3, float);
779     *ncolours = NCOLOURS;
780
781     /*
782      * Basic background colour is whatever the front end thinks is
783      * a sensible default.
784      */
785     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
786
787     /*
788      * Wires are black.
789      */
790     ret[COL_WIRE * 3 + 0] = 0.0F;
791     ret[COL_WIRE * 3 + 1] = 0.0F;
792     ret[COL_WIRE * 3 + 2] = 0.0F;
793
794     /*
795      * Powered wires and powered endpoints are cyan.
796      */
797     ret[COL_POWERED * 3 + 0] = 0.0F;
798     ret[COL_POWERED * 3 + 1] = 1.0F;
799     ret[COL_POWERED * 3 + 2] = 1.0F;
800
801     /*
802      * Barriers are red.
803      */
804     ret[COL_BARRIER * 3 + 0] = 1.0F;
805     ret[COL_BARRIER * 3 + 1] = 0.0F;
806     ret[COL_BARRIER * 3 + 2] = 0.0F;
807
808     /*
809      * Unpowered endpoints are blue.
810      */
811     ret[COL_ENDPOINT * 3 + 0] = 0.0F;
812     ret[COL_ENDPOINT * 3 + 1] = 0.0F;
813     ret[COL_ENDPOINT * 3 + 2] = 1.0F;
814
815     /*
816      * Tile borders are a darker grey than the background.
817      */
818     ret[COL_BORDER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
819     ret[COL_BORDER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
820     ret[COL_BORDER * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
821
822     /*
823      * Locked tiles are a grey in between those two.
824      */
825     ret[COL_LOCKED * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
826     ret[COL_LOCKED * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
827     ret[COL_LOCKED * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
828
829     return ret;
830 }
831
832 static void draw_thick_line(frontend *fe, int x1, int y1, int x2, int y2,
833                             int colour)
834 {
835     draw_line(fe, x1-1, y1, x2-1, y2, COL_WIRE);
836     draw_line(fe, x1+1, y1, x2+1, y2, COL_WIRE);
837     draw_line(fe, x1, y1-1, x2, y2-1, COL_WIRE);
838     draw_line(fe, x1, y1+1, x2, y2+1, COL_WIRE);
839     draw_line(fe, x1, y1, x2, y2, colour);
840 }
841
842 static void draw_rect_coords(frontend *fe, int x1, int y1, int x2, int y2,
843                              int colour)
844 {
845     int mx = (x1 < x2 ? x1 : x2);
846     int my = (y1 < y2 ? y1 : y2);
847     int dx = (x2 + x1 - 2*mx + 1);
848     int dy = (y2 + y1 - 2*my + 1);
849
850     draw_rect(fe, mx, my, dx, dy, colour);
851 }
852
853 static void draw_barrier_corner(frontend *fe, int x, int y, int dir, int phase)
854 {
855     int bx = WINDOW_OFFSET + TILE_SIZE * x;
856     int by = WINDOW_OFFSET + TILE_SIZE * y;
857     int x1, y1, dx, dy, dir2;
858
859     dir >>= 4;
860
861     dir2 = A(dir);
862     dx = X(dir) + X(dir2);
863     dy = Y(dir) + Y(dir2);
864     x1 = (dx > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
865     y1 = (dy > 0 ? TILE_SIZE+TILE_BORDER-1 : 0);
866
867     if (phase == 0) {
868         draw_rect_coords(fe, bx+x1, by+y1,
869                          bx+x1-TILE_BORDER*dx, by+y1-(TILE_BORDER-1)*dy,
870                          COL_WIRE);
871         draw_rect_coords(fe, bx+x1, by+y1,
872                          bx+x1-(TILE_BORDER-1)*dx, by+y1-TILE_BORDER*dy,
873                          COL_WIRE);
874     } else {
875         draw_rect_coords(fe, bx+x1, by+y1,
876                          bx+x1-(TILE_BORDER-1)*dx, by+y1-(TILE_BORDER-1)*dy,
877                          COL_BARRIER);
878     }
879 }
880
881 static void draw_barrier(frontend *fe, int x, int y, int dir, int phase)
882 {
883     int bx = WINDOW_OFFSET + TILE_SIZE * x;
884     int by = WINDOW_OFFSET + TILE_SIZE * y;
885     int x1, y1, w, h;
886
887     x1 = (X(dir) > 0 ? TILE_SIZE : X(dir) == 0 ? TILE_BORDER : 0);
888     y1 = (Y(dir) > 0 ? TILE_SIZE : Y(dir) == 0 ? TILE_BORDER : 0);
889     w = (X(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
890     h = (Y(dir) ? TILE_BORDER : TILE_SIZE - TILE_BORDER);
891
892     if (phase == 0) {
893         draw_rect(fe, bx+x1-X(dir), by+y1-Y(dir), w, h, COL_WIRE);
894     } else {
895         draw_rect(fe, bx+x1, by+y1, w, h, COL_BARRIER);
896     }
897 }
898
899 static void draw_tile(frontend *fe, game_state *state, int x, int y, int tile,
900                       float angle)
901 {
902     int bx = WINDOW_OFFSET + TILE_SIZE * x;
903     int by = WINDOW_OFFSET + TILE_SIZE * y;
904     float matrix[4];
905     float cx, cy, ex, ey, tx, ty;
906     int dir, col, phase;
907
908     /*
909      * When we draw a single tile, we must draw everything up to
910      * and including the borders around the tile. This means that
911      * if the neighbouring tiles have connections to those borders,
912      * we must draw those connections on the borders themselves.
913      *
914      * This would be terribly fiddly if we ever had to draw a tile
915      * while its neighbour was in mid-rotate, because we'd have to
916      * arrange to _know_ that the neighbour was being rotated and
917      * hence had an anomalous effect on the redraw of this tile.
918      * Fortunately, the drawing algorithm avoids ever calling us in
919      * this circumstance: we're either drawing lots of straight
920      * tiles at game start or after a move is complete, or we're
921      * repeatedly drawing only the rotating tile. So no problem.
922      */
923
924     /*
925      * So. First blank the tile out completely: draw a big
926      * rectangle in border colour, and a smaller rectangle in
927      * background colour to fill it in.
928      */
929     draw_rect(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER,
930               COL_BORDER);
931     draw_rect(fe, bx+TILE_BORDER, by+TILE_BORDER,
932               TILE_SIZE-TILE_BORDER, TILE_SIZE-TILE_BORDER,
933               tile & LOCKED ? COL_LOCKED : COL_BACKGROUND);
934
935     /*
936      * Set up the rotation matrix.
937      */
938     matrix[0] = (float)cos(angle * PI / 180.0);
939     matrix[1] = (float)-sin(angle * PI / 180.0);
940     matrix[2] = (float)sin(angle * PI / 180.0);
941     matrix[3] = (float)cos(angle * PI / 180.0);
942
943     /*
944      * Draw the wires.
945      */
946     cx = cy = TILE_BORDER + (TILE_SIZE-TILE_BORDER) / 2.0F - 0.5F;
947     col = (tile & ACTIVE ? COL_POWERED : COL_WIRE);
948     for (dir = 1; dir < 0x10; dir <<= 1) {
949         if (tile & dir) {
950             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
951             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
952             MATMUL(tx, ty, matrix, ex, ey);
953             draw_thick_line(fe, bx+(int)cx, by+(int)cy,
954                             bx+(int)(cx+tx), by+(int)(cy+ty),
955                             COL_WIRE);
956         }
957     }
958     for (dir = 1; dir < 0x10; dir <<= 1) {
959         if (tile & dir) {
960             ex = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * X(dir);
961             ey = (TILE_SIZE - TILE_BORDER - 1.0F) / 2.0F * Y(dir);
962             MATMUL(tx, ty, matrix, ex, ey);
963             draw_line(fe, bx+(int)cx, by+(int)cy,
964                       bx+(int)(cx+tx), by+(int)(cy+ty), col);
965         }
966     }
967
968     /*
969      * Draw the box in the middle. We do this in blue if the tile
970      * is an unpowered endpoint, in cyan if the tile is a powered
971      * endpoint, in black if the tile is the centrepiece, and
972      * otherwise not at all.
973      */
974     col = -1;
975     if (x == state->cx && y == state->cy)
976         col = COL_WIRE;
977     else if (COUNT(tile) == 1) {
978         col = (tile & ACTIVE ? COL_POWERED : COL_ENDPOINT);
979     }
980     if (col >= 0) {
981         int i, points[8];
982
983         points[0] = +1; points[1] = +1;
984         points[2] = +1; points[3] = -1;
985         points[4] = -1; points[5] = -1;
986         points[6] = -1; points[7] = +1;
987
988         for (i = 0; i < 8; i += 2) {
989             ex = (TILE_SIZE * 0.24F) * points[i];
990             ey = (TILE_SIZE * 0.24F) * points[i+1];
991             MATMUL(tx, ty, matrix, ex, ey);
992             points[i] = bx+(int)(cx+tx);
993             points[i+1] = by+(int)(cy+ty);
994         }
995
996         draw_polygon(fe, points, 4, TRUE, col);
997         draw_polygon(fe, points, 4, FALSE, COL_WIRE);
998     }
999
1000     /*
1001      * Draw the points on the border if other tiles are connected
1002      * to us.
1003      */
1004     for (dir = 1; dir < 0x10; dir <<= 1) {
1005         int dx, dy, px, py, lx, ly, vx, vy, ox, oy;
1006
1007         dx = X(dir);
1008         dy = Y(dir);
1009
1010         ox = x + dx;
1011         oy = y + dy;
1012
1013         if (ox < 0 || ox >= state->width || oy < 0 || oy >= state->height)
1014             continue;
1015
1016         if (!(tile(state, ox, oy) & F(dir)))
1017             continue;
1018
1019         px = bx + (int)(dx>0 ? TILE_SIZE + TILE_BORDER - 1 : dx<0 ? 0 : cx);
1020         py = by + (int)(dy>0 ? TILE_SIZE + TILE_BORDER - 1 : dy<0 ? 0 : cy);
1021         lx = dx * (TILE_BORDER-1);
1022         ly = dy * (TILE_BORDER-1);
1023         vx = (dy ? 1 : 0);
1024         vy = (dx ? 1 : 0);
1025
1026         if (angle == 0.0 && (tile & dir)) {
1027             /*
1028              * If we are fully connected to the other tile, we must
1029              * draw right across the tile border. (We can use our
1030              * own ACTIVE state to determine what colour to do this
1031              * in: if we are fully connected to the other tile then
1032              * the two ACTIVE states will be the same.)
1033              */
1034             draw_rect_coords(fe, px-vx, py-vy, px+lx+vx, py+ly+vy, COL_WIRE);
1035             draw_rect_coords(fe, px, py, px+lx, py+ly,
1036                              (tile & ACTIVE) ? COL_POWERED : COL_WIRE);
1037         } else {
1038             /*
1039              * The other tile extends into our border, but isn't
1040              * actually connected to us. Just draw a single black
1041              * dot.
1042              */
1043             draw_rect_coords(fe, px, py, px, py, COL_WIRE);
1044         }
1045     }
1046
1047     /*
1048      * Draw barrier corners, and then barriers.
1049      */
1050     for (phase = 0; phase < 2; phase++) {
1051         for (dir = 1; dir < 0x10; dir <<= 1)
1052             if (barrier(state, x, y) & (dir << 4))
1053                 draw_barrier_corner(fe, x, y, dir << 4, phase);
1054         for (dir = 1; dir < 0x10; dir <<= 1)
1055             if (barrier(state, x, y) & dir)
1056                 draw_barrier(fe, x, y, dir, phase);
1057     }
1058
1059     draw_update(fe, bx, by, TILE_SIZE+TILE_BORDER, TILE_SIZE+TILE_BORDER);
1060 }
1061
1062 void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1063                  game_state *state, float t, float ft)
1064 {
1065     int x, y, tx, ty, frame;
1066     unsigned char *active;
1067     float angle = 0.0;
1068
1069     /*
1070      * Clear the screen and draw the exterior barrier lines if this
1071      * is our first call.
1072      */
1073     if (!ds->started) {
1074         int phase;
1075
1076         ds->started = TRUE;
1077
1078         draw_rect(fe, 0, 0, 
1079                   WINDOW_OFFSET * 2 + TILE_SIZE * state->width + TILE_BORDER,
1080                   WINDOW_OFFSET * 2 + TILE_SIZE * state->height + TILE_BORDER,
1081                   COL_BACKGROUND);
1082         draw_update(fe, 0, 0, 
1083                     WINDOW_OFFSET*2 + TILE_SIZE*state->width + TILE_BORDER,
1084                     WINDOW_OFFSET*2 + TILE_SIZE*state->height + TILE_BORDER);
1085
1086         for (phase = 0; phase < 2; phase++) {
1087
1088             for (x = 0; x < ds->width; x++) {
1089                 if (barrier(state, x, 0) & UL)
1090                     draw_barrier_corner(fe, x, -1, LD, phase);
1091                 if (barrier(state, x, 0) & RU)
1092                     draw_barrier_corner(fe, x, -1, DR, phase);
1093                 if (barrier(state, x, 0) & U)
1094                     draw_barrier(fe, x, -1, D, phase);
1095                 if (barrier(state, x, ds->height-1) & DR)
1096                     draw_barrier_corner(fe, x, ds->height, RU, phase);
1097                 if (barrier(state, x, ds->height-1) & LD)
1098                     draw_barrier_corner(fe, x, ds->height, UL, phase);
1099                 if (barrier(state, x, ds->height-1) & D)
1100                     draw_barrier(fe, x, ds->height, U, phase);
1101             }
1102
1103             for (y = 0; y < ds->height; y++) {
1104                 if (barrier(state, 0, y) & UL)
1105                     draw_barrier_corner(fe, -1, y, RU, phase);
1106                 if (barrier(state, 0, y) & LD)
1107                     draw_barrier_corner(fe, -1, y, DR, phase);
1108                 if (barrier(state, 0, y) & L)
1109                     draw_barrier(fe, -1, y, R, phase);
1110                 if (barrier(state, ds->width-1, y) & RU)
1111                     draw_barrier_corner(fe, ds->width, y, UL, phase);
1112                 if (barrier(state, ds->width-1, y) & DR)
1113                     draw_barrier_corner(fe, ds->width, y, LD, phase);
1114                 if (barrier(state, ds->width-1, y) & R)
1115                     draw_barrier(fe, ds->width, y, L, phase);
1116             }
1117         }
1118     }
1119
1120     tx = ty = -1;
1121     if (oldstate && (t < ROTATE_TIME)) {
1122         /*
1123          * We're animating a tile rotation. Find the turning tile,
1124          * if any.
1125          */
1126         for (x = 0; x < oldstate->width; x++)
1127             for (y = 0; y < oldstate->height; y++)
1128                 if ((tile(oldstate, x, y) ^ tile(state, x, y)) & 0xF) {
1129                     tx = x, ty = y;
1130                     goto break_label;  /* leave both loops at once */
1131                 }
1132         break_label:
1133
1134         if (tx >= 0) {
1135             if (tile(state, tx, ty) == ROT(tile(oldstate, tx, ty),
1136                                            state->last_rotate_dir))
1137                 angle = state->last_rotate_dir * 90.0F * (t / ROTATE_TIME);
1138             else
1139                 angle = state->last_rotate_dir * -90.0F * (t / ROTATE_TIME);
1140             state = oldstate;
1141         }
1142     }
1143     
1144     frame = -1;
1145     if (ft > 0) {
1146         /*
1147          * We're animating a completion flash. Find which frame
1148          * we're at.
1149          */
1150         frame = (int)(ft / FLASH_FRAME);
1151     }
1152
1153     /*
1154      * Draw any tile which differs from the way it was last drawn.
1155      */
1156     active = compute_active(state);
1157
1158     for (x = 0; x < ds->width; x++)
1159         for (y = 0; y < ds->height; y++) {
1160             unsigned char c = tile(state, x, y) | index(state, active, x, y);
1161
1162             /*
1163              * In a completion flash, we adjust the LOCKED bit
1164              * depending on our distance from the centre point and
1165              * the frame number.
1166              */
1167             if (frame >= 0) {
1168                 int xdist, ydist, dist;
1169                 xdist = (x < state->cx ? state->cx - x : x - state->cx);
1170                 ydist = (y < state->cy ? state->cy - y : y - state->cy);
1171                 dist = (xdist > ydist ? xdist : ydist);
1172
1173                 if (frame >= dist && frame < dist+4) {
1174                     int lock = (frame - dist) & 1;
1175                     lock = lock ? LOCKED : 0;
1176                     c = (c &~ LOCKED) | lock;
1177                 }
1178             }
1179
1180             if (index(state, ds->visible, x, y) != c ||
1181                 index(state, ds->visible, x, y) == 0xFF ||
1182                 (x == tx && y == ty)) {
1183                 draw_tile(fe, state, x, y, c,
1184                           (x == tx && y == ty ? angle : 0.0F));
1185                 if (x == tx && y == ty)
1186                     index(state, ds->visible, x, y) = 0xFF;
1187                 else
1188                     index(state, ds->visible, x, y) = c;
1189             }
1190         }
1191
1192     sfree(active);
1193 }
1194
1195 float game_anim_length(game_state *oldstate, game_state *newstate)
1196 {
1197     int x, y;
1198
1199     /*
1200      * If there's a tile which has been rotated, allow time to
1201      * animate its rotation.
1202      */
1203     for (x = 0; x < oldstate->width; x++)
1204         for (y = 0; y < oldstate->height; y++)
1205             if ((tile(oldstate, x, y) ^ tile(newstate, x, y)) & 0xF) {
1206                 return ROTATE_TIME;
1207             }
1208
1209     return 0.0F;
1210 }
1211
1212 float game_flash_length(game_state *oldstate, game_state *newstate)
1213 {
1214     /*
1215      * If the game has just been completed, we display a completion
1216      * flash.
1217      */
1218     if (!oldstate->completed && newstate->completed) {
1219         int size;
1220         size = 0;
1221         if (size < newstate->cx+1)
1222             size = newstate->cx+1;
1223         if (size < newstate->cy+1)
1224             size = newstate->cy+1;
1225         if (size < newstate->width - newstate->cx)
1226             size = newstate->width - newstate->cx;
1227         if (size < newstate->height - newstate->cy)
1228             size = newstate->height - newstate->cy;
1229         return FLASH_FRAME * (size+4);
1230     }
1231
1232     return 0.0F;
1233 }