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