chiark / gitweb /
Mines now follows the conventional approach of offering a completely
[sgt-puzzles.git] / rect.c
1 /*
2  * rect.c: Puzzle from nikoli.co.jp. You have a square grid with
3  * numbers in some squares; you must divide the square grid up into
4  * variously sized rectangles, such that every rectangle contains
5  * exactly one numbered square and the area of each rectangle is
6  * equal to the number contained in it.
7  */
8
9 /*
10  * TODO:
11  * 
12  *  - Improve on singleton removal by making an aesthetic choice
13  *    about which of the options to take.
14  * 
15  *  - When doing the 3x3 trick in singleton removal, limit the size
16  *    of the generated rectangles in accordance with the max
17  *    rectangle size.
18  * 
19  *  - If we start by sorting the rectlist in descending order
20  *    of area, we might be able to bias our random number
21  *    selection to produce a few large rectangles more often
22  *    than oodles of small ones? Unsure, but might be worth a
23  *    try.
24  */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <assert.h>
30 #include <ctype.h>
31 #include <math.h>
32
33 #include "puzzles.h"
34
35 enum {
36     COL_BACKGROUND,
37     COL_CORRECT,
38     COL_LINE,
39     COL_TEXT,
40     COL_GRID,
41     COL_DRAG,
42     NCOLOURS
43 };
44
45 struct game_params {
46     int w, h;
47     float expandfactor;
48     int unique;
49 };
50
51 #define INDEX(state, x, y)    (((y) * (state)->w) + (x))
52 #define index(state, a, x, y) ((a) [ INDEX(state,x,y) ])
53 #define grid(state,x,y)       index(state, (state)->grid, x, y)
54 #define vedge(state,x,y)      index(state, (state)->vedge, x, y)
55 #define hedge(state,x,y)      index(state, (state)->hedge, x, y)
56
57 #define CRANGE(state,x,y,dx,dy) ( (x) >= dx && (x) < (state)->w && \
58                                 (y) >= dy && (y) < (state)->h )
59 #define RANGE(state,x,y)  CRANGE(state,x,y,0,0)
60 #define HRANGE(state,x,y) CRANGE(state,x,y,0,1)
61 #define VRANGE(state,x,y) CRANGE(state,x,y,1,0)
62
63 #define TILE_SIZE 24
64 #define BORDER 18
65
66 #define CORNER_TOLERANCE 0.15F
67 #define CENTRE_TOLERANCE 0.15F
68
69 #define FLASH_TIME 0.13F
70
71 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
72 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
73
74 struct game_state {
75     int w, h;
76     int *grid;                         /* contains the numbers */
77     unsigned char *vedge;              /* (w+1) x h */
78     unsigned char *hedge;              /* w x (h+1) */
79     int completed, cheated;
80 };
81
82 static game_params *default_params(void)
83 {
84     game_params *ret = snew(game_params);
85
86     ret->w = ret->h = 7;
87     ret->expandfactor = 0.0F;
88     ret->unique = TRUE;
89
90     return ret;
91 }
92
93 static int game_fetch_preset(int i, char **name, game_params **params)
94 {
95     game_params *ret;
96     int w, h;
97     char buf[80];
98
99     switch (i) {
100       case 0: w = 7, h = 7; break;
101       case 1: w = 11, h = 11; break;
102       case 2: w = 15, h = 15; break;
103       case 3: w = 19, h = 19; break;
104       default: return FALSE;
105     }
106
107     sprintf(buf, "%dx%d", w, h);
108     *name = dupstr(buf);
109     *params = ret = snew(game_params);
110     ret->w = w;
111     ret->h = h;
112     ret->expandfactor = 0.0F;
113     ret->unique = TRUE;
114     return TRUE;
115 }
116
117 static void free_params(game_params *params)
118 {
119     sfree(params);
120 }
121
122 static game_params *dup_params(game_params *params)
123 {
124     game_params *ret = snew(game_params);
125     *ret = *params;                    /* structure copy */
126     return ret;
127 }
128
129 static void decode_params(game_params *ret, char const *string)
130 {
131     ret->w = ret->h = atoi(string);
132     while (*string && isdigit((unsigned char)*string)) string++;
133     if (*string == 'x') {
134         string++;
135         ret->h = atoi(string);
136         while (*string && isdigit((unsigned char)*string)) string++;
137     }
138     if (*string == 'e') {
139         string++;
140         ret->expandfactor = atof(string);
141         while (*string &&
142                (*string == '.' || isdigit((unsigned char)*string))) string++;
143     }
144     if (*string == 'a') {
145         string++;
146         ret->unique = FALSE;
147     }
148 }
149
150 static char *encode_params(game_params *params, int full)
151 {
152     char data[256];
153
154     sprintf(data, "%dx%d", params->w, params->h);
155     if (full && params->expandfactor)
156         sprintf(data + strlen(data), "e%g", params->expandfactor);
157     if (full && !params->unique)
158         strcat(data, "a");
159
160     return dupstr(data);
161 }
162
163 static config_item *game_configure(game_params *params)
164 {
165     config_item *ret;
166     char buf[80];
167
168     ret = snewn(5, config_item);
169
170     ret[0].name = "Width";
171     ret[0].type = C_STRING;
172     sprintf(buf, "%d", params->w);
173     ret[0].sval = dupstr(buf);
174     ret[0].ival = 0;
175
176     ret[1].name = "Height";
177     ret[1].type = C_STRING;
178     sprintf(buf, "%d", params->h);
179     ret[1].sval = dupstr(buf);
180     ret[1].ival = 0;
181
182     ret[2].name = "Expansion factor";
183     ret[2].type = C_STRING;
184     sprintf(buf, "%g", params->expandfactor);
185     ret[2].sval = dupstr(buf);
186     ret[2].ival = 0;
187
188     ret[3].name = "Ensure unique solution";
189     ret[3].type = C_BOOLEAN;
190     ret[3].sval = NULL;
191     ret[3].ival = params->unique;
192
193     ret[4].name = NULL;
194     ret[4].type = C_END;
195     ret[4].sval = NULL;
196     ret[4].ival = 0;
197
198     return ret;
199 }
200
201 static game_params *custom_params(config_item *cfg)
202 {
203     game_params *ret = snew(game_params);
204
205     ret->w = atoi(cfg[0].sval);
206     ret->h = atoi(cfg[1].sval);
207     ret->expandfactor = atof(cfg[2].sval);
208     ret->unique = cfg[3].ival;
209
210     return ret;
211 }
212
213 static char *validate_params(game_params *params)
214 {
215     if (params->w <= 0 && params->h <= 0)
216         return "Width and height must both be greater than zero";
217     if (params->w < 2 && params->h < 2)
218         return "Grid area must be greater than one";
219     if (params->expandfactor < 0.0F)
220         return "Expansion factor may not be negative";
221     return NULL;
222 }
223
224 struct point {
225     int x, y;
226 };
227
228 struct rect {
229     int x, y;
230     int w, h;
231 };
232
233 struct rectlist {
234     struct rect *rects;
235     int n;
236 };
237
238 struct numberdata {
239     int area;
240     int npoints;
241     struct point *points;
242 };
243
244 /* ----------------------------------------------------------------------
245  * Solver for Rectangles games.
246  * 
247  * This solver is souped up beyond the needs of actually _solving_
248  * a puzzle. It is also designed to cope with uncertainty about
249  * where the numbers have been placed. This is because I run it on
250  * my generated grids _before_ placing the numbers, and have it
251  * tell me where I need to place the numbers to ensure a unique
252  * solution.
253  */
254
255 static void remove_rect_placement(int w, int h,
256                                   struct rectlist *rectpositions,
257                                   int *overlaps,
258                                   int rectnum, int placement)
259 {
260     int x, y, xx, yy;
261
262 #ifdef SOLVER_DIAGNOSTICS
263     printf("ruling out rect %d placement at %d,%d w=%d h=%d\n", rectnum,
264            rectpositions[rectnum].rects[placement].x,
265            rectpositions[rectnum].rects[placement].y,
266            rectpositions[rectnum].rects[placement].w,
267            rectpositions[rectnum].rects[placement].h);
268 #endif
269
270     /*
271      * Decrement each entry in the overlaps array to reflect the
272      * removal of this rectangle placement.
273      */
274     for (yy = 0; yy < rectpositions[rectnum].rects[placement].h; yy++) {
275         y = yy + rectpositions[rectnum].rects[placement].y;
276         for (xx = 0; xx < rectpositions[rectnum].rects[placement].w; xx++) {
277             x = xx + rectpositions[rectnum].rects[placement].x;
278
279             assert(overlaps[(rectnum * h + y) * w + x] != 0);
280
281             if (overlaps[(rectnum * h + y) * w + x] > 0)
282                 overlaps[(rectnum * h + y) * w + x]--;
283         }
284     }
285
286     /*
287      * Remove the placement from the list of positions for that
288      * rectangle, by interchanging it with the one on the end.
289      */
290     if (placement < rectpositions[rectnum].n - 1) {
291         struct rect t;
292
293         t = rectpositions[rectnum].rects[rectpositions[rectnum].n - 1];
294         rectpositions[rectnum].rects[rectpositions[rectnum].n - 1] =
295             rectpositions[rectnum].rects[placement];
296         rectpositions[rectnum].rects[placement] = t;
297     }
298     rectpositions[rectnum].n--;
299 }
300
301 static void remove_number_placement(int w, int h, struct numberdata *number,
302                                     int index, int *rectbyplace)
303 {
304     /*
305      * Remove the entry from the rectbyplace array.
306      */
307     rectbyplace[number->points[index].y * w + number->points[index].x] = -1;
308
309     /*
310      * Remove the placement from the list of candidates for that
311      * number, by interchanging it with the one on the end.
312      */
313     if (index < number->npoints - 1) {
314         struct point t;
315
316         t = number->points[number->npoints - 1];
317         number->points[number->npoints - 1] = number->points[index];
318         number->points[index] = t;
319     }
320     number->npoints--;
321 }
322
323 static int rect_solver(int w, int h, int nrects, struct numberdata *numbers,
324                        game_state *result, random_state *rs)
325 {
326     struct rectlist *rectpositions;
327     int *overlaps, *rectbyplace, *workspace;
328     int i, ret;
329
330     /*
331      * Start by setting up a list of candidate positions for each
332      * rectangle.
333      */
334     rectpositions = snewn(nrects, struct rectlist);
335     for (i = 0; i < nrects; i++) {
336         int rw, rh, area = numbers[i].area;
337         int j, minx, miny, maxx, maxy;
338         struct rect *rlist;
339         int rlistn, rlistsize;
340
341         /*
342          * For each rectangle, begin by finding the bounding
343          * rectangle of its candidate number placements.
344          */
345         maxx = maxy = -1;
346         minx = w;
347         miny = h;
348         for (j = 0; j < numbers[i].npoints; j++) {
349             if (minx > numbers[i].points[j].x) minx = numbers[i].points[j].x;
350             if (miny > numbers[i].points[j].y) miny = numbers[i].points[j].y;
351             if (maxx < numbers[i].points[j].x) maxx = numbers[i].points[j].x;
352             if (maxy < numbers[i].points[j].y) maxy = numbers[i].points[j].y;
353         }
354
355         /*
356          * Now loop over all possible rectangle placements
357          * overlapping a point within that bounding rectangle;
358          * ensure each one actually contains a candidate number
359          * placement, and add it to the list.
360          */
361         rlist = NULL;
362         rlistn = rlistsize = 0;
363
364         for (rw = 1; rw <= area && rw <= w; rw++) {
365             int x, y;
366
367             if (area % rw)
368                 continue;
369             rh = area / rw;
370             if (rh > h)
371                 continue;
372
373             for (y = miny - rh + 1; y <= maxy; y++) {
374                 if (y < 0 || y+rh > h)
375                     continue;
376
377                 for (x = minx - rw + 1; x <= maxx; x++) {
378                     if (x < 0 || x+rw > w)
379                         continue;
380
381                     /*
382                      * See if we can find a candidate number
383                      * placement within this rectangle.
384                      */
385                     for (j = 0; j < numbers[i].npoints; j++)
386                         if (numbers[i].points[j].x >= x &&
387                             numbers[i].points[j].x < x+rw &&
388                             numbers[i].points[j].y >= y &&
389                             numbers[i].points[j].y < y+rh)
390                             break;
391
392                     if (j < numbers[i].npoints) {
393                         /*
394                          * Add this to the list of candidate
395                          * placements for this rectangle.
396                          */
397                         if (rlistn >= rlistsize) {
398                             rlistsize = rlistn + 32;
399                             rlist = sresize(rlist, rlistsize, struct rect);
400                         }
401                         rlist[rlistn].x = x;
402                         rlist[rlistn].y = y;
403                         rlist[rlistn].w = rw;
404                         rlist[rlistn].h = rh;
405 #ifdef SOLVER_DIAGNOSTICS
406                         printf("rect %d [area %d]: candidate position at"
407                                " %d,%d w=%d h=%d\n",
408                                i, area, x, y, rw, rh);
409 #endif
410                         rlistn++;
411                     }
412                 }
413             }
414         }
415
416         rectpositions[i].rects = rlist;
417         rectpositions[i].n = rlistn;
418     }
419
420     /*
421      * Next, construct a multidimensional array tracking how many
422      * candidate positions for each rectangle overlap each square.
423      * 
424      * Indexing of this array is by the formula
425      * 
426      *   overlaps[(rectindex * h + y) * w + x]
427      */
428     overlaps = snewn(nrects * w * h, int);
429     memset(overlaps, 0, nrects * w * h * sizeof(int));
430     for (i = 0; i < nrects; i++) {
431         int j;
432
433         for (j = 0; j < rectpositions[i].n; j++) {
434             int xx, yy;
435
436             for (yy = 0; yy < rectpositions[i].rects[j].h; yy++)
437                 for (xx = 0; xx < rectpositions[i].rects[j].w; xx++)
438                     overlaps[(i * h + yy+rectpositions[i].rects[j].y) * w +
439                              xx+rectpositions[i].rects[j].x]++;
440         }
441     }
442
443     /*
444      * Also we want an array covering the grid once, to make it
445      * easy to figure out which squares are candidate number
446      * placements for which rectangles. (The existence of this
447      * single array assumes that no square starts off as a
448      * candidate number placement for more than one rectangle. This
449      * assumption is justified, because this solver is _either_
450      * used to solve real problems - in which case there is a
451      * single placement for every number - _or_ used to decide on
452      * number placements for a new puzzle, in which case each
453      * number's placements are confined to the intended position of
454      * the rectangle containing that number.)
455      */
456     rectbyplace = snewn(w * h, int);
457     for (i = 0; i < w*h; i++)
458         rectbyplace[i] = -1;
459
460     for (i = 0; i < nrects; i++) {
461         int j;
462
463         for (j = 0; j < numbers[i].npoints; j++) {
464             int x = numbers[i].points[j].x;
465             int y = numbers[i].points[j].y;
466
467             assert(rectbyplace[y * w + x] == -1);
468             rectbyplace[y * w + x] = i;
469         }
470     }
471
472     workspace = snewn(nrects, int);
473
474     /*
475      * Now run the actual deduction loop.
476      */
477     while (1) {
478         int done_something = FALSE;
479
480 #ifdef SOLVER_DIAGNOSTICS
481         printf("starting deduction loop\n");
482
483         for (i = 0; i < nrects; i++) {
484             printf("rect %d overlaps:\n", i);
485             {
486                 int x, y;
487                 for (y = 0; y < h; y++) {
488                     for (x = 0; x < w; x++) {
489                         printf("%3d", overlaps[(i * h + y) * w + x]);
490                     }
491                     printf("\n");
492                 }
493             }
494         }
495         printf("rectbyplace:\n");
496         {
497             int x, y;
498             for (y = 0; y < h; y++) {
499                 for (x = 0; x < w; x++) {
500                     printf("%3d", rectbyplace[y * w + x]);
501                 }
502                 printf("\n");
503             }
504         }
505 #endif
506
507         /*
508          * Housekeeping. Look for rectangles whose number has only
509          * one candidate position left, and mark that square as
510          * known if it isn't already.
511          */
512         for (i = 0; i < nrects; i++) {
513             if (numbers[i].npoints == 1) {
514                 int x = numbers[i].points[0].x;
515                 int y = numbers[i].points[0].y;
516                 if (overlaps[(i * h + y) * w + x] >= -1) {
517                     int j;
518
519                     assert(overlaps[(i * h + y) * w + x] > 0);
520 #ifdef SOLVER_DIAGNOSTICS
521                     printf("marking %d,%d as known for rect %d"
522                            " (sole remaining number position)\n", x, y, i);
523 #endif
524
525                     for (j = 0; j < nrects; j++)
526                         overlaps[(j * h + y) * w + x] = -1;
527                     
528                     overlaps[(i * h + y) * w + x] = -2;
529                 }
530             }
531         }
532
533         /*
534          * Now look at the intersection of all possible placements
535          * for each rectangle, and mark all squares in that
536          * intersection as known for that rectangle if they aren't
537          * already.
538          */
539         for (i = 0; i < nrects; i++) {
540             int minx, miny, maxx, maxy, xx, yy, j;
541
542             minx = miny = 0;
543             maxx = w;
544             maxy = h;
545
546             for (j = 0; j < rectpositions[i].n; j++) {
547                 int x = rectpositions[i].rects[j].x;
548                 int y = rectpositions[i].rects[j].y;
549                 int w = rectpositions[i].rects[j].w;
550                 int h = rectpositions[i].rects[j].h;
551
552                 if (minx < x) minx = x;
553                 if (miny < y) miny = y;
554                 if (maxx > x+w) maxx = x+w;
555                 if (maxy > y+h) maxy = y+h;
556             }
557
558             for (yy = miny; yy < maxy; yy++)
559                 for (xx = minx; xx < maxx; xx++)
560                     if (overlaps[(i * h + yy) * w + xx] >= -1) {
561                         assert(overlaps[(i * h + yy) * w + xx] > 0);
562 #ifdef SOLVER_DIAGNOSTICS
563                         printf("marking %d,%d as known for rect %d"
564                                " (intersection of all placements)\n",
565                                xx, yy, i);
566 #endif
567
568                         for (j = 0; j < nrects; j++)
569                             overlaps[(j * h + yy) * w + xx] = -1;
570                     
571                         overlaps[(i * h + yy) * w + xx] = -2;
572                     }
573         }
574
575         /*
576          * Rectangle-focused deduction. Look at each rectangle in
577          * turn and try to rule out some of its candidate
578          * placements.
579          */
580         for (i = 0; i < nrects; i++) {
581             int j;
582
583             for (j = 0; j < rectpositions[i].n; j++) {
584                 int xx, yy, k;
585                 int del = FALSE;
586
587                 for (k = 0; k < nrects; k++)
588                     workspace[k] = 0;
589
590                 for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
591                     int y = yy + rectpositions[i].rects[j].y;
592                     for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
593                         int x = xx + rectpositions[i].rects[j].x;
594  
595                         if (overlaps[(i * h + y) * w + x] == -1) {
596                             /*
597                              * This placement overlaps a square
598                              * which is _known_ to be part of
599                              * another rectangle. Therefore we must
600                              * rule it out.
601                              */
602 #ifdef SOLVER_DIAGNOSTICS
603                             printf("rect %d placement at %d,%d w=%d h=%d "
604                                    "contains %d,%d which is known-other\n", i,
605                                    rectpositions[i].rects[j].x,
606                                    rectpositions[i].rects[j].y,
607                                    rectpositions[i].rects[j].w,
608                                    rectpositions[i].rects[j].h,
609                                    x, y);
610 #endif
611                             del = TRUE;
612                         }
613
614                         if (rectbyplace[y * w + x] != -1) {
615                             /*
616                              * This placement overlaps one of the
617                              * candidate number placements for some
618                              * rectangle. Count it.
619                              */
620                             workspace[rectbyplace[y * w + x]]++;
621                         }
622                     }
623                 }
624
625                 if (!del) {
626                     /*
627                      * If we haven't ruled this placement out
628                      * already, see if it overlaps _all_ of the
629                      * candidate number placements for any
630                      * rectangle. If so, we can rule it out.
631                      */
632                     for (k = 0; k < nrects; k++)
633                         if (k != i && workspace[k] == numbers[k].npoints) {
634 #ifdef SOLVER_DIAGNOSTICS
635                             printf("rect %d placement at %d,%d w=%d h=%d "
636                                    "contains all number points for rect %d\n",
637                                    i,
638                                    rectpositions[i].rects[j].x,
639                                    rectpositions[i].rects[j].y,
640                                    rectpositions[i].rects[j].w,
641                                    rectpositions[i].rects[j].h,
642                                    k);
643 #endif
644                             del = TRUE;
645                             break;
646                         }
647
648                     /*
649                      * Failing that, see if it overlaps at least
650                      * one of the candidate number placements for
651                      * itself! (This might not be the case if one
652                      * of those number placements has been removed
653                      * recently.).
654                      */
655                     if (!del && workspace[i] == 0) {
656 #ifdef SOLVER_DIAGNOSTICS
657                         printf("rect %d placement at %d,%d w=%d h=%d "
658                                "contains none of its own number points\n",
659                                i,
660                                rectpositions[i].rects[j].x,
661                                rectpositions[i].rects[j].y,
662                                rectpositions[i].rects[j].w,
663                                rectpositions[i].rects[j].h);
664 #endif
665                         del = TRUE;
666                     }
667                 }
668
669                 if (del) {
670                     remove_rect_placement(w, h, rectpositions, overlaps, i, j);
671
672                     j--;               /* don't skip over next placement */
673
674                     done_something = TRUE;
675                 }
676             }
677         }
678
679         /*
680          * Square-focused deduction. Look at each square not marked
681          * as known, and see if there are any which can only be
682          * part of a single rectangle.
683          */
684         {
685             int x, y, n, index;
686             for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
687                 /* Known squares are marked as <0 everywhere, so we only need
688                  * to check the overlaps entry for rect 0. */
689                 if (overlaps[y * w + x] < 0)
690                     continue;          /* known already */
691
692                 n = 0;
693                 index = -1;
694                 for (i = 0; i < nrects; i++)
695                     if (overlaps[(i * h + y) * w + x] > 0)
696                         n++, index = i;
697
698                 if (n == 1) {
699                     int j;
700
701                     /*
702                      * Now we can rule out all placements for
703                      * rectangle `index' which _don't_ contain
704                      * square x,y.
705                      */
706 #ifdef SOLVER_DIAGNOSTICS
707                     printf("square %d,%d can only be in rectangle %d\n",
708                            x, y, index);
709 #endif
710                     for (j = 0; j < rectpositions[index].n; j++) {
711                         struct rect *r = &rectpositions[index].rects[j];
712                         if (x >= r->x && x < r->x + r->w &&
713                             y >= r->y && y < r->y + r->h)
714                             continue;  /* this one is OK */
715                         remove_rect_placement(w, h, rectpositions, overlaps,
716                                               index, j);
717                         j--;           /* don't skip over next placement */
718                         done_something = TRUE;
719                     }
720                 }
721             }
722         }
723
724         /*
725          * If we've managed to deduce anything by normal means,
726          * loop round again and see if there's more to be done.
727          * Only if normal deduction has completely failed us should
728          * we now move on to narrowing down the possible number
729          * placements.
730          */
731         if (done_something)
732             continue;
733
734         /*
735          * Now we have done everything we can with the current set
736          * of number placements. So we need to winnow the number
737          * placements so as to narrow down the possibilities. We do
738          * this by searching for a candidate placement (of _any_
739          * rectangle) which overlaps a candidate placement of the
740          * number for some other rectangle.
741          */
742         if (rs) {
743             struct rpn {
744                 int rect;
745                 int placement;
746                 int number;
747             } *rpns = NULL;
748             int nrpns = 0, rpnsize = 0;
749             int j;
750
751             for (i = 0; i < nrects; i++) {
752                 for (j = 0; j < rectpositions[i].n; j++) {
753                     int xx, yy;
754
755                     for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
756                         int y = yy + rectpositions[i].rects[j].y;
757                         for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
758                             int x = xx + rectpositions[i].rects[j].x;
759
760                             if (rectbyplace[y * w + x] >= 0 &&
761                                 rectbyplace[y * w + x] != i) {
762                                 /*
763                                  * Add this to the list of
764                                  * winnowing possibilities.
765                                  */
766                                 if (nrpns >= rpnsize) {
767                                     rpnsize = rpnsize * 3 / 2 + 32;
768                                     rpns = sresize(rpns, rpnsize, struct rpn);
769                                 }
770                                 rpns[nrpns].rect = i;
771                                 rpns[nrpns].placement = j;
772                                 rpns[nrpns].number = rectbyplace[y * w + x];
773                                 nrpns++;
774                             }
775                         }
776                     }
777  
778                 }
779             }
780
781 #ifdef SOLVER_DIAGNOSTICS
782             printf("%d candidate rect placements we could eliminate\n", nrpns);
783 #endif
784             if (nrpns > 0) {
785                 /*
786                  * Now choose one of these unwanted rectangle
787                  * placements, and eliminate it.
788                  */
789                 int index = random_upto(rs, nrpns);
790                 int k, m;
791                 struct rpn rpn = rpns[index];
792                 struct rect r;
793                 sfree(rpns);
794
795                 i = rpn.rect;
796                 j = rpn.placement;
797                 k = rpn.number;
798                 r = rectpositions[i].rects[j];
799
800                 /*
801                  * We rule out placement j of rectangle i by means
802                  * of removing all of rectangle k's candidate
803                  * number placements which do _not_ overlap it.
804                  * This will ensure that it is eliminated during
805                  * the next pass of rectangle-focused deduction.
806                  */
807 #ifdef SOLVER_DIAGNOSTICS
808                 printf("ensuring number for rect %d is within"
809                        " rect %d's placement at %d,%d w=%d h=%d\n",
810                        k, i, r.x, r.y, r.w, r.h);
811 #endif
812
813                 for (m = 0; m < numbers[k].npoints; m++) {
814                     int x = numbers[k].points[m].x;
815                     int y = numbers[k].points[m].y;
816
817                     if (x < r.x || x >= r.x + r.w ||
818                         y < r.y || y >= r.y + r.h) {
819 #ifdef SOLVER_DIAGNOSTICS
820                         printf("eliminating number for rect %d at %d,%d\n",
821                                k, x, y);
822 #endif
823                         remove_number_placement(w, h, &numbers[k],
824                                                 m, rectbyplace);
825                         m--;           /* don't skip the next one */
826                         done_something = TRUE;
827                     }
828                 }
829             }
830         }
831
832         if (!done_something) {
833 #ifdef SOLVER_DIAGNOSTICS
834             printf("terminating deduction loop\n");
835 #endif
836             break;
837         }
838     }
839
840     ret = TRUE;
841     for (i = 0; i < nrects; i++) {
842 #ifdef SOLVER_DIAGNOSTICS
843         printf("rect %d has %d possible placements\n",
844                i, rectpositions[i].n);
845 #endif
846         assert(rectpositions[i].n > 0);
847         if (rectpositions[i].n > 1) {
848             ret = FALSE;
849         } else if (result) {
850             /*
851              * Place the rectangle in its only possible position.
852              */
853             int x, y;
854             struct rect *r = &rectpositions[i].rects[0];
855
856             for (y = 0; y < r->h; y++) {
857                 if (r->x > 0)
858                     vedge(result, r->x, r->y+y) = 1;
859                 if (r->x+r->w < result->w)
860                     vedge(result, r->x+r->w, r->y+y) = 1;
861             }
862             for (x = 0; x < r->w; x++) {
863                 if (r->y > 0)
864                     hedge(result, r->x+x, r->y) = 1;
865                 if (r->y+r->h < result->h)
866                     hedge(result, r->x+x, r->y+r->h) = 1;
867             }
868         }
869     }
870
871     /*
872      * Free up all allocated storage.
873      */
874     sfree(workspace);
875     sfree(rectbyplace);
876     sfree(overlaps);
877     for (i = 0; i < nrects; i++)
878         sfree(rectpositions[i].rects);
879     sfree(rectpositions);
880
881     return ret;
882 }
883
884 /* ----------------------------------------------------------------------
885  * Grid generation code.
886  */
887
888 static struct rectlist *get_rectlist(game_params *params, int *grid)
889 {
890     int rw, rh;
891     int x, y;
892     int maxarea;
893     struct rect *rects = NULL;
894     int nrects = 0, rectsize = 0;
895
896     /*
897      * Maximum rectangle area is 1/6 of total grid size, unless
898      * this means we can't place any rectangles at all in which
899      * case we set it to 2 at minimum.
900      */
901     maxarea = params->w * params->h / 6;
902     if (maxarea < 2)
903         maxarea = 2;
904
905     for (rw = 1; rw <= params->w; rw++)
906         for (rh = 1; rh <= params->h; rh++) {
907             if (rw * rh > maxarea)
908                 continue;
909             if (rw * rh == 1)
910                 continue;
911             for (x = 0; x <= params->w - rw; x++)
912                 for (y = 0; y <= params->h - rh; y++) {
913                     if (nrects >= rectsize) {
914                         rectsize = nrects + 256;
915                         rects = sresize(rects, rectsize, struct rect);
916                     }
917
918                     rects[nrects].x = x;
919                     rects[nrects].y = y;
920                     rects[nrects].w = rw;
921                     rects[nrects].h = rh;
922                     nrects++;
923                 }
924         }
925
926     if (nrects > 0) {
927         struct rectlist *ret;
928         ret = snew(struct rectlist);
929         ret->rects = rects;
930         ret->n = nrects;
931         return ret;
932     } else {
933         assert(rects == NULL);         /* hence no need to free */
934         return NULL;
935     }
936 }
937
938 static void free_rectlist(struct rectlist *list)
939 {
940     sfree(list->rects);
941     sfree(list);
942 }
943
944 static void place_rect(game_params *params, int *grid, struct rect r)
945 {
946     int idx = INDEX(params, r.x, r.y);
947     int x, y;
948
949     for (x = r.x; x < r.x+r.w; x++)
950         for (y = r.y; y < r.y+r.h; y++) {
951             index(params, grid, x, y) = idx;
952         }
953 #ifdef GENERATION_DIAGNOSTICS
954     printf("    placing rectangle at (%d,%d) size %d x %d\n",
955            r.x, r.y, r.w, r.h);
956 #endif
957 }
958
959 static struct rect find_rect(game_params *params, int *grid, int x, int y)
960 {
961     int idx, w, h;
962     struct rect r;
963
964     /*
965      * Find the top left of the rectangle.
966      */
967     idx = index(params, grid, x, y);
968
969     if (idx < 0) {
970         r.x = x;
971         r.y = y;
972         r.w = r.h = 1;
973         return r;                      /* 1x1 singleton here */
974     }
975
976     y = idx / params->w;
977     x = idx % params->w;
978
979     /*
980      * Find the width and height of the rectangle.
981      */
982     for (w = 1;
983          (x+w < params->w && index(params,grid,x+w,y)==idx);
984          w++);
985     for (h = 1;
986          (y+h < params->h && index(params,grid,x,y+h)==idx);
987          h++);
988
989     r.x = x;
990     r.y = y;
991     r.w = w;
992     r.h = h;
993
994     return r;
995 }
996
997 #ifdef GENERATION_DIAGNOSTICS
998 static void display_grid(game_params *params, int *grid, int *numbers, int all)
999 {
1000     unsigned char *egrid = snewn((params->w*2+3) * (params->h*2+3),
1001                                  unsigned char);
1002     int x, y;
1003     int r = (params->w*2+3);
1004
1005     memset(egrid, 0, (params->w*2+3) * (params->h*2+3));
1006
1007     for (x = 0; x < params->w; x++)
1008         for (y = 0; y < params->h; y++) {
1009             int i = index(params, grid, x, y);
1010             if (x == 0 || index(params, grid, x-1, y) != i)
1011                 egrid[(2*y+2) * r + (2*x+1)] = 1;
1012             if (x == params->w-1 || index(params, grid, x+1, y) != i)
1013                 egrid[(2*y+2) * r + (2*x+3)] = 1;
1014             if (y == 0 || index(params, grid, x, y-1) != i)
1015                 egrid[(2*y+1) * r + (2*x+2)] = 1;
1016             if (y == params->h-1 || index(params, grid, x, y+1) != i)
1017                 egrid[(2*y+3) * r + (2*x+2)] = 1;
1018         }
1019
1020     for (y = 1; y < 2*params->h+2; y++) {
1021         for (x = 1; x < 2*params->w+2; x++) {
1022             if (!((y|x)&1)) {
1023                 int k = numbers ? index(params, numbers, x/2-1, y/2-1) : 0;
1024                 if (k || (all && numbers)) printf("%2d", k); else printf("  ");
1025             } else if (!((y&x)&1)) {
1026                 int v = egrid[y*r+x];
1027                 if ((y&1) && v) v = '-';
1028                 if ((x&1) && v) v = '|';
1029                 if (!v) v = ' ';
1030                 putchar(v);
1031                 if (!(x&1)) putchar(v);
1032             } else {
1033                 int c, d = 0;
1034                 if (egrid[y*r+(x+1)]) d |= 1;
1035                 if (egrid[(y-1)*r+x]) d |= 2;
1036                 if (egrid[y*r+(x-1)]) d |= 4;
1037                 if (egrid[(y+1)*r+x]) d |= 8;
1038                 c = " ??+?-++?+|+++++"[d];
1039                 putchar(c);
1040                 if (!(x&1)) putchar(c);
1041             }
1042         }
1043         putchar('\n');
1044     }
1045
1046     sfree(egrid);
1047 }
1048 #endif
1049
1050 struct game_aux_info {
1051     int w, h;
1052     unsigned char *vedge;              /* (w+1) x h */
1053     unsigned char *hedge;              /* w x (h+1) */
1054 };
1055
1056 static char *new_game_desc(game_params *params, random_state *rs,
1057                            game_aux_info **aux)
1058 {
1059     int *grid, *numbers = NULL;
1060     struct rectlist *list;
1061     int x, y, y2, y2last, yx, run, i;
1062     char *desc, *p;
1063     game_params params2real, *params2 = &params2real;
1064
1065     while (1) {
1066         /*
1067          * Set up the smaller width and height which we will use to
1068          * generate the base grid.
1069          */
1070         params2->w = params->w / (1.0F + params->expandfactor);
1071         if (params2->w < 2 && params->w >= 2) params2->w = 2;
1072         params2->h = params->h / (1.0F + params->expandfactor);
1073         if (params2->h < 2 && params->h >= 2) params2->h = 2;
1074
1075         grid = snewn(params2->w * params2->h, int);
1076
1077         for (y = 0; y < params2->h; y++)
1078             for (x = 0; x < params2->w; x++) {
1079                 index(params2, grid, x, y) = -1;
1080             }
1081
1082         list = get_rectlist(params2, grid);
1083         assert(list != NULL);
1084
1085         /*
1086          * Place rectangles until we can't any more.
1087          */
1088         while (list->n > 0) {
1089             int i, m;
1090             struct rect r;
1091
1092             /*
1093              * Pick a random rectangle.
1094              */
1095             i = random_upto(rs, list->n);
1096             r = list->rects[i];
1097
1098             /*
1099              * Place it.
1100              */
1101             place_rect(params2, grid, r);
1102
1103             /*
1104              * Winnow the list by removing any rectangles which
1105              * overlap this one.
1106              */
1107             m = 0;
1108             for (i = 0; i < list->n; i++) {
1109                 struct rect s = list->rects[i];
1110                 if (s.x+s.w <= r.x || r.x+r.w <= s.x ||
1111                     s.y+s.h <= r.y || r.y+r.h <= s.y)
1112                     list->rects[m++] = s;
1113             }
1114             list->n = m;
1115         }
1116
1117         free_rectlist(list);
1118
1119         /*
1120          * Deal with singleton spaces remaining in the grid, one by
1121          * one.
1122          *
1123          * We do this by making a local change to the layout. There are
1124          * several possibilities:
1125          *
1126          *     +-----+-----+    Here, we can remove the singleton by
1127          *     |     |     |    extending the 1x2 rectangle below it
1128          *     +--+--+-----+    into a 1x3.
1129          *     |  |  |     |
1130          *     |  +--+     |
1131          *     |  |  |     |
1132          *     |  |  |     |
1133          *     |  |  |     |
1134          *     +--+--+-----+
1135          *
1136          *     +--+--+--+       Here, that trick doesn't work: there's no
1137          *     |     |  |       1 x n rectangle with the singleton at one
1138          *     |     |  |       end. Instead, we extend a 1 x n rectangle
1139          *     |     |  |       _out_ from the singleton, shaving a layer
1140          *     +--+--+  |       off the end of another rectangle. So if we
1141          *     |  |  |  |       extended up, we'd make our singleton part
1142          *     |  +--+--+       of a 1x3 and generate a 1x2 where the 2x2
1143          *     |  |     |       used to be; or we could extend right into
1144          *     +--+-----+       a 2x1, turning the 1x3 into a 1x2.
1145          *
1146          *     +-----+--+       Here, we can't even do _that_, since any
1147          *     |     |  |       direction we choose to extend the singleton
1148          *     +--+--+  |       will produce a new singleton as a result of
1149          *     |  |  |  |       truncating one of the size-2 rectangles.
1150          *     |  +--+--+       Fortunately, this case can _only_ occur when
1151          *     |  |     |       a singleton is surrounded by four size-2s
1152          *     +--+-----+       in this fashion; so instead we can simply
1153          *                      replace the whole section with a single 3x3.
1154          */
1155         for (x = 0; x < params2->w; x++) {
1156             for (y = 0; y < params2->h; y++) {
1157                 if (index(params2, grid, x, y) < 0) {
1158                     int dirs[4], ndirs;
1159
1160 #ifdef GENERATION_DIAGNOSTICS
1161                     display_grid(params2, grid, NULL, FALSE);
1162                     printf("singleton at %d,%d\n", x, y);
1163 #endif
1164
1165                     /*
1166                      * Check in which directions we can feasibly extend
1167                      * the singleton. We can extend in a particular
1168                      * direction iff either:
1169                      *
1170                      *  - the rectangle on that side of the singleton
1171                      *    is not 2x1, and we are at one end of the edge
1172                      *    of it we are touching
1173                      *
1174                      *  - it is 2x1 but we are on its short side.
1175                      *
1176                      * FIXME: we could plausibly choose between these
1177                      * based on the sizes of the rectangles they would
1178                      * create?
1179                      */
1180                     ndirs = 0;
1181                     if (x < params2->w-1) {
1182                         struct rect r = find_rect(params2, grid, x+1, y);
1183                         if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1184                             dirs[ndirs++] = 1;   /* right */
1185                     }
1186                     if (y > 0) {
1187                         struct rect r = find_rect(params2, grid, x, y-1);
1188                         if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1189                             dirs[ndirs++] = 2;   /* up */
1190                     }
1191                     if (x > 0) {
1192                         struct rect r = find_rect(params2, grid, x-1, y);
1193                         if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1194                             dirs[ndirs++] = 4;   /* left */
1195                     }
1196                     if (y < params2->h-1) {
1197                         struct rect r = find_rect(params2, grid, x, y+1);
1198                         if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1199                             dirs[ndirs++] = 8;   /* down */
1200                     }
1201
1202                     if (ndirs > 0) {
1203                         int which, dir;
1204                         struct rect r1, r2;
1205
1206                         which = random_upto(rs, ndirs);
1207                         dir = dirs[which];
1208
1209                         switch (dir) {
1210                           case 1:          /* right */
1211                             assert(x < params2->w+1);
1212 #ifdef GENERATION_DIAGNOSTICS
1213                             printf("extending right\n");
1214 #endif
1215                             r1 = find_rect(params2, grid, x+1, y);
1216                             r2.x = x;
1217                             r2.y = y;
1218                             r2.w = 1 + r1.w;
1219                             r2.h = 1;
1220                             if (r1.y == y)
1221                                 r1.y++;
1222                             r1.h--;
1223                             break;
1224                           case 2:          /* up */
1225                             assert(y > 0);
1226 #ifdef GENERATION_DIAGNOSTICS
1227                             printf("extending up\n");
1228 #endif
1229                             r1 = find_rect(params2, grid, x, y-1);
1230                             r2.x = x;
1231                             r2.y = r1.y;
1232                             r2.w = 1;
1233                             r2.h = 1 + r1.h;
1234                             if (r1.x == x)
1235                                 r1.x++;
1236                             r1.w--;
1237                             break;
1238                           case 4:          /* left */
1239                             assert(x > 0);
1240 #ifdef GENERATION_DIAGNOSTICS
1241                             printf("extending left\n");
1242 #endif
1243                             r1 = find_rect(params2, grid, x-1, y);
1244                             r2.x = r1.x;
1245                             r2.y = y;
1246                             r2.w = 1 + r1.w;
1247                             r2.h = 1;
1248                             if (r1.y == y)
1249                                 r1.y++;
1250                             r1.h--;
1251                             break;
1252                           case 8:          /* down */
1253                             assert(y < params2->h+1);
1254 #ifdef GENERATION_DIAGNOSTICS
1255                             printf("extending down\n");
1256 #endif
1257                             r1 = find_rect(params2, grid, x, y+1);
1258                             r2.x = x;
1259                             r2.y = y;
1260                             r2.w = 1;
1261                             r2.h = 1 + r1.h;
1262                             if (r1.x == x)
1263                                 r1.x++;
1264                             r1.w--;
1265                             break;
1266                         }
1267                         if (r1.h > 0 && r1.w > 0)
1268                             place_rect(params2, grid, r1);
1269                         place_rect(params2, grid, r2);
1270                     } else {
1271 #ifndef NDEBUG
1272                         /*
1273                          * Sanity-check that there really is a 3x3
1274                          * rectangle surrounding this singleton and it
1275                          * contains absolutely everything we could
1276                          * possibly need.
1277                          */
1278                         {
1279                             int xx, yy;
1280                             assert(x > 0 && x < params2->w-1);
1281                             assert(y > 0 && y < params2->h-1);
1282
1283                             for (xx = x-1; xx <= x+1; xx++)
1284                                 for (yy = y-1; yy <= y+1; yy++) {
1285                                     struct rect r = find_rect(params2,grid,xx,yy);
1286                                     assert(r.x >= x-1);
1287                                     assert(r.y >= y-1);
1288                                     assert(r.x+r.w-1 <= x+1);
1289                                     assert(r.y+r.h-1 <= y+1);
1290                                 }
1291                         }
1292 #endif
1293
1294 #ifdef GENERATION_DIAGNOSTICS
1295                         printf("need the 3x3 trick\n");
1296 #endif
1297
1298                         /*
1299                          * FIXME: If the maximum rectangle area for
1300                          * this grid is less than 9, we ought to
1301                          * subdivide the 3x3 in some fashion. There are
1302                          * five other possibilities:
1303                          *
1304                          *  - a 6 and a 3
1305                          *  - a 4, a 3 and a 2
1306                          *  - three 3s
1307                          *  - a 3 and three 2s (two different arrangements).
1308                          */
1309
1310                         {
1311                             struct rect r;
1312                             r.x = x-1;
1313                             r.y = y-1;
1314                             r.w = r.h = 3;
1315                             place_rect(params2, grid, r);
1316                         }
1317                     }
1318                 }
1319             }
1320         }
1321
1322         /*
1323          * We have now constructed a grid of the size specified in
1324          * params2. Now we extend it into a grid of the size specified
1325          * in params. We do this in two passes: we extend it vertically
1326          * until it's the right height, then we transpose it, then
1327          * extend it vertically again (getting it effectively the right
1328          * width), then finally transpose again.
1329          */
1330         for (i = 0; i < 2; i++) {
1331             int *grid2, *expand, *where;
1332             game_params params3real, *params3 = &params3real;
1333
1334 #ifdef GENERATION_DIAGNOSTICS
1335             printf("before expansion:\n");
1336             display_grid(params2, grid, NULL, TRUE);
1337 #endif
1338
1339             /*
1340              * Set up the new grid.
1341              */
1342             grid2 = snewn(params2->w * params->h, int);
1343             expand = snewn(params2->h-1, int);
1344             where = snewn(params2->w, int);
1345             params3->w = params2->w;
1346             params3->h = params->h;
1347
1348             /*
1349              * Decide which horizontal edges are going to get expanded,
1350              * and by how much.
1351              */
1352             for (y = 0; y < params2->h-1; y++)
1353                 expand[y] = 0;
1354             for (y = params2->h; y < params->h; y++) {
1355                 x = random_upto(rs, params2->h-1);
1356                 expand[x]++;
1357             }
1358
1359 #ifdef GENERATION_DIAGNOSTICS
1360             printf("expand[] = {");
1361             for (y = 0; y < params2->h-1; y++)
1362                 printf(" %d", expand[y]);
1363             printf(" }\n");
1364 #endif
1365
1366             /*
1367              * Perform the expansion. The way this works is that we
1368              * alternately:
1369              *
1370              *  - copy a row from grid into grid2
1371              *
1372              *  - invent some number of additional rows in grid2 where
1373              *    there was previously only a horizontal line between
1374              *    rows in grid, and make random decisions about where
1375              *    among these to place each rectangle edge that ran
1376              *    along this line.
1377              */
1378             for (y = y2 = y2last = 0; y < params2->h; y++) {
1379                 /*
1380                  * Copy a single line from row y of grid into row y2 of
1381                  * grid2.
1382                  */
1383                 for (x = 0; x < params2->w; x++) {
1384                     int val = index(params2, grid, x, y);
1385                     if (val / params2->w == y &&   /* rect starts on this line */
1386                         (y2 == 0 ||            /* we're at the very top, or... */
1387                          index(params3, grid2, x, y2-1) / params3->w < y2last
1388                          /* this rect isn't already started */))
1389                         index(params3, grid2, x, y2) =
1390                         INDEX(params3, val % params2->w, y2);
1391                     else
1392                         index(params3, grid2, x, y2) =
1393                         index(params3, grid2, x, y2-1);
1394                 }
1395
1396                 /*
1397                  * If that was the last line, terminate the loop early.
1398                  */
1399                 if (++y2 == params3->h)
1400                     break;
1401
1402                 y2last = y2;
1403
1404                 /*
1405                  * Invent some number of additional lines. First walk
1406                  * along this line working out where to put all the
1407                  * edges that coincide with it.
1408                  */
1409                 yx = -1;
1410                 for (x = 0; x < params2->w; x++) {
1411                     if (index(params2, grid, x, y) !=
1412                         index(params2, grid, x, y+1)) {
1413                         /*
1414                          * This is a horizontal edge, so it needs
1415                          * placing.
1416                          */
1417                         if (x == 0 ||
1418                             (index(params2, grid, x-1, y) !=
1419                              index(params2, grid, x, y) &&
1420                              index(params2, grid, x-1, y+1) !=
1421                              index(params2, grid, x, y+1))) {
1422                             /*
1423                              * Here we have the chance to make a new
1424                              * decision.
1425                              */
1426                             yx = random_upto(rs, expand[y]+1);
1427                         } else {
1428                             /*
1429                              * Here we just reuse the previous value of
1430                              * yx.
1431                              */
1432                         }
1433                     } else
1434                         yx = -1;
1435                     where[x] = yx;
1436                 }
1437
1438                 for (yx = 0; yx < expand[y]; yx++) {
1439                     /*
1440                      * Invent a single row. For each square in the row,
1441                      * we copy the grid entry from the square above it,
1442                      * unless we're starting the new rectangle here.
1443                      */
1444                     for (x = 0; x < params2->w; x++) {
1445                         if (yx == where[x]) {
1446                             int val = index(params2, grid, x, y+1);
1447                             val %= params2->w;
1448                             val = INDEX(params3, val, y2);
1449                             index(params3, grid2, x, y2) = val;
1450                         } else
1451                             index(params3, grid2, x, y2) =
1452                             index(params3, grid2, x, y2-1);
1453                     }
1454
1455                     y2++;
1456                 }
1457             }
1458
1459             sfree(expand);
1460             sfree(where);
1461
1462 #ifdef GENERATION_DIAGNOSTICS
1463             printf("after expansion:\n");
1464             display_grid(params3, grid2, NULL, TRUE);
1465 #endif
1466             /*
1467              * Transpose.
1468              */
1469             params2->w = params3->h;
1470             params2->h = params3->w;
1471             sfree(grid);
1472             grid = snewn(params2->w * params2->h, int);
1473             for (x = 0; x < params2->w; x++)
1474                 for (y = 0; y < params2->h; y++) {
1475                     int idx1 = INDEX(params2, x, y);
1476                     int idx2 = INDEX(params3, y, x);
1477                     int tmp;
1478
1479                     tmp = grid2[idx2];
1480                     tmp = (tmp % params3->w) * params2->w + (tmp / params3->w);
1481                     grid[idx1] = tmp;
1482                 }
1483
1484             sfree(grid2);
1485
1486             {
1487                 int tmp;
1488                 tmp = params->w;
1489                 params->w = params->h;
1490                 params->h = tmp;
1491             }
1492
1493 #ifdef GENERATION_DIAGNOSTICS
1494             printf("after transposition:\n");
1495             display_grid(params2, grid, NULL, TRUE);
1496 #endif
1497         }
1498
1499         /*
1500          * Run the solver to narrow down the possible number
1501          * placements.
1502          */
1503         {
1504             struct numberdata *nd;
1505             int nnumbers, i, ret;
1506
1507             /* Count the rectangles. */
1508             nnumbers = 0;
1509             for (y = 0; y < params->h; y++) {
1510                 for (x = 0; x < params->w; x++) {
1511                     int idx = INDEX(params, x, y);
1512                     if (index(params, grid, x, y) == idx)
1513                         nnumbers++;
1514                 }
1515             }
1516
1517             nd = snewn(nnumbers, struct numberdata);
1518
1519             /* Now set up each number's candidate position list. */
1520             i = 0;
1521             for (y = 0; y < params->h; y++) {
1522                 for (x = 0; x < params->w; x++) {
1523                     int idx = INDEX(params, x, y);
1524                     if (index(params, grid, x, y) == idx) {
1525                         struct rect r = find_rect(params, grid, x, y);
1526                         int j, k, m;
1527
1528                         nd[i].area = r.w * r.h;
1529                         nd[i].npoints = nd[i].area;
1530                         nd[i].points = snewn(nd[i].npoints, struct point);
1531                         m = 0;
1532                         for (j = 0; j < r.h; j++)
1533                             for (k = 0; k < r.w; k++) {
1534                                 nd[i].points[m].x = k + r.x;
1535                                 nd[i].points[m].y = j + r.y;
1536                                 m++;
1537                             }
1538                         assert(m == nd[i].npoints);
1539
1540                         i++;
1541                     }
1542                 }
1543             }
1544
1545             if (params->unique)
1546                 ret = rect_solver(params->w, params->h, nnumbers, nd,
1547                                   NULL, rs);
1548             else
1549                 ret = TRUE;            /* allow any number placement at all */
1550
1551             if (ret) {
1552                 /*
1553                  * Now place the numbers according to the solver's
1554                  * recommendations.
1555                  */
1556                 numbers = snewn(params->w * params->h, int);
1557
1558                 for (y = 0; y < params->h; y++)
1559                     for (x = 0; x < params->w; x++) {
1560                         index(params, numbers, x, y) = 0;
1561                     }
1562
1563                 for (i = 0; i < nnumbers; i++) {
1564                     int idx = random_upto(rs, nd[i].npoints);
1565                     int x = nd[i].points[idx].x;
1566                     int y = nd[i].points[idx].y;
1567                     index(params,numbers,x,y) = nd[i].area;
1568                 }
1569             }
1570
1571             /*
1572              * Clean up.
1573              */
1574             for (i = 0; i < nnumbers; i++)
1575                 sfree(nd[i].points);
1576             sfree(nd);
1577
1578             /*
1579              * If we've succeeded, then terminate the loop.
1580              */
1581             if (ret)
1582                 break;
1583         }
1584
1585         /*
1586          * Give up and go round again.
1587          */
1588         sfree(grid);
1589     }
1590
1591     /*
1592      * Store the rectangle data in the game_aux_info.
1593      */
1594     {
1595         game_aux_info *ai = snew(game_aux_info);
1596
1597         ai->w = params->w;
1598         ai->h = params->h;
1599         ai->vedge = snewn(ai->w * ai->h, unsigned char);
1600         ai->hedge = snewn(ai->w * ai->h, unsigned char);
1601
1602         for (y = 0; y < params->h; y++)
1603             for (x = 1; x < params->w; x++) {
1604                 vedge(ai, x, y) =
1605                     index(params, grid, x, y) != index(params, grid, x-1, y);
1606             }
1607         for (y = 1; y < params->h; y++)
1608             for (x = 0; x < params->w; x++) {
1609                 hedge(ai, x, y) =
1610                     index(params, grid, x, y) != index(params, grid, x, y-1);
1611             }
1612
1613         *aux = ai;
1614     }
1615
1616 #ifdef GENERATION_DIAGNOSTICS
1617     display_grid(params, grid, numbers, FALSE);
1618 #endif
1619
1620     desc = snewn(11 * params->w * params->h, char);
1621     p = desc;
1622     run = 0;
1623     for (i = 0; i <= params->w * params->h; i++) {
1624         int n = (i < params->w * params->h ? numbers[i] : -1);
1625
1626         if (!n)
1627             run++;
1628         else {
1629             if (run) {
1630                 while (run > 0) {
1631                     int c = 'a' - 1 + run;
1632                     if (run > 26)
1633                         c = 'z';
1634                     *p++ = c;
1635                     run -= c - ('a' - 1);
1636                 }
1637             } else {
1638                 /*
1639                  * If there's a number in the very top left or
1640                  * bottom right, there's no point putting an
1641                  * unnecessary _ before or after it.
1642                  */
1643                 if (p > desc && n > 0)
1644                     *p++ = '_';
1645             }
1646             if (n > 0)
1647                 p += sprintf(p, "%d", n);
1648             run = 0;
1649         }
1650     }
1651     *p = '\0';
1652
1653     sfree(grid);
1654     sfree(numbers);
1655
1656     return desc;
1657 }
1658
1659 static void game_free_aux_info(game_aux_info *ai)
1660 {
1661     sfree(ai->vedge);
1662     sfree(ai->hedge);
1663     sfree(ai);
1664 }
1665
1666 static char *validate_desc(game_params *params, char *desc)
1667 {
1668     int area = params->w * params->h;
1669     int squares = 0;
1670
1671     while (*desc) {
1672         int n = *desc++;
1673         if (n >= 'a' && n <= 'z') {
1674             squares += n - 'a' + 1;
1675         } else if (n == '_') {
1676             /* do nothing */;
1677         } else if (n > '0' && n <= '9') {
1678             squares++;
1679             while (*desc >= '0' && *desc <= '9')
1680                 desc++;
1681         } else
1682             return "Invalid character in game description";
1683     }
1684
1685     if (squares < area)
1686         return "Not enough data to fill grid";
1687
1688     if (squares > area)
1689         return "Too much data to fit in grid";
1690
1691     return NULL;
1692 }
1693
1694 static game_state *new_game(midend_data *me, game_params *params, char *desc)
1695 {
1696     game_state *state = snew(game_state);
1697     int x, y, i, area;
1698
1699     state->w = params->w;
1700     state->h = params->h;
1701
1702     area = state->w * state->h;
1703
1704     state->grid = snewn(area, int);
1705     state->vedge = snewn(area, unsigned char);
1706     state->hedge = snewn(area, unsigned char);
1707     state->completed = state->cheated = FALSE;
1708
1709     i = 0;
1710     while (*desc) {
1711         int n = *desc++;
1712         if (n >= 'a' && n <= 'z') {
1713             int run = n - 'a' + 1;
1714             assert(i + run <= area);
1715             while (run-- > 0)
1716                 state->grid[i++] = 0;
1717         } else if (n == '_') {
1718             /* do nothing */;
1719         } else if (n > '0' && n <= '9') {
1720             assert(i < area);
1721             state->grid[i++] = atoi(desc-1);
1722             while (*desc >= '0' && *desc <= '9')
1723                 desc++;
1724         } else {
1725             assert(!"We can't get here");
1726         }
1727     }
1728     assert(i == area);
1729
1730     for (y = 0; y < state->h; y++)
1731         for (x = 0; x < state->w; x++)
1732             vedge(state,x,y) = hedge(state,x,y) = 0;
1733
1734     return state;
1735 }
1736
1737 static game_state *dup_game(game_state *state)
1738 {
1739     game_state *ret = snew(game_state);
1740
1741     ret->w = state->w;
1742     ret->h = state->h;
1743
1744     ret->vedge = snewn(state->w * state->h, unsigned char);
1745     ret->hedge = snewn(state->w * state->h, unsigned char);
1746     ret->grid = snewn(state->w * state->h, int);
1747
1748     ret->completed = state->completed;
1749     ret->cheated = state->cheated;
1750
1751     memcpy(ret->grid, state->grid, state->w * state->h * sizeof(int));
1752     memcpy(ret->vedge, state->vedge, state->w*state->h*sizeof(unsigned char));
1753     memcpy(ret->hedge, state->hedge, state->w*state->h*sizeof(unsigned char));
1754
1755     return ret;
1756 }
1757
1758 static void free_game(game_state *state)
1759 {
1760     sfree(state->grid);
1761     sfree(state->vedge);
1762     sfree(state->hedge);
1763     sfree(state);
1764 }
1765
1766 static game_state *solve_game(game_state *state, game_aux_info *ai,
1767                               char **error)
1768 {
1769     game_state *ret;
1770
1771     if (!ai) {
1772         int i, j, n;
1773         struct numberdata *nd;
1774
1775         /*
1776          * Attempt the in-built solver.
1777          */
1778
1779         /* Set up each number's (very short) candidate position list. */
1780         for (i = n = 0; i < state->h * state->w; i++)
1781             if (state->grid[i])
1782                 n++;
1783
1784         nd = snewn(n, struct numberdata);
1785
1786         for (i = j = 0; i < state->h * state->w; i++)
1787             if (state->grid[i]) {
1788                 nd[j].area = state->grid[i];
1789                 nd[j].npoints = 1;
1790                 nd[j].points = snewn(1, struct point);
1791                 nd[j].points[0].x = i % state->w;
1792                 nd[j].points[0].y = i / state->w;
1793                 j++;
1794             }
1795
1796         assert(j == n);
1797
1798         ret = dup_game(state);
1799         ret->cheated = TRUE;
1800
1801         rect_solver(state->w, state->h, n, nd, ret, NULL);
1802
1803         /*
1804          * Clean up.
1805          */
1806         for (i = 0; i < n; i++)
1807             sfree(nd[i].points);
1808         sfree(nd);
1809
1810         return ret;
1811     }
1812
1813     assert(state->w == ai->w);
1814     assert(state->h == ai->h);
1815
1816     ret = dup_game(state);
1817     memcpy(ret->vedge, ai->vedge, ai->w * ai->h * sizeof(unsigned char));
1818     memcpy(ret->hedge, ai->hedge, ai->w * ai->h * sizeof(unsigned char));
1819     ret->cheated = TRUE;
1820
1821     return ret;
1822 }
1823
1824 static char *game_text_format(game_state *state)
1825 {
1826     char *ret, *p, buf[80];
1827     int i, x, y, col, maxlen;
1828
1829     /*
1830      * First determine the number of spaces required to display a
1831      * number. We'll use at least two, because one looks a bit
1832      * silly.
1833      */
1834     col = 2;
1835     for (i = 0; i < state->w * state->h; i++) {
1836         x = sprintf(buf, "%d", state->grid[i]);
1837         if (col < x) col = x;
1838     }
1839
1840     /*
1841      * Now we know the exact total size of the grid we're going to
1842      * produce: it's got 2*h+1 rows, each containing w lots of col,
1843      * w+1 boundary characters and a trailing newline.
1844      */
1845     maxlen = (2*state->h+1) * (state->w * (col+1) + 2);
1846
1847     ret = snewn(maxlen+1, char);
1848     p = ret;
1849
1850     for (y = 0; y <= 2*state->h; y++) {
1851         for (x = 0; x <= 2*state->w; x++) {
1852             if (x & y & 1) {
1853                 /*
1854                  * Display a number.
1855                  */
1856                 int v = grid(state, x/2, y/2);
1857                 if (v)
1858                     sprintf(buf, "%*d", col, v);
1859                 else
1860                     sprintf(buf, "%*s", col, "");
1861                 memcpy(p, buf, col);
1862                 p += col;
1863             } else if (x & 1) {
1864                 /*
1865                  * Display a horizontal edge or nothing.
1866                  */
1867                 int h = (y==0 || y==2*state->h ? 1 :
1868                          HRANGE(state, x/2, y/2) && hedge(state, x/2, y/2));
1869                 int i;
1870                 if (h)
1871                     h = '-';
1872                 else
1873                     h = ' ';
1874                 for (i = 0; i < col; i++)
1875                     *p++ = h;
1876             } else if (y & 1) {
1877                 /*
1878                  * Display a vertical edge or nothing.
1879                  */
1880                 int v = (x==0 || x==2*state->w ? 1 :
1881                          VRANGE(state, x/2, y/2) && vedge(state, x/2, y/2));
1882                 if (v)
1883                     *p++ = '|';
1884                 else
1885                     *p++ = ' ';
1886             } else {
1887                 /*
1888                  * Display a corner, or a vertical edge, or a
1889                  * horizontal edge, or nothing.
1890                  */
1891                 int hl = (y==0 || y==2*state->h ? 1 :
1892                           HRANGE(state, (x-1)/2, y/2) && hedge(state, (x-1)/2, y/2));
1893                 int hr = (y==0 || y==2*state->h ? 1 :
1894                           HRANGE(state, (x+1)/2, y/2) && hedge(state, (x+1)/2, y/2));
1895                 int vu = (x==0 || x==2*state->w ? 1 :
1896                           VRANGE(state, x/2, (y-1)/2) && vedge(state, x/2, (y-1)/2));
1897                 int vd = (x==0 || x==2*state->w ? 1 :
1898                           VRANGE(state, x/2, (y+1)/2) && vedge(state, x/2, (y+1)/2));
1899                 if (!hl && !hr && !vu && !vd)
1900                     *p++ = ' ';
1901                 else if (hl && hr && !vu && !vd)
1902                     *p++ = '-';
1903                 else if (!hl && !hr && vu && vd)
1904                     *p++ = '|';
1905                 else
1906                     *p++ = '+';
1907             }
1908         }
1909         *p++ = '\n';
1910     }
1911
1912     assert(p - ret == maxlen);
1913     *p = '\0';
1914     return ret;
1915 }
1916
1917 static unsigned char *get_correct(game_state *state)
1918 {
1919     unsigned char *ret;
1920     int x, y;
1921
1922     ret = snewn(state->w * state->h, unsigned char);
1923     memset(ret, 0xFF, state->w * state->h);
1924
1925     for (x = 0; x < state->w; x++)
1926         for (y = 0; y < state->h; y++)
1927             if (index(state,ret,x,y) == 0xFF) {
1928                 int rw, rh;
1929                 int xx, yy;
1930                 int num, area, valid;
1931
1932                 /*
1933                  * Find a rectangle starting at this point.
1934                  */
1935                 rw = 1;
1936                 while (x+rw < state->w && !vedge(state,x+rw,y))
1937                     rw++;
1938                 rh = 1;
1939                 while (y+rh < state->h && !hedge(state,x,y+rh))
1940                     rh++;
1941
1942                 /*
1943                  * We know what the dimensions of the rectangle
1944                  * should be if it's there at all. Find out if we
1945                  * really have a valid rectangle.
1946                  */
1947                 valid = TRUE;
1948                 /* Check the horizontal edges. */
1949                 for (xx = x; xx < x+rw; xx++) {
1950                     for (yy = y; yy <= y+rh; yy++) {
1951                         int e = !HRANGE(state,xx,yy) || hedge(state,xx,yy);
1952                         int ec = (yy == y || yy == y+rh);
1953                         if (e != ec)
1954                             valid = FALSE;
1955                     }
1956                 }
1957                 /* Check the vertical edges. */
1958                 for (yy = y; yy < y+rh; yy++) {
1959                     for (xx = x; xx <= x+rw; xx++) {
1960                         int e = !VRANGE(state,xx,yy) || vedge(state,xx,yy);
1961                         int ec = (xx == x || xx == x+rw);
1962                         if (e != ec)
1963                             valid = FALSE;
1964                     }
1965                 }
1966
1967                 /*
1968                  * If this is not a valid rectangle with no other
1969                  * edges inside it, we just mark this square as not
1970                  * complete and proceed to the next square.
1971                  */
1972                 if (!valid) {
1973                     index(state, ret, x, y) = 0;
1974                     continue;
1975                 }
1976
1977                 /*
1978                  * We have a rectangle. Now see what its area is,
1979                  * and how many numbers are in it.
1980                  */
1981                 num = 0;
1982                 area = 0;
1983                 for (xx = x; xx < x+rw; xx++) {
1984                     for (yy = y; yy < y+rh; yy++) {
1985                         area++;
1986                         if (grid(state,xx,yy)) {
1987                             if (num > 0)
1988                                 valid = FALSE;   /* two numbers */
1989                             num = grid(state,xx,yy);
1990                         }
1991                     }
1992                 }
1993                 if (num != area)
1994                     valid = FALSE;
1995
1996                 /*
1997                  * Now fill in the whole rectangle based on the
1998                  * value of `valid'.
1999                  */
2000                 for (xx = x; xx < x+rw; xx++) {
2001                     for (yy = y; yy < y+rh; yy++) {
2002                         index(state, ret, xx, yy) = valid;
2003                     }
2004                 }
2005             }
2006
2007     return ret;
2008 }
2009
2010 struct game_ui {
2011     /*
2012      * These coordinates are 2 times the obvious grid coordinates.
2013      * Hence, the top left of the grid is (0,0), the grid point to
2014      * the right of that is (2,0), the one _below that_ is (2,2)
2015      * and so on. This is so that we can specify a drag start point
2016      * on an edge (one odd coordinate) or in the middle of a square
2017      * (two odd coordinates) rather than always at a corner.
2018      * 
2019      * -1,-1 means no drag is in progress.
2020      */
2021     int drag_start_x;
2022     int drag_start_y;
2023     int drag_end_x;
2024     int drag_end_y;
2025     /*
2026      * This flag is set as soon as a dragging action moves the
2027      * mouse pointer away from its starting point, so that even if
2028      * the pointer _returns_ to its starting point the action is
2029      * treated as a small drag rather than a click.
2030      */
2031     int dragged;
2032 };
2033
2034 static game_ui *new_ui(game_state *state)
2035 {
2036     game_ui *ui = snew(game_ui);
2037     ui->drag_start_x = -1;
2038     ui->drag_start_y = -1;
2039     ui->drag_end_x = -1;
2040     ui->drag_end_y = -1;
2041     ui->dragged = FALSE;
2042     return ui;
2043 }
2044
2045 static void free_ui(game_ui *ui)
2046 {
2047     sfree(ui);
2048 }
2049
2050 static void coord_round(float x, float y, int *xr, int *yr)
2051 {
2052     float xs, ys, xv, yv, dx, dy, dist;
2053
2054     /*
2055      * Find the nearest square-centre.
2056      */
2057     xs = (float)floor(x) + 0.5F;
2058     ys = (float)floor(y) + 0.5F;
2059
2060     /*
2061      * And find the nearest grid vertex.
2062      */
2063     xv = (float)floor(x + 0.5F);
2064     yv = (float)floor(y + 0.5F);
2065
2066     /*
2067      * We allocate clicks in parts of the grid square to either
2068      * corners, edges or square centres, as follows:
2069      * 
2070      *   +--+--------+--+
2071      *   |  |        |  |
2072      *   +--+        +--+
2073      *   |   `.    ,'   |
2074      *   |     +--+     |
2075      *   |     |  |     |
2076      *   |     +--+     |
2077      *   |   ,'    `.   |
2078      *   +--+        +--+
2079      *   |  |        |  |
2080      *   +--+--------+--+
2081      * 
2082      * (Not to scale!)
2083      * 
2084      * In other words: we measure the square distance (i.e.
2085      * max(dx,dy)) from the click to the nearest corner, and if
2086      * it's within CORNER_TOLERANCE then we return a corner click.
2087      * We measure the square distance from the click to the nearest
2088      * centre, and if that's within CENTRE_TOLERANCE we return a
2089      * centre click. Failing that, we find which of the two edge
2090      * centres is nearer to the click and return that edge.
2091      */
2092
2093     /*
2094      * Check for corner click.
2095      */
2096     dx = (float)fabs(x - xv);
2097     dy = (float)fabs(y - yv);
2098     dist = (dx > dy ? dx : dy);
2099     if (dist < CORNER_TOLERANCE) {
2100         *xr = 2 * (int)xv;
2101         *yr = 2 * (int)yv;
2102     } else {
2103         /*
2104          * Check for centre click.
2105          */
2106         dx = (float)fabs(x - xs);
2107         dy = (float)fabs(y - ys);
2108         dist = (dx > dy ? dx : dy);
2109         if (dist < CENTRE_TOLERANCE) {
2110             *xr = 1 + 2 * (int)xs;
2111             *yr = 1 + 2 * (int)ys;
2112         } else {
2113             /*
2114              * Failing both of those, see which edge we're closer to.
2115              * Conveniently, this is simply done by testing the relative
2116              * magnitude of dx and dy (which are currently distances from
2117              * the square centre).
2118              */
2119             if (dx > dy) {
2120                 /* Vertical edge: x-coord of corner,
2121                  * y-coord of square centre. */
2122                 *xr = 2 * (int)xv;
2123                 *yr = 1 + 2 * (int)ys;
2124             } else {
2125                 /* Horizontal edge: x-coord of square centre,
2126                  * y-coord of corner. */
2127                 *xr = 1 + 2 * (int)xs;
2128                 *yr = 2 * (int)yv;
2129             }
2130         }
2131     }
2132 }
2133
2134 static void ui_draw_rect(game_state *state, game_ui *ui,
2135                          unsigned char *hedge, unsigned char *vedge, int c)
2136 {
2137     int x1, x2, y1, y2, x, y, t;
2138
2139     x1 = ui->drag_start_x;
2140     x2 = ui->drag_end_x;
2141     if (x2 < x1) { t = x1; x1 = x2; x2 = t; }
2142
2143     y1 = ui->drag_start_y;
2144     y2 = ui->drag_end_y;
2145     if (y2 < y1) { t = y1; y1 = y2; y2 = t; }
2146
2147     x1 = x1 / 2;               /* rounds down */
2148     x2 = (x2+1) / 2;           /* rounds up */
2149     y1 = y1 / 2;               /* rounds down */
2150     y2 = (y2+1) / 2;           /* rounds up */
2151
2152     /*
2153      * Draw horizontal edges of rectangles.
2154      */
2155     for (x = x1; x < x2; x++)
2156         for (y = y1; y <= y2; y++)
2157             if (HRANGE(state,x,y)) {
2158                 int val = index(state,hedge,x,y);
2159                 if (y == y1 || y == y2)
2160                     val = c;
2161                 else if (c == 1)
2162                     val = 0;
2163                 index(state,hedge,x,y) = val;
2164             }
2165
2166     /*
2167      * Draw vertical edges of rectangles.
2168      */
2169     for (y = y1; y < y2; y++)
2170         for (x = x1; x <= x2; x++)
2171             if (VRANGE(state,x,y)) {
2172                 int val = index(state,vedge,x,y);
2173                 if (x == x1 || x == x2)
2174                     val = c;
2175                 else if (c == 1)
2176                     val = 0;
2177                 index(state,vedge,x,y) = val;
2178             }
2179 }
2180
2181 static game_state *make_move(game_state *from, game_ui *ui,
2182                              int x, int y, int button)
2183 {
2184     int xc, yc;
2185     int startdrag = FALSE, enddrag = FALSE, active = FALSE;
2186     game_state *ret;
2187
2188     button &= ~MOD_MASK;
2189
2190     if (button == LEFT_BUTTON) {
2191         startdrag = TRUE;
2192     } else if (button == LEFT_RELEASE) {
2193         enddrag = TRUE;
2194     } else if (button != LEFT_DRAG) {
2195         return NULL;
2196     }
2197
2198     coord_round(FROMCOORD((float)x), FROMCOORD((float)y), &xc, &yc);
2199
2200     if (startdrag) {
2201         ui->drag_start_x = xc;
2202         ui->drag_start_y = yc;
2203         ui->drag_end_x = xc;
2204         ui->drag_end_y = yc;
2205         ui->dragged = FALSE;
2206         active = TRUE;
2207     }
2208
2209     if (xc != ui->drag_end_x || yc != ui->drag_end_y) {
2210         ui->drag_end_x = xc;
2211         ui->drag_end_y = yc;
2212         ui->dragged = TRUE;
2213         active = TRUE;
2214     }
2215
2216     ret = NULL;
2217
2218     if (enddrag) {
2219         if (xc >= 0 && xc <= 2*from->w &&
2220             yc >= 0 && yc <= 2*from->h) {
2221             ret = dup_game(from);
2222
2223             if (ui->dragged) {
2224                 ui_draw_rect(ret, ui, ret->hedge, ret->vedge, 1);
2225             } else {
2226                 if ((xc & 1) && !(yc & 1) && HRANGE(from,xc/2,yc/2)) {
2227                     hedge(ret,xc/2,yc/2) = !hedge(ret,xc/2,yc/2);
2228                 }
2229                 if ((yc & 1) && !(xc & 1) && VRANGE(from,xc/2,yc/2)) {
2230                     vedge(ret,xc/2,yc/2) = !vedge(ret,xc/2,yc/2);
2231                 }
2232             }
2233
2234             if (!memcmp(ret->hedge, from->hedge, from->w*from->h) &&
2235                 !memcmp(ret->vedge, from->vedge, from->w*from->h)) {
2236                 free_game(ret);
2237                 ret = NULL;
2238             }
2239
2240             /*
2241              * We've made a real change to the grid. Check to see
2242              * if the game has been completed.
2243              */
2244             if (ret && !ret->completed) {
2245                 int x, y, ok;
2246                 unsigned char *correct = get_correct(ret);
2247
2248                 ok = TRUE;
2249                 for (x = 0; x < ret->w; x++)
2250                     for (y = 0; y < ret->h; y++)
2251                         if (!index(ret, correct, x, y))
2252                             ok = FALSE;
2253
2254                 sfree(correct);
2255
2256                 if (ok)
2257                     ret->completed = TRUE;
2258             }
2259         }
2260
2261         ui->drag_start_x = -1;
2262         ui->drag_start_y = -1;
2263         ui->drag_end_x = -1;
2264         ui->drag_end_y = -1;
2265         ui->dragged = FALSE;
2266         active = TRUE;
2267     }
2268
2269     if (ret)
2270         return ret;                    /* a move has been made */
2271     else if (active)
2272         return from;                   /* UI activity has occurred */
2273     else
2274         return NULL;
2275 }
2276
2277 /* ----------------------------------------------------------------------
2278  * Drawing routines.
2279  */
2280
2281 #define CORRECT 65536
2282
2283 #define COLOUR(k) ( (k)==1 ? COL_LINE : COL_DRAG )
2284 #define MAX(x,y) ( (x)>(y) ? (x) : (y) )
2285 #define MAX4(x,y,z,w) ( MAX(MAX(x,y),MAX(z,w)) )
2286
2287 struct game_drawstate {
2288     int started;
2289     int w, h;
2290     unsigned int *visible;
2291 };
2292
2293 static void game_size(game_params *params, int *x, int *y)
2294 {
2295     *x = params->w * TILE_SIZE + 2*BORDER + 1;
2296     *y = params->h * TILE_SIZE + 2*BORDER + 1;
2297 }
2298
2299 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2300 {
2301     float *ret = snewn(3 * NCOLOURS, float);
2302
2303     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2304
2305     ret[COL_GRID * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2306     ret[COL_GRID * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2307     ret[COL_GRID * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2308
2309     ret[COL_DRAG * 3 + 0] = 1.0F;
2310     ret[COL_DRAG * 3 + 1] = 0.0F;
2311     ret[COL_DRAG * 3 + 2] = 0.0F;
2312
2313     ret[COL_CORRECT * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2314     ret[COL_CORRECT * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2315     ret[COL_CORRECT * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2316
2317     ret[COL_LINE * 3 + 0] = 0.0F;
2318     ret[COL_LINE * 3 + 1] = 0.0F;
2319     ret[COL_LINE * 3 + 2] = 0.0F;
2320
2321     ret[COL_TEXT * 3 + 0] = 0.0F;
2322     ret[COL_TEXT * 3 + 1] = 0.0F;
2323     ret[COL_TEXT * 3 + 2] = 0.0F;
2324
2325     *ncolours = NCOLOURS;
2326     return ret;
2327 }
2328
2329 static game_drawstate *game_new_drawstate(game_state *state)
2330 {
2331     struct game_drawstate *ds = snew(struct game_drawstate);
2332     int i;
2333
2334     ds->started = FALSE;
2335     ds->w = state->w;
2336     ds->h = state->h;
2337     ds->visible = snewn(ds->w * ds->h, unsigned int);
2338     for (i = 0; i < ds->w * ds->h; i++)
2339         ds->visible[i] = 0xFFFF;
2340
2341     return ds;
2342 }
2343
2344 static void game_free_drawstate(game_drawstate *ds)
2345 {
2346     sfree(ds->visible);
2347     sfree(ds);
2348 }
2349
2350 static void draw_tile(frontend *fe, game_state *state, int x, int y,
2351                unsigned char *hedge, unsigned char *vedge,
2352                unsigned char *corners, int correct)
2353 {
2354     int cx = COORD(x), cy = COORD(y);
2355     char str[80];
2356
2357     draw_rect(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1, COL_GRID);
2358     draw_rect(fe, cx+1, cy+1, TILE_SIZE-1, TILE_SIZE-1,
2359               correct ? COL_CORRECT : COL_BACKGROUND);
2360
2361     if (grid(state,x,y)) {
2362         sprintf(str, "%d", grid(state,x,y));
2363         draw_text(fe, cx+TILE_SIZE/2, cy+TILE_SIZE/2, FONT_VARIABLE,
2364                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_TEXT, str);
2365     }
2366
2367     /*
2368      * Draw edges.
2369      */
2370     if (!HRANGE(state,x,y) || index(state,hedge,x,y))
2371         draw_rect(fe, cx, cy, TILE_SIZE+1, 2,
2372                   HRANGE(state,x,y) ? COLOUR(index(state,hedge,x,y)) :
2373                   COL_LINE);
2374     if (!HRANGE(state,x,y+1) || index(state,hedge,x,y+1))
2375         draw_rect(fe, cx, cy+TILE_SIZE-1, TILE_SIZE+1, 2,
2376                   HRANGE(state,x,y+1) ? COLOUR(index(state,hedge,x,y+1)) :
2377                   COL_LINE);
2378     if (!VRANGE(state,x,y) || index(state,vedge,x,y))
2379         draw_rect(fe, cx, cy, 2, TILE_SIZE+1,
2380                   VRANGE(state,x,y) ? COLOUR(index(state,vedge,x,y)) :
2381                   COL_LINE);
2382     if (!VRANGE(state,x+1,y) || index(state,vedge,x+1,y))
2383         draw_rect(fe, cx+TILE_SIZE-1, cy, 2, TILE_SIZE+1,
2384                   VRANGE(state,x+1,y) ? COLOUR(index(state,vedge,x+1,y)) :
2385                   COL_LINE);
2386
2387     /*
2388      * Draw corners.
2389      */
2390     if (index(state,corners,x,y))
2391         draw_rect(fe, cx, cy, 2, 2,
2392                   COLOUR(index(state,corners,x,y)));
2393     if (x+1 < state->w && index(state,corners,x+1,y))
2394         draw_rect(fe, cx+TILE_SIZE-1, cy, 2, 2,
2395                   COLOUR(index(state,corners,x+1,y)));
2396     if (y+1 < state->h && index(state,corners,x,y+1))
2397         draw_rect(fe, cx, cy+TILE_SIZE-1, 2, 2,
2398                   COLOUR(index(state,corners,x,y+1)));
2399     if (x+1 < state->w && y+1 < state->h && index(state,corners,x+1,y+1))
2400         draw_rect(fe, cx+TILE_SIZE-1, cy+TILE_SIZE-1, 2, 2,
2401                   COLOUR(index(state,corners,x+1,y+1)));
2402
2403     draw_update(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1);
2404 }
2405
2406 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2407                  game_state *state, int dir, game_ui *ui,
2408                  float animtime, float flashtime)
2409 {
2410     int x, y;
2411     unsigned char *correct;
2412     unsigned char *hedge, *vedge, *corners;
2413
2414     correct = get_correct(state);
2415
2416     if (ui->dragged) {
2417         hedge = snewn(state->w*state->h, unsigned char);
2418         vedge = snewn(state->w*state->h, unsigned char);
2419         memcpy(hedge, state->hedge, state->w*state->h);
2420         memcpy(vedge, state->vedge, state->w*state->h);
2421         ui_draw_rect(state, ui, hedge, vedge, 2);
2422     } else {
2423         hedge = state->hedge;
2424         vedge = state->vedge;
2425     }
2426
2427     corners = snewn(state->w * state->h, unsigned char);
2428     memset(corners, 0, state->w * state->h);
2429     for (x = 0; x < state->w; x++)
2430         for (y = 0; y < state->h; y++) {
2431             if (x > 0) {
2432                 int e = index(state, vedge, x, y);
2433                 if (index(state,corners,x,y) < e)
2434                     index(state,corners,x,y) = e;
2435                 if (y+1 < state->h &&
2436                     index(state,corners,x,y+1) < e)
2437                     index(state,corners,x,y+1) = e;
2438             }
2439             if (y > 0) {
2440                 int e = index(state, hedge, x, y);
2441                 if (index(state,corners,x,y) < e)
2442                     index(state,corners,x,y) = e;
2443                 if (x+1 < state->w &&
2444                     index(state,corners,x+1,y) < e)
2445                     index(state,corners,x+1,y) = e;
2446             }
2447         }
2448
2449     if (!ds->started) {
2450         draw_rect(fe, 0, 0,
2451                   state->w * TILE_SIZE + 2*BORDER + 1,
2452                   state->h * TILE_SIZE + 2*BORDER + 1, COL_BACKGROUND);
2453         draw_rect(fe, COORD(0)-1, COORD(0)-1,
2454                   ds->w*TILE_SIZE+3, ds->h*TILE_SIZE+3, COL_LINE);
2455         ds->started = TRUE;
2456         draw_update(fe, 0, 0,
2457                     state->w * TILE_SIZE + 2*BORDER + 1,
2458                     state->h * TILE_SIZE + 2*BORDER + 1);
2459     }
2460
2461     for (x = 0; x < state->w; x++)
2462         for (y = 0; y < state->h; y++) {
2463             unsigned int c = 0;
2464
2465             if (HRANGE(state,x,y))
2466                 c |= index(state,hedge,x,y);
2467             if (HRANGE(state,x,y+1))
2468                 c |= index(state,hedge,x,y+1) << 2;
2469             if (VRANGE(state,x,y))
2470                 c |= index(state,vedge,x,y) << 4;
2471             if (VRANGE(state,x+1,y))
2472                 c |= index(state,vedge,x+1,y) << 6;
2473             c |= index(state,corners,x,y) << 8;
2474             if (x+1 < state->w)
2475                 c |= index(state,corners,x+1,y) << 10;
2476             if (y+1 < state->h)
2477                 c |= index(state,corners,x,y+1) << 12;
2478             if (x+1 < state->w && y+1 < state->h)
2479                 c |= index(state,corners,x+1,y+1) << 14;
2480             if (index(state, correct, x, y) && !flashtime)
2481                 c |= CORRECT;
2482
2483             if (index(ds,ds->visible,x,y) != c) {
2484                 draw_tile(fe, state, x, y, hedge, vedge, corners, c & CORRECT);
2485                 index(ds,ds->visible,x,y) = c;
2486             }
2487         }
2488
2489     if (hedge != state->hedge) {
2490         sfree(hedge);
2491         sfree(vedge);
2492    }
2493
2494     sfree(corners);
2495     sfree(correct);
2496 }
2497
2498 static float game_anim_length(game_state *oldstate,
2499                               game_state *newstate, int dir, game_ui *ui)
2500 {
2501     return 0.0F;
2502 }
2503
2504 static float game_flash_length(game_state *oldstate,
2505                                game_state *newstate, int dir, game_ui *ui)
2506 {
2507     if (!oldstate->completed && newstate->completed &&
2508         !oldstate->cheated && !newstate->cheated)
2509         return FLASH_TIME;
2510     return 0.0F;
2511 }
2512
2513 static int game_wants_statusbar(void)
2514 {
2515     return FALSE;
2516 }
2517
2518 #ifdef COMBINED
2519 #define thegame rect
2520 #endif
2521
2522 const struct game thegame = {
2523     "Rectangles", "games.rectangles",
2524     default_params,
2525     game_fetch_preset,
2526     decode_params,
2527     encode_params,
2528     free_params,
2529     dup_params,
2530     TRUE, game_configure, custom_params,
2531     validate_params,
2532     new_game_desc,
2533     game_free_aux_info,
2534     validate_desc,
2535     new_game,
2536     dup_game,
2537     free_game,
2538     TRUE, solve_game,
2539     TRUE, game_text_format,
2540     new_ui,
2541     free_ui,
2542     make_move,
2543     game_size,
2544     game_colours,
2545     game_new_drawstate,
2546     game_free_drawstate,
2547     game_redraw,
2548     game_anim_length,
2549     game_flash_length,
2550     game_wants_statusbar,
2551 };