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