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