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