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