chiark / gitweb /
Update changelog for 20170923.ff218728-0+iwj2~3.gbpc58e0c release
[sgt-puzzles.git] / pattern.c
1 /*
2  * pattern.c: the pattern-reconstruction game known as `nonograms'.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <ctype.h>
10 #include <math.h>
11
12 #include "puzzles.h"
13
14 enum {
15     COL_BACKGROUND,
16     COL_EMPTY,
17     COL_FULL,
18     COL_TEXT,
19     COL_UNKNOWN,
20     COL_GRID,
21     COL_CURSOR,
22     COL_ERROR,
23     NCOLOURS
24 };
25
26 #define PREFERRED_TILE_SIZE 24
27 #define TILE_SIZE (ds->tilesize)
28 #define BORDER (3 * TILE_SIZE / 4)
29 #define TLBORDER(d) ( (d) / 5 + 2 )
30 #define GUTTER (TILE_SIZE / 2)
31
32 #define FROMCOORD(d, x) \
33         ( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
34
35 #define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
36 #define GETTILESIZE(d, w) ((double)w / (2.0 + (double)TLBORDER(d) + (double)(d)))
37
38 #define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
39
40 struct game_params {
41     int w, h;
42 };
43
44 #define GRID_UNKNOWN 2
45 #define GRID_FULL 1
46 #define GRID_EMPTY 0
47
48 typedef struct game_state_common {
49     /* Parts of the game state that don't change during play. */
50     int w, h;
51     int rowsize;
52     int *rowdata, *rowlen;
53     unsigned char *immutable;
54     int refcount;
55 } game_state_common;
56
57 struct game_state {
58     game_state_common *common;
59     unsigned char *grid;
60     int completed, cheated;
61 };
62
63 #define FLASH_TIME 0.13F
64
65 static game_params *default_params(void)
66 {
67     game_params *ret = snew(game_params);
68
69     ret->w = ret->h = 15;
70
71     return ret;
72 }
73
74 static const struct game_params pattern_presets[] = {
75     {10, 10},
76     {15, 15},
77     {20, 20},
78 #ifndef SLOW_SYSTEM
79     {25, 25},
80     {30, 30},
81 #endif
82 };
83
84 static int game_fetch_preset(int i, char **name, game_params **params)
85 {
86     game_params *ret;
87     char str[80];
88
89     if (i < 0 || i >= lenof(pattern_presets))
90         return FALSE;
91
92     ret = snew(game_params);
93     *ret = pattern_presets[i];
94
95     sprintf(str, "%dx%d", ret->w, ret->h);
96
97     *name = dupstr(str);
98     *params = ret;
99     return TRUE;
100 }
101
102 static void free_params(game_params *params)
103 {
104     sfree(params);
105 }
106
107 static game_params *dup_params(const game_params *params)
108 {
109     game_params *ret = snew(game_params);
110     *ret = *params;                    /* structure copy */
111     return ret;
112 }
113
114 static void decode_params(game_params *ret, char const *string)
115 {
116     char const *p = string;
117
118     ret->w = atoi(p);
119     while (*p && isdigit((unsigned char)*p)) p++;
120     if (*p == 'x') {
121         p++;
122         ret->h = atoi(p);
123         while (*p && isdigit((unsigned char)*p)) p++;
124     } else {
125         ret->h = ret->w;
126     }
127 }
128
129 static char *encode_params(const game_params *params, int full)
130 {
131     char ret[400];
132     int len;
133
134     len = sprintf(ret, "%dx%d", params->w, params->h);
135     assert(len < lenof(ret));
136     ret[len] = '\0';
137
138     return dupstr(ret);
139 }
140
141 static config_item *game_configure(const game_params *params)
142 {
143     config_item *ret;
144     char buf[80];
145
146     ret = snewn(3, config_item);
147
148     ret[0].name = "Width";
149     ret[0].type = C_STRING;
150     sprintf(buf, "%d", params->w);
151     ret[0].u.string.sval = dupstr(buf);
152
153     ret[1].name = "Height";
154     ret[1].type = C_STRING;
155     sprintf(buf, "%d", params->h);
156     ret[1].u.string.sval = dupstr(buf);
157
158     ret[2].name = NULL;
159     ret[2].type = C_END;
160
161     return ret;
162 }
163
164 static game_params *custom_params(const config_item *cfg)
165 {
166     game_params *ret = snew(game_params);
167
168     ret->w = atoi(cfg[0].u.string.sval);
169     ret->h = atoi(cfg[1].u.string.sval);
170
171     return ret;
172 }
173
174 static const char *validate_params(const game_params *params, int full)
175 {
176     if (params->w <= 0 || params->h <= 0)
177         return "Width and height must both be greater than zero";
178     return NULL;
179 }
180
181 /* ----------------------------------------------------------------------
182  * Puzzle generation code.
183  * 
184  * For this particular puzzle, it seemed important to me to ensure
185  * a unique solution. I do this the brute-force way, by having a
186  * solver algorithm alongside the generator, and repeatedly
187  * generating a random grid until I find one whose solution is
188  * unique. It turns out that this isn't too onerous on a modern PC
189  * provided you keep grid size below around 30. Any offers of
190  * better algorithms, however, will be very gratefully received.
191  * 
192  * Another annoyance of this approach is that it limits the
193  * available puzzles to those solvable by the algorithm I've used.
194  * My algorithm only ever considers a single row or column at any
195  * one time, which means it's incapable of solving the following
196  * difficult example (found by Bella Image around 1995/6, when she
197  * and I were both doing maths degrees):
198  * 
199  *        2  1  2  1 
200  *
201  *      +--+--+--+--+
202  * 1 1  |  |  |  |  |
203  *      +--+--+--+--+
204  *   2  |  |  |  |  |
205  *      +--+--+--+--+
206  *   1  |  |  |  |  |
207  *      +--+--+--+--+
208  *   1  |  |  |  |  |
209  *      +--+--+--+--+
210  * 
211  * Obviously this cannot be solved by a one-row-or-column-at-a-time
212  * algorithm (it would require at least one row or column reading
213  * `2 1', `1 2', `3' or `4' to get started). However, it can be
214  * proved to have a unique solution: if the top left square were
215  * empty, then the only option for the top row would be to fill the
216  * two squares in the 1 columns, which would imply the squares
217  * below those were empty, leaving no place for the 2 in the second
218  * row. Contradiction. Hence the top left square is full, and the
219  * unique solution follows easily from that starting point.
220  * 
221  * (The game ID for this puzzle is 4x4:2/1/2/1/1.1/2/1/1 , in case
222  * it's useful to anyone.)
223  */
224
225 #ifndef STANDALONE_PICTURE_GENERATOR
226 static int float_compare(const void *av, const void *bv)
227 {
228     const float *a = (const float *)av;
229     const float *b = (const float *)bv;
230     if (*a < *b)
231         return -1;
232     else if (*a > *b)
233         return +1;
234     else
235         return 0;
236 }
237
238 static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
239 {
240     float *fgrid;
241     float *fgrid2;
242     int step, i, j;
243     float threshold;
244
245     fgrid = snewn(w*h, float);
246
247     for (i = 0; i < h; i++) {
248         for (j = 0; j < w; j++) {
249             fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
250         }
251     }
252
253     /*
254      * The above gives a completely random splattering of black and
255      * white cells. We want to gently bias this in favour of _some_
256      * reasonably thick areas of white and black, while retaining
257      * some randomness and fine detail.
258      * 
259      * So we evolve the starting grid using a cellular automaton.
260      * Currently, I'm doing something very simple indeed, which is
261      * to set each square to the average of the surrounding nine
262      * cells (or the average of fewer, if we're on a corner).
263      */
264     for (step = 0; step < 1; step++) {
265         fgrid2 = snewn(w*h, float);
266
267         for (i = 0; i < h; i++) {
268             for (j = 0; j < w; j++) {
269                 float sx, xbar;
270                 int n, p, q;
271
272                 /*
273                  * Compute the average of the surrounding cells.
274                  */
275                 n = 0;
276                 sx = 0.F;
277                 for (p = -1; p <= +1; p++) {
278                     for (q = -1; q <= +1; q++) {
279                         if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
280                             continue;
281                         /*
282                          * An additional special case not mentioned
283                          * above: if a grid dimension is 2xn then
284                          * we do not average across that dimension
285                          * at all. Otherwise a 2x2 grid would
286                          * contain four identical squares.
287                          */
288                         if ((h==2 && p!=0) || (w==2 && q!=0))
289                             continue;
290                         n++;
291                         sx += fgrid[(i+p)*w+(j+q)];
292                     }
293                 }
294                 xbar = sx / n;
295
296                 fgrid2[i*w+j] = xbar;
297             }
298         }
299
300         sfree(fgrid);
301         fgrid = fgrid2;
302     }
303
304     fgrid2 = snewn(w*h, float);
305     memcpy(fgrid2, fgrid, w*h*sizeof(float));
306     qsort(fgrid2, w*h, sizeof(float), float_compare);
307     /* Choose a threshold that makes half the pixels black. In case of
308      * an odd number of pixels, select randomly between just under and
309      * just over half. */
310     {
311         int index = w * h / 2;
312         if (w & h & 1)
313             index += random_upto(rs, 2);
314         if (index < w*h)
315             threshold = fgrid2[index];
316         else
317             threshold = fgrid2[w*h-1] + 1;
318     }
319     sfree(fgrid2);
320
321     for (i = 0; i < h; i++) {
322         for (j = 0; j < w; j++) {
323             retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
324                               GRID_EMPTY);
325         }
326     }
327
328     sfree(fgrid);
329 }
330 #endif
331
332 static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
333 {
334     int i, n;
335
336     n = 0;
337
338     for (i = 0; i < len; i++) {
339         if (start[i*step] == GRID_FULL) {
340             int runlen = 1;
341             while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
342                 runlen++;
343             ret[n++] = runlen;
344             i += runlen;
345         }
346
347         if (i < len && start[i*step] == GRID_UNKNOWN)
348             return -1;
349     }
350
351     return n;
352 }
353
354 #define UNKNOWN 0
355 #define BLOCK 1
356 #define DOT 2
357 #define STILL_UNKNOWN 3
358
359 #ifdef STANDALONE_SOLVER
360 int verbose = FALSE;
361 #endif
362
363 static int do_recurse(unsigned char *known, unsigned char *deduced,
364                        unsigned char *row,
365                        unsigned char *minpos_done, unsigned char *maxpos_done,
366                        unsigned char *minpos_ok, unsigned char *maxpos_ok,
367                        int *data, int len,
368                        int freespace, int ndone, int lowest)
369 {
370     int i, j, k;
371
372
373     /* This algorithm basically tries all possible ways the given rows of
374      * black blocks can be laid out in the row/column being examined.
375      * Special care is taken to avoid checking the tail of a row/column
376      * if the same conditions have already been checked during this recursion
377      * The algorithm also takes care to cut its losses as soon as an
378      * invalid (partial) solution is detected.
379      */
380     if (data[ndone]) {
381         if (lowest >= minpos_done[ndone] && lowest <= maxpos_done[ndone]) {
382             if (lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone]) {
383                 for (i=0; i<lowest; i++)
384                     deduced[i] |= row[i];
385             }
386             return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
387         } else {
388             if (lowest < minpos_done[ndone]) minpos_done[ndone] = lowest;
389             if (lowest > maxpos_done[ndone]) maxpos_done[ndone] = lowest;
390         }
391         for (i=0; i<=freespace; i++) {
392             j = lowest;
393             for (k=0; k<i; k++) {
394                 if (known[j] == BLOCK) goto next_iter;
395                 row[j++] = DOT;
396             }
397             for (k=0; k<data[ndone]; k++) {
398                 if (known[j] == DOT) goto next_iter;
399                 row[j++] = BLOCK;
400             }
401             if (j < len) {
402                 if (known[j] == BLOCK) goto next_iter;
403                 row[j++] = DOT;
404             }
405             if (do_recurse(known, deduced, row, minpos_done, maxpos_done,
406                            minpos_ok, maxpos_ok, data, len, freespace-i, ndone+1, j)) {
407                 if (lowest < minpos_ok[ndone]) minpos_ok[ndone] = lowest;
408                 if (lowest + i > maxpos_ok[ndone]) maxpos_ok[ndone] = lowest + i;
409                 if (lowest + i > maxpos_done[ndone]) maxpos_done[ndone] = lowest + i;
410             }
411             next_iter:
412             j++;
413         }
414         return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
415     } else {
416         for (i=lowest; i<len; i++) {
417             if (known[i] == BLOCK) return FALSE;
418             row[i] = DOT;
419             }
420         for (i=0; i<len; i++)
421             deduced[i] |= row[i];
422         return TRUE;
423     }
424 }
425
426
427 static int do_row(unsigned char *known, unsigned char *deduced,
428                   unsigned char *row,
429                   unsigned char *minpos_done, unsigned char *maxpos_done,
430                   unsigned char *minpos_ok, unsigned char *maxpos_ok,
431                   unsigned char *start, int len, int step, int *data,
432                   unsigned int *changed
433 #ifdef STANDALONE_SOLVER
434                   , const char *rowcol, int index, int cluewid
435 #endif
436                   )
437 {
438     int rowlen, i, freespace, done_any;
439
440     freespace = len+1;
441     for (rowlen = 0; data[rowlen]; rowlen++) {
442         minpos_done[rowlen] = minpos_ok[rowlen] = len - 1;
443         maxpos_done[rowlen] = maxpos_ok[rowlen] = 0;
444         freespace -= data[rowlen]+1;
445     }
446
447     for (i = 0; i < len; i++) {
448         known[i] = start[i*step];
449         deduced[i] = 0;
450     }
451     for (i = len - 1; i >= 0 && known[i] == DOT; i--)
452         freespace--;
453
454     if (rowlen == 0) {
455         memset(deduced, DOT, len);
456     } else if (rowlen == 1 && data[0] == len) {
457         memset(deduced, BLOCK, len);
458     } else {
459         do_recurse(known, deduced, row, minpos_done, maxpos_done, minpos_ok,
460                    maxpos_ok, data, len, freespace, 0, 0);
461     }
462
463     done_any = FALSE;
464     for (i=0; i<len; i++)
465         if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
466             start[i*step] = deduced[i];
467             if (changed) changed[i]++;
468             done_any = TRUE;
469         }
470 #ifdef STANDALONE_SOLVER
471     if (verbose && done_any) {
472         char buf[80];
473         int thiscluewid;
474         printf("%s %2d: [", rowcol, index);
475         for (thiscluewid = -1, i = 0; data[i]; i++)
476             thiscluewid += sprintf(buf, " %d", data[i]);
477         printf("%*s", cluewid - thiscluewid, "");
478         for (i = 0; data[i]; i++)
479             printf(" %d", data[i]);
480         printf(" ] ");
481         for (i = 0; i < len; i++)
482             putchar(known[i] == BLOCK ? '#' :
483                     known[i] == DOT ? '.' : '?');
484         printf(" -> ");
485         for (i = 0; i < len; i++)
486             putchar(start[i*step] == BLOCK ? '#' :
487                     start[i*step] == DOT ? '.' : '?');
488         putchar('\n');
489     }
490 #endif
491     return done_any;
492 }
493
494 static int solve_puzzle(const game_state *state, unsigned char *grid,
495                         int w, int h,
496                         unsigned char *matrix, unsigned char *workspace,
497                         unsigned int *changed_h, unsigned int *changed_w,
498                         int *rowdata
499 #ifdef STANDALONE_SOLVER
500                         , int cluewid
501 #else
502                         , int dummy
503 #endif
504                         )
505 {
506     int i, j, ok, max;
507     int max_h, max_w;
508
509     assert((state!=NULL && state->common->rowdata!=NULL) ^ (grid!=NULL));
510
511     max = max(w, h);
512
513     memset(matrix, 0, w*h);
514     if (state) {
515         for (i=0; i<w*h; i++) {
516             if (state->common->immutable[i])
517                 matrix[i] = state->grid[i];
518         }
519     }
520
521     /* For each column, compute how many squares can be deduced
522      * from just the row-data and initial clues.
523      * Later, changed_* will hold how many squares were changed
524      * in every row/column in the previous iteration
525      * Changed_* is used to choose the next rows / cols to re-examine
526      */
527     for (i=0; i<h; i++) {
528         int freespace, rowlen;
529         if (state && state->common->rowdata) {
530             memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
531             rowlen = state->common->rowlen[w+i];
532         } else {
533             rowlen = compute_rowdata(rowdata, grid+i*w, w, 1);
534         }
535         rowdata[rowlen] = 0;
536         if (rowlen == 0) {
537             changed_h[i] = w;
538         } else {
539             for (j=0, freespace=w+1; rowdata[j]; j++)
540                 freespace -= rowdata[j] + 1;
541             for (j=0, changed_h[i]=0; rowdata[j]; j++)
542                 if (rowdata[j] > freespace)
543                     changed_h[i] += rowdata[j] - freespace;
544         }
545         for (j = 0; j < w; j++)
546             if (matrix[i*w+j])
547                 changed_h[i]++;
548     }
549     for (i=0,max_h=0; i<h; i++)
550         if (changed_h[i] > max_h)
551             max_h = changed_h[i];
552     for (i=0; i<w; i++) {
553         int freespace, rowlen;
554         if (state && state->common->rowdata) {
555             memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
556             rowlen = state->common->rowlen[i];
557         } else {
558             rowlen = compute_rowdata(rowdata, grid+i, h, w);
559         }
560         rowdata[rowlen] = 0;
561         if (rowlen == 0) {
562             changed_w[i] = h;
563         } else {
564             for (j=0, freespace=h+1; rowdata[j]; j++)
565                 freespace -= rowdata[j] + 1;
566             for (j=0, changed_w[i]=0; rowdata[j]; j++)
567                 if (rowdata[j] > freespace)
568                     changed_w[i] += rowdata[j] - freespace;
569         }
570         for (j = 0; j < h; j++)
571             if (matrix[j*w+i])
572                 changed_w[i]++;
573     }
574     for (i=0,max_w=0; i<w; i++)
575         if (changed_w[i] > max_w)
576             max_w = changed_w[i];
577
578     /* Solve the puzzle.
579      * Process rows/columns individually. Deductions involving more than one
580      * row and/or column at a time are not supported.
581      * Take care to only process rows/columns which have been changed since they
582      * were previously processed.
583      * Also, prioritize rows/columns which have had the most changes since their
584      * previous processing, as they promise the greatest benefit.
585      * Extremely rectangular grids (e.g. 10x20, 15x40, etc.) are not treated specially.
586      */
587     do {
588         for (; max_h && max_h >= max_w; max_h--) {
589             for (i=0; i<h; i++) {
590                 if (changed_h[i] >= max_h) {
591                     if (state && state->common->rowdata) {
592                         memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
593                         rowdata[state->common->rowlen[w+i]] = 0;
594                     } else {
595                         rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
596                     }
597                     do_row(workspace, workspace+max, workspace+2*max,
598                            workspace+3*max, workspace+4*max,
599                            workspace+5*max, workspace+6*max,
600                            matrix+i*w, w, 1, rowdata, changed_w
601 #ifdef STANDALONE_SOLVER
602                            , "row", i+1, cluewid
603 #endif
604                            );
605                     changed_h[i] = 0;
606                 }
607             }
608             for (i=0,max_w=0; i<w; i++)
609                 if (changed_w[i] > max_w)
610                     max_w = changed_w[i];
611         }
612         for (; max_w && max_w >= max_h; max_w--) {
613             for (i=0; i<w; i++) {
614                 if (changed_w[i] >= max_w) {
615                     if (state && state->common->rowdata) {
616                         memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
617                         rowdata[state->common->rowlen[i]] = 0;
618                     } else {
619                         rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
620                     }
621                     do_row(workspace, workspace+max, workspace+2*max,
622                            workspace+3*max, workspace+4*max,
623                            workspace+5*max, workspace+6*max,
624                            matrix+i, h, w, rowdata, changed_h
625 #ifdef STANDALONE_SOLVER
626                            , "col", i+1, cluewid
627 #endif
628                            );
629                     changed_w[i] = 0;
630                 }
631             }
632             for (i=0,max_h=0; i<h; i++)
633                 if (changed_h[i] > max_h)
634                     max_h = changed_h[i];
635         }
636     } while (max_h>0 || max_w>0);
637
638     ok = TRUE;
639     for (i=0; i<h; i++) {
640         for (j=0; j<w; j++) {
641             if (matrix[i*w+j] == UNKNOWN)
642                 ok = FALSE;
643         }
644     }
645
646     return ok;
647 }
648
649 #ifndef STANDALONE_PICTURE_GENERATOR
650 static unsigned char *generate_soluble(random_state *rs, int w, int h)
651 {
652     int i, j, ok, ntries, max;
653     unsigned char *grid, *matrix, *workspace;
654     unsigned int *changed_h, *changed_w;
655     int *rowdata;
656
657     max = max(w, h);
658
659     grid = snewn(w*h, unsigned char);
660     /* Allocate this here, to avoid having to reallocate it again for every geneerated grid */
661     matrix = snewn(w*h, unsigned char);
662     workspace = snewn(max*7, unsigned char);
663     changed_h = snewn(max+1, unsigned int);
664     changed_w = snewn(max+1, unsigned int);
665     rowdata = snewn(max+1, int);
666
667     ntries = 0;
668
669     do {
670         ntries++;
671
672         generate(rs, w, h, grid);
673
674         /*
675          * The game is a bit too easy if any row or column is
676          * completely black or completely white. An exception is
677          * made for rows/columns that are under 3 squares,
678          * otherwise nothing will ever be successfully generated.
679          */
680         ok = TRUE;
681         if (w > 2) {
682             for (i = 0; i < h; i++) {
683                 int colours = 0;
684                 for (j = 0; j < w; j++)
685                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
686                 if (colours != 3)
687                     ok = FALSE;
688             }
689         }
690         if (h > 2) {
691             for (j = 0; j < w; j++) {
692                 int colours = 0;
693                 for (i = 0; i < h; i++)
694                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
695                 if (colours != 3)
696                     ok = FALSE;
697             }
698         }
699         if (!ok)
700             continue;
701
702         ok = solve_puzzle(NULL, grid, w, h, matrix, workspace,
703                           changed_h, changed_w, rowdata, 0);
704     } while (!ok);
705
706     sfree(matrix);
707     sfree(workspace);
708     sfree(changed_h);
709     sfree(changed_w);
710     sfree(rowdata);
711     return grid;
712 }
713 #endif
714
715 #ifdef STANDALONE_PICTURE_GENERATOR
716 unsigned char *picture;
717 #endif
718
719 static char *new_game_desc(const game_params *params, random_state *rs,
720                            char **aux, int interactive)
721 {
722     unsigned char *grid;
723     int i, j, max, rowlen, *rowdata;
724     char intbuf[80], *desc;
725     int desclen, descpos;
726 #ifdef STANDALONE_PICTURE_GENERATOR
727     game_state *state;
728     int *index;
729 #endif
730
731     max = max(params->w, params->h);
732
733 #ifdef STANDALONE_PICTURE_GENERATOR
734     /*
735      * Fixed input picture.
736      */
737     grid = snewn(params->w * params->h, unsigned char);
738     memcpy(grid, picture, params->w * params->h);
739
740     /*
741      * Now winnow the immutable square set as far as possible.
742      */
743     state = snew(game_state);
744     state->grid = grid;
745     state->common = snew(game_state_common);
746     state->common->rowdata = NULL;
747     state->common->immutable = snewn(params->w * params->h, unsigned char);
748     memset(state->common->immutable, 1, params->w * params->h);
749
750     index = snewn(params->w * params->h, int);
751     for (i = 0; i < params->w * params->h; i++)
752         index[i] = i;
753     shuffle(index, params->w * params->h, sizeof(*index), rs);
754
755     {
756         unsigned char *matrix = snewn(params->w*params->h, unsigned char);
757         unsigned char *workspace = snewn(max*7, unsigned char);
758         unsigned int *changed_h = snewn(max+1, unsigned int);
759         unsigned int *changed_w = snewn(max+1, unsigned int);
760         int *rowdata = snewn(max+1, int);
761         for (i = 0; i < params->w * params->h; i++) {
762             state->common->immutable[index[i]] = 0;
763             if (!solve_puzzle(state, grid, params->w, params->h,
764                               matrix, workspace, changed_h, changed_w,
765                               rowdata, 0))
766                 state->common->immutable[index[i]] = 1;
767         }
768         sfree(workspace);
769         sfree(changed_h);
770         sfree(changed_w);
771         sfree(rowdata);
772         sfree(matrix);
773     }
774 #else
775     grid = generate_soluble(rs, params->w, params->h);
776 #endif
777     rowdata = snewn(max, int);
778
779     /*
780      * Save the solved game in aux.
781      */
782     if (aux) {
783         char *ai = snewn(params->w * params->h + 2, char);
784
785         /*
786          * String format is exactly the same as a solve move, so we
787          * can just dupstr this in solve_game().
788          */
789
790         ai[0] = 'S';
791
792         for (i = 0; i < params->w * params->h; i++)
793             ai[i+1] = grid[i] ? '1' : '0';
794
795         ai[params->w * params->h + 1] = '\0';
796
797         *aux = ai;
798     }
799
800     /*
801      * Seed is a slash-separated list of row contents; each row
802      * contents section is a dot-separated list of integers. Row
803      * contents are listed in the order (columns left to right,
804      * then rows top to bottom).
805      * 
806      * Simplest way to handle memory allocation is to make two
807      * passes, first computing the seed size and then writing it
808      * out.
809      */
810     desclen = 0;
811     for (i = 0; i < params->w + params->h; i++) {
812         if (i < params->w)
813             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
814         else
815             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
816                                      params->w, 1);
817         if (rowlen > 0) {
818             for (j = 0; j < rowlen; j++) {
819                 desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
820             }
821         } else {
822             desclen++;
823         }
824     }
825     desc = snewn(desclen, char);
826     descpos = 0;
827     for (i = 0; i < params->w + params->h; i++) {
828         if (i < params->w)
829             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
830         else
831             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
832                                      params->w, 1);
833         if (rowlen > 0) {
834             for (j = 0; j < rowlen; j++) {
835                 int len = sprintf(desc+descpos, "%d", rowdata[j]);
836                 if (j+1 < rowlen)
837                     desc[descpos + len] = '.';
838                 else
839                     desc[descpos + len] = '/';
840                 descpos += len+1;
841             }
842         } else {
843             desc[descpos++] = '/';
844         }
845     }
846     assert(descpos == desclen);
847     assert(desc[desclen-1] == '/');
848     desc[desclen-1] = '\0';
849 #ifdef STANDALONE_PICTURE_GENERATOR
850     for (i = 0; i < params->w * params->h; i++)
851         if (state->common->immutable[i])
852             break;
853     if (i < params->w * params->h) {
854         /*
855          * At least one immutable square, so we need a suffix.
856          */
857         int run;
858
859         desc = sresize(desc, desclen + params->w * params->h + 3, char);
860         desc[descpos-1] = ',';
861
862         run = 0;
863         for (i = 0; i < params->w * params->h; i++) {
864             if (!state->common->immutable[i]) {
865                 run++;
866                 if (run == 25) {
867                     desc[descpos++] = 'z';
868                     run = 0;
869                 }
870             } else {
871                 desc[descpos++] = run + (grid[i] == GRID_FULL ? 'A' : 'a');
872                 run = 0;
873             }
874         }
875         if (run > 0)
876             desc[descpos++] = run + 'a';
877         desc[descpos] = '\0';
878     }
879     sfree(state->common->immutable);
880     sfree(state->common);
881     sfree(state);
882 #endif
883     sfree(rowdata);
884     sfree(grid);
885     return desc;
886 }
887
888 static const char *validate_desc(const game_params *params, const char *desc)
889 {
890     int i, n, rowspace;
891     const char *p;
892
893     for (i = 0; i < params->w + params->h; i++) {
894         if (i < params->w)
895             rowspace = params->h + 1;
896         else
897             rowspace = params->w + 1;
898
899         if (*desc && isdigit((unsigned char)*desc)) {
900             do {
901                 p = desc;
902                 while (*desc && isdigit((unsigned char)*desc)) desc++;
903                 n = atoi(p);
904                 rowspace -= n+1;
905
906                 if (rowspace < 0) {
907                     if (i < params->w)
908                         return "at least one column contains more numbers than will fit";
909                     else
910                         return "at least one row contains more numbers than will fit";
911                 }
912             } while (*desc++ == '.');
913         } else {
914             desc++;                    /* expect a slash immediately */
915         }
916
917         if (desc[-1] == '/') {
918             if (i+1 == params->w + params->h)
919                 return "too many row/column specifications";
920         } else if (desc[-1] == '\0' || desc[-1] == ',') {
921             if (i+1 < params->w + params->h)
922                 return "too few row/column specifications";
923         } else
924             return "unrecognised character in game specification";
925     }
926
927     if (desc[-1] == ',') {
928         /*
929          * Optional extra piece of game description which fills in
930          * some grid squares as extra clues.
931          */
932         i = 0;
933         while (i < params->w * params->h) {
934             int c = (unsigned char)*desc++;
935             if ((c >= 'a' && c <= 'z') ||
936                 (c >= 'A' && c <= 'Z')) {
937                 int len = tolower(c) - 'a';
938                 i += len;
939                 if (len < 25 && i < params->w*params->h)
940                     i++;
941                 if (i > params->w * params->h) {
942                     return "too much data in clue-squares section";
943                 }
944             } else if (!c) {
945                 return "too little data in clue-squares section";
946             } else {
947                 return "unrecognised character in clue-squares section";
948             }
949         }
950         if (*desc) {
951             return "too much data in clue-squares section";
952         }
953     }
954
955     return NULL;
956 }
957
958 static game_state *new_game(midend *me, const game_params *params,
959                             const char *desc)
960 {
961     int i;
962     const char *p;
963     game_state *state = snew(game_state);
964
965     state->common = snew(game_state_common);
966     state->common->refcount = 1;
967
968     state->common->w = params->w;
969     state->common->h = params->h;
970
971     state->grid = snewn(state->common->w * state->common->h, unsigned char);
972     memset(state->grid, GRID_UNKNOWN, state->common->w * state->common->h);
973
974     state->common->immutable = snewn(state->common->w * state->common->h,
975                                      unsigned char);
976     memset(state->common->immutable, 0, state->common->w * state->common->h);
977
978     state->common->rowsize = max(state->common->w, state->common->h);
979     state->common->rowdata = snewn(state->common->rowsize * (state->common->w + state->common->h), int);
980     state->common->rowlen = snewn(state->common->w + state->common->h, int);
981
982     state->completed = state->cheated = FALSE;
983
984     for (i = 0; i < params->w + params->h; i++) {
985         state->common->rowlen[i] = 0;
986         if (*desc && isdigit((unsigned char)*desc)) {
987             do {
988                 p = desc;
989                 while (*desc && isdigit((unsigned char)*desc)) desc++;
990                 state->common->rowdata[state->common->rowsize * i + state->common->rowlen[i]++] =
991                     atoi(p);
992             } while (*desc++ == '.');
993         } else {
994             desc++;                    /* expect a slash immediately */
995         }
996     }
997
998     if (desc[-1] == ',') {
999         /*
1000          * Optional extra piece of game description which fills in
1001          * some grid squares as extra clues.
1002          */
1003         i = 0;
1004         while (i < params->w * params->h) {
1005             int c = (unsigned char)*desc++;
1006             int full = isupper(c), len = tolower(c) - 'a';
1007             i += len;
1008             if (len < 25 && i < params->w*params->h) {
1009                 state->grid[i] = full ? GRID_FULL : GRID_EMPTY;
1010                 state->common->immutable[i] = TRUE;
1011                 i++;
1012             }
1013         }
1014     }
1015
1016     return state;
1017 }
1018
1019 static game_state *dup_game(const game_state *state)
1020 {
1021     game_state *ret = snew(game_state);
1022
1023     ret->common = state->common;
1024     ret->common->refcount++;
1025
1026     ret->grid = snewn(ret->common->w * ret->common->h, unsigned char);
1027     memcpy(ret->grid, state->grid, ret->common->w * ret->common->h);
1028
1029     ret->completed = state->completed;
1030     ret->cheated = state->cheated;
1031
1032     return ret;
1033 }
1034
1035 static void free_game(game_state *state)
1036 {
1037     if (--state->common->refcount == 0) {
1038         sfree(state->common->rowdata);
1039         sfree(state->common->rowlen);
1040         sfree(state->common->immutable);
1041         sfree(state->common);
1042     }
1043     sfree(state->grid);
1044     sfree(state);
1045 }
1046
1047 static char *solve_game(const game_state *state, const game_state *currstate,
1048                         const char *ai, const char **error)
1049 {
1050     unsigned char *matrix;
1051     int w = state->common->w, h = state->common->h;
1052     int i;
1053     char *ret;
1054     int max, ok;
1055     unsigned char *workspace;
1056     unsigned int *changed_h, *changed_w;
1057     int *rowdata;
1058
1059     /*
1060      * If we already have the solved state in ai, copy it out.
1061      */
1062     if (ai)
1063         return dupstr(ai);
1064
1065     max = max(w, h);
1066     matrix = snewn(w*h, unsigned char);
1067     workspace = snewn(max*7, unsigned char);
1068     changed_h = snewn(max+1, unsigned int);
1069     changed_w = snewn(max+1, unsigned int);
1070     rowdata = snewn(max+1, int);
1071
1072     ok = solve_puzzle(state, NULL, w, h, matrix, workspace,
1073                       changed_h, changed_w, rowdata, 0);
1074
1075     sfree(workspace);
1076     sfree(changed_h);
1077     sfree(changed_w);
1078     sfree(rowdata);
1079
1080     if (!ok) {
1081         sfree(matrix);
1082         *error = "Solving algorithm cannot complete this puzzle";
1083         return NULL;
1084     }
1085
1086     ret = snewn(w*h+2, char);
1087     ret[0] = 'S';
1088     for (i = 0; i < w*h; i++) {
1089         assert(matrix[i] == BLOCK || matrix[i] == DOT);
1090         ret[i+1] = (matrix[i] == BLOCK ? '1' : '0');
1091     }
1092     ret[w*h+1] = '\0';
1093
1094     sfree(matrix);
1095
1096     return ret;
1097 }
1098
1099 static int game_can_format_as_text_now(const game_params *params)
1100 {
1101     return TRUE;
1102 }
1103
1104 static char *game_text_format(const game_state *state)
1105 {
1106     int w = state->common->w, h = state->common->h, i, j;
1107     int left_gap = 0, top_gap = 0, ch = 2, cw = 1, limit = 1;
1108
1109     int len, topleft, lw, lh, gw, gh; /* {line,grid}_{width,height} */
1110     char *board, *buf;
1111
1112     for (i = 0; i < w; ++i) {
1113         top_gap = max(top_gap, state->common->rowlen[i]);
1114         for (j = 0; j < state->common->rowlen[i]; ++j)
1115             while (state->common->rowdata[i*state->common->rowsize + j] >= limit) {
1116                 ++cw;
1117                 limit *= 10;
1118             }
1119     }
1120     for (i = 0; i < h; ++i) {
1121         int rowlen = 0, predecessors = FALSE;
1122         for (j = 0; j < state->common->rowlen[i+w]; ++j) {
1123             int copy = state->common->rowdata[(i+w)*state->common->rowsize + j];
1124             rowlen += predecessors;
1125             predecessors = TRUE;
1126             do ++rowlen; while (copy /= 10);
1127         }
1128         left_gap = max(left_gap, rowlen);
1129     }
1130
1131     cw = max(cw, 3);
1132
1133     gw = w*cw + 2;
1134     gh = h*ch + 1;
1135     lw = gw + left_gap;
1136     lh = gh + top_gap;
1137     len = lw * lh;
1138     topleft = lw * top_gap + left_gap;
1139
1140     board = snewn(len + 1, char);
1141     sprintf(board, "%*s\n", len - 2, "");
1142
1143     for (i = 0; i < lh; ++i) {
1144         board[lw - 1 + i*lw] = '\n';
1145         if (i < top_gap) continue;
1146         board[lw - 2 + i*lw] = ((i - top_gap) % ch ? '|' : '+');
1147     }
1148
1149     for (i = 0; i < w; ++i) {
1150         for (j = 0; j < state->common->rowlen[i]; ++j) {
1151             int cell = topleft + i*cw + 1 + lw*(j - state->common->rowlen[i]);
1152             int nch = sprintf(board + cell, "%*d", cw - 1,
1153                               state->common->rowdata[i*state->common->rowsize + j]);
1154             board[cell + nch] = ' '; /* de-NUL-ify */
1155         }
1156     }
1157
1158     buf = snewn(left_gap, char);
1159     for (i = 0; i < h; ++i) {
1160         char *p = buf, *start = board + top_gap*lw + left_gap + (i*ch+1)*lw;
1161         for (j = 0; j < state->common->rowlen[i+w]; ++j) {
1162             if (p > buf) *p++ = ' ';
1163             p += sprintf(p, "%d", state->common->rowdata[(i+w)*state->common->rowsize + j]);
1164         }
1165         memcpy(start - (p - buf), buf, p - buf);
1166     }
1167
1168     for (i = 0; i < w; ++i) {
1169         for (j = 0; j < h; ++j) {
1170             int cell = topleft + i*cw + j*ch*lw;
1171             int center = cell + cw/2 + (ch/2)*lw;
1172             int dx, dy;
1173             board[cell] = 0 ? center : '+';
1174             for (dx = 1; dx < cw; ++dx) board[cell + dx] = '-';
1175             for (dy = 1; dy < ch; ++dy) board[cell + dy*lw] = '|';
1176             if (state->grid[i*w+j] == GRID_UNKNOWN) continue;
1177             for (dx = 1; dx < cw; ++dx)
1178                 for (dy = 1; dy < ch; ++dy)
1179                     board[cell + dx + dy*lw] =
1180                         state->grid[i*w+j] == GRID_FULL ? '#' : '.';
1181         }
1182     }
1183
1184     memcpy(board + topleft + h*ch*lw, board + topleft, gw - 1);
1185
1186     sfree(buf);
1187
1188     return board;
1189 }
1190
1191 struct game_ui {
1192     int dragging;
1193     int drag_start_x;
1194     int drag_start_y;
1195     int drag_end_x;
1196     int drag_end_y;
1197     int drag, release, state;
1198     int cur_x, cur_y, cur_visible;
1199 };
1200
1201 static game_ui *new_ui(const game_state *state)
1202 {
1203     game_ui *ret;
1204
1205     ret = snew(game_ui);
1206     ret->dragging = FALSE;
1207     ret->cur_x = ret->cur_y = ret->cur_visible = 0;
1208
1209     return ret;
1210 }
1211
1212 static void free_ui(game_ui *ui)
1213 {
1214     sfree(ui);
1215 }
1216
1217 static char *encode_ui(const game_ui *ui)
1218 {
1219     return NULL;
1220 }
1221
1222 static void decode_ui(game_ui *ui, const char *encoding)
1223 {
1224 }
1225
1226 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1227                                const game_state *newstate)
1228 {
1229 }
1230
1231 struct game_drawstate {
1232     int started;
1233     int w, h;
1234     int tilesize;
1235     unsigned char *visible, *numcolours;
1236     int cur_x, cur_y;
1237 };
1238
1239 static char *interpret_move(const game_state *state, game_ui *ui,
1240                             const game_drawstate *ds,
1241                             int x, int y, int button)
1242 {
1243     int control = button & MOD_CTRL, shift = button & MOD_SHFT;
1244     button &= ~MOD_MASK;
1245
1246     x = FROMCOORD(state->common->w, x);
1247     y = FROMCOORD(state->common->h, y);
1248
1249     if (x >= 0 && x < state->common->w && y >= 0 && y < state->common->h &&
1250         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
1251          button == MIDDLE_BUTTON)) {
1252 #ifdef STYLUS_BASED
1253         int currstate = state->grid[y * state->common->w + x];
1254 #endif
1255
1256         ui->dragging = TRUE;
1257
1258         if (button == LEFT_BUTTON) {
1259             ui->drag = LEFT_DRAG;
1260             ui->release = LEFT_RELEASE;
1261 #ifdef STYLUS_BASED
1262             ui->state = (currstate + 2) % 3; /* FULL -> EMPTY -> UNKNOWN */
1263 #else
1264             ui->state = GRID_FULL;
1265 #endif
1266         } else if (button == RIGHT_BUTTON) {
1267             ui->drag = RIGHT_DRAG;
1268             ui->release = RIGHT_RELEASE;
1269 #ifdef STYLUS_BASED
1270             ui->state = (currstate + 1) % 3; /* EMPTY -> FULL -> UNKNOWN */
1271 #else
1272             ui->state = GRID_EMPTY;
1273 #endif
1274         } else /* if (button == MIDDLE_BUTTON) */ {
1275             ui->drag = MIDDLE_DRAG;
1276             ui->release = MIDDLE_RELEASE;
1277             ui->state = GRID_UNKNOWN;
1278         }
1279
1280         ui->drag_start_x = ui->drag_end_x = x;
1281         ui->drag_start_y = ui->drag_end_y = y;
1282         ui->cur_visible = 0;
1283
1284         return UI_UPDATE;
1285     }
1286
1287     if (ui->dragging && button == ui->drag) {
1288         /*
1289          * There doesn't seem much point in allowing a rectangle
1290          * drag; people will generally only want to drag a single
1291          * horizontal or vertical line, so we make that easy by
1292          * snapping to it.
1293          * 
1294          * Exception: if we're _middle_-button dragging to tag
1295          * things as UNKNOWN, we may well want to trash an entire
1296          * area and start over!
1297          */
1298         if (ui->state != GRID_UNKNOWN) {
1299             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
1300                 y = ui->drag_start_y;
1301             else
1302                 x = ui->drag_start_x;
1303         }
1304
1305         if (x < 0) x = 0;
1306         if (y < 0) y = 0;
1307         if (x >= state->common->w) x = state->common->w - 1;
1308         if (y >= state->common->h) y = state->common->h - 1;
1309
1310         ui->drag_end_x = x;
1311         ui->drag_end_y = y;
1312
1313         return UI_UPDATE;
1314     }
1315
1316     if (ui->dragging && button == ui->release) {
1317         int x1, x2, y1, y2, xx, yy;
1318         int move_needed = FALSE;
1319
1320         x1 = min(ui->drag_start_x, ui->drag_end_x);
1321         x2 = max(ui->drag_start_x, ui->drag_end_x);
1322         y1 = min(ui->drag_start_y, ui->drag_end_y);
1323         y2 = max(ui->drag_start_y, ui->drag_end_y);
1324
1325         for (yy = y1; yy <= y2; yy++)
1326             for (xx = x1; xx <= x2; xx++)
1327                 if (!state->common->immutable[yy * state->common->w + xx] &&
1328                     state->grid[yy * state->common->w + xx] != ui->state)
1329                     move_needed = TRUE;
1330
1331         ui->dragging = FALSE;
1332
1333         if (move_needed) {
1334             char buf[80];
1335             sprintf(buf, "%c%d,%d,%d,%d",
1336                     (char)(ui->state == GRID_FULL ? 'F' :
1337                            ui->state == GRID_EMPTY ? 'E' : 'U'),
1338                     x1, y1, x2-x1+1, y2-y1+1);
1339             return dupstr(buf);
1340         } else
1341             return UI_UPDATE;
1342     }
1343
1344     if (IS_CURSOR_MOVE(button)) {
1345         int x = ui->cur_x, y = ui->cur_y, newstate;
1346         char buf[80];
1347         move_cursor(button, &ui->cur_x, &ui->cur_y, state->common->w, state->common->h, 0);
1348         ui->cur_visible = 1;
1349         if (!control && !shift) return UI_UPDATE;
1350
1351         newstate = control ? shift ? GRID_UNKNOWN : GRID_FULL : GRID_EMPTY;
1352         if (state->grid[y * state->common->w + x] == newstate &&
1353             state->grid[ui->cur_y * state->common->w + ui->cur_x] == newstate)
1354             return UI_UPDATE;
1355
1356         sprintf(buf, "%c%d,%d,%d,%d", control ? shift ? 'U' : 'F' : 'E',
1357                 min(x, ui->cur_x), min(y, ui->cur_y),
1358                 abs(x - ui->cur_x) + 1, abs(y - ui->cur_y) + 1);
1359         return dupstr(buf);
1360     }
1361
1362     if (IS_CURSOR_SELECT(button)) {
1363         int currstate = state->grid[ui->cur_y * state->common->w + ui->cur_x];
1364         int newstate;
1365         char buf[80];
1366
1367         if (!ui->cur_visible) {
1368             ui->cur_visible = 1;
1369             return UI_UPDATE;
1370         }
1371
1372         if (button == CURSOR_SELECT2)
1373             newstate = currstate == GRID_UNKNOWN ? GRID_EMPTY :
1374                 currstate == GRID_EMPTY ? GRID_FULL : GRID_UNKNOWN;
1375         else
1376             newstate = currstate == GRID_UNKNOWN ? GRID_FULL :
1377                 currstate == GRID_FULL ? GRID_EMPTY : GRID_UNKNOWN;
1378
1379         sprintf(buf, "%c%d,%d,%d,%d",
1380                 (char)(newstate == GRID_FULL ? 'F' :
1381                        newstate == GRID_EMPTY ? 'E' : 'U'),
1382                 ui->cur_x, ui->cur_y, 1, 1);
1383         return dupstr(buf);
1384     }
1385
1386     return NULL;
1387 }
1388
1389 static game_state *execute_move(const game_state *from, const char *move)
1390 {
1391     game_state *ret;
1392     int x1, x2, y1, y2, xx, yy;
1393     int val;
1394
1395     if (move[0] == 'S' &&
1396         strlen(move) == from->common->w * from->common->h + 1) {
1397         int i;
1398
1399         ret = dup_game(from);
1400
1401         for (i = 0; i < ret->common->w * ret->common->h; i++)
1402             ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
1403
1404         ret->completed = ret->cheated = TRUE;
1405
1406         return ret;
1407     } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
1408         sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
1409         x1 >= 0 && x2 >= 0 && x1+x2 <= from->common->w &&
1410         y1 >= 0 && y2 >= 0 && y1+y2 <= from->common->h) {
1411
1412         x2 += x1;
1413         y2 += y1;
1414         val = (move[0] == 'F' ? GRID_FULL :
1415                  move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
1416
1417         ret = dup_game(from);
1418         for (yy = y1; yy < y2; yy++)
1419             for (xx = x1; xx < x2; xx++)
1420                 if (!ret->common->immutable[yy * ret->common->w + xx])
1421                     ret->grid[yy * ret->common->w + xx] = val;
1422
1423         /*
1424          * An actual change, so check to see if we've completed the
1425          * game.
1426          */
1427         if (!ret->completed) {
1428             int *rowdata = snewn(ret->common->rowsize, int);
1429             int i, len;
1430
1431             ret->completed = TRUE;
1432
1433             for (i=0; i<ret->common->w; i++) {
1434                 len = compute_rowdata(rowdata, ret->grid+i,
1435                                       ret->common->h, ret->common->w);
1436                 if (len != ret->common->rowlen[i] ||
1437                     memcmp(ret->common->rowdata+i*ret->common->rowsize,
1438                            rowdata, len * sizeof(int))) {
1439                     ret->completed = FALSE;
1440                     break;
1441                 }
1442             }
1443             for (i=0; i<ret->common->h; i++) {
1444                 len = compute_rowdata(rowdata, ret->grid+i*ret->common->w,
1445                                       ret->common->w, 1);
1446                 if (len != ret->common->rowlen[i+ret->common->w] ||
1447                     memcmp(ret->common->rowdata +
1448                            (i+ret->common->w)*ret->common->rowsize,
1449                            rowdata, len * sizeof(int))) {
1450                     ret->completed = FALSE;
1451                     break;
1452                 }
1453             }
1454
1455             sfree(rowdata);
1456         }
1457
1458         return ret;
1459     } else
1460         return NULL;
1461 }
1462
1463 /* ----------------------------------------------------------------------
1464  * Error-checking during gameplay.
1465  */
1466
1467 /*
1468  * The difficulty in error-checking Pattern is to make the error check
1469  * _weak_ enough. The most obvious way would be to check each row and
1470  * column by calling (a modified form of) do_row() to recursively
1471  * analyse the row contents against the clue set and see if the
1472  * GRID_UNKNOWNs could be filled in in any way that would end up
1473  * correct. However, this turns out to be such a strong error check as
1474  * to constitute a spoiler in many situations: you make a typo while
1475  * trying to fill in one row, and not only does the row light up to
1476  * indicate an error, but several columns crossed by the move also
1477  * light up and draw your attention to deductions you hadn't even
1478  * noticed you could make.
1479  *
1480  * So instead I restrict error-checking to 'complete runs' within a
1481  * row, by which I mean contiguous sequences of GRID_FULL bounded at
1482  * both ends by either GRID_EMPTY or the ends of the row. We identify
1483  * all the complete runs in a row, and verify that _those_ are
1484  * consistent with the row's clue list. Sequences of complete runs
1485  * separated by solid GRID_EMPTY are required to match contiguous
1486  * sequences in the clue list, whereas if there's at least one
1487  * GRID_UNKNOWN between any two complete runs then those two need not
1488  * be contiguous in the clue list.
1489  *
1490  * To simplify the edge cases, I pretend that the clue list for the
1491  * row is extended with a 0 at each end, and I also pretend that the
1492  * grid data for the row is extended with a GRID_EMPTY and a
1493  * zero-length run at each end. This permits the contiguity checker to
1494  * handle the fiddly end effects (e.g. if the first contiguous
1495  * sequence of complete runs in the grid matches _something_ in the
1496  * clue list but not at the beginning, this is allowable iff there's a
1497  * GRID_UNKNOWN before the first one) with minimal faff, since the end
1498  * effects just drop out as special cases of the normal inter-run
1499  * handling (in this code the above case is not 'at the end of the
1500  * clue list' at all, but between the implicit initial zero run and
1501  * the first nonzero one).
1502  *
1503  * We must also be a little careful about how we search for a
1504  * contiguous sequence of runs. In the clue list (1 1 2 1 2 3),
1505  * suppose we see a GRID_UNKNOWN and then a length-1 run. We search
1506  * for 1 in the clue list and find it at the very beginning. But now
1507  * suppose we find a length-2 run with no GRID_UNKNOWN before it. We
1508  * can't naively look at the next clue from the 1 we found, because
1509  * that'll be the second 1 and won't match. Instead, we must backtrack
1510  * by observing that the 2 we've just found must be contiguous with
1511  * the 1 we've already seen, so we search for the sequence (1 2) and
1512  * find it starting at the second 1. Now if we see a 3, we must
1513  * rethink again and search for (1 2 3).
1514  */
1515
1516 struct errcheck_state {
1517     /*
1518      * rowdata and rowlen point at the clue data for this row in the
1519      * game state.
1520      */
1521     int *rowdata;
1522     int rowlen;
1523     /*
1524      * rowpos indicates the lowest position where it would be valid to
1525      * see our next run length. It might be equal to rowlen,
1526      * indicating that the next run would have to be the terminating 0.
1527      */
1528     int rowpos;
1529     /*
1530      * ncontig indicates how many runs we've seen in a contiguous
1531      * block. This is taken into account when searching for the next
1532      * run we find, unless ncontig is zeroed out first by encountering
1533      * a GRID_UNKNOWN.
1534      */
1535     int ncontig;
1536 };
1537
1538 static int errcheck_found_run(struct errcheck_state *es, int r)
1539 {
1540 /* Macro to handle the pretence that rowdata has a 0 at each end */
1541 #define ROWDATA(k) ((k)<0 || (k)>=es->rowlen ? 0 : es->rowdata[(k)])
1542
1543     /*
1544      * See if we can find this new run length at a position where it
1545      * also matches the last 'ncontig' runs we've seen.
1546      */
1547     int i, newpos;
1548     for (newpos = es->rowpos; newpos <= es->rowlen; newpos++) {
1549
1550         if (ROWDATA(newpos) != r)
1551             goto notfound;
1552
1553         for (i = 1; i <= es->ncontig; i++)
1554             if (ROWDATA(newpos - i) != ROWDATA(es->rowpos - i))
1555                 goto notfound;
1556
1557         es->rowpos = newpos+1;
1558         es->ncontig++;
1559         return TRUE;
1560
1561       notfound:;
1562     }
1563
1564     return FALSE;
1565
1566 #undef ROWDATA
1567 }
1568
1569 static int check_errors(const game_state *state, int i)
1570 {
1571     int start, step, end, j;
1572     int val, runlen;
1573     struct errcheck_state aes, *es = &aes;
1574
1575     es->rowlen = state->common->rowlen[i];
1576     es->rowdata = state->common->rowdata + state->common->rowsize * i;
1577     /* Pretend that we've already encountered the initial zero run */
1578     es->ncontig = 1;
1579     es->rowpos = 0;
1580
1581     if (i < state->common->w) {
1582         start = i;
1583         step = state->common->w;
1584         end = start + step * state->common->h;
1585     } else {
1586         start = (i - state->common->w) * state->common->w;
1587         step = 1;
1588         end = start + step * state->common->w;
1589     }
1590
1591     runlen = -1;
1592     for (j = start - step; j <= end; j += step) {
1593         if (j < start || j == end)
1594             val = GRID_EMPTY;
1595         else
1596             val = state->grid[j];
1597
1598         if (val == GRID_UNKNOWN) {
1599             runlen = -1;
1600             es->ncontig = 0;
1601         } else if (val == GRID_FULL) {
1602             if (runlen >= 0)
1603                 runlen++;
1604         } else if (val == GRID_EMPTY) {
1605             if (runlen > 0) {
1606                 if (!errcheck_found_run(es, runlen))
1607                     return TRUE;       /* error! */
1608             }
1609             runlen = 0;
1610         }
1611     }
1612
1613     /* Signal end-of-row by sending errcheck_found_run the terminating
1614      * zero run, which will be marked as contiguous with the previous
1615      * run if and only if there hasn't been a GRID_UNKNOWN before. */
1616     if (!errcheck_found_run(es, 0))
1617         return TRUE;                   /* error at the last minute! */
1618
1619     return FALSE;                      /* no error */
1620 }
1621
1622 /* ----------------------------------------------------------------------
1623  * Drawing routines.
1624  */
1625
1626 static void game_compute_size(const game_params *params, int tilesize,
1627                               int *x, int *y)
1628 {
1629     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1630     struct { int tilesize; } ads, *ds = &ads;
1631     ads.tilesize = tilesize;
1632
1633     *x = SIZE(params->w);
1634     *y = SIZE(params->h);
1635 }
1636
1637 static void game_set_size(drawing *dr, game_drawstate *ds,
1638                           const game_params *params, int tilesize)
1639 {
1640     ds->tilesize = tilesize;
1641 }
1642
1643 static float *game_colours(frontend *fe, int *ncolours)
1644 {
1645     float *ret = snewn(3 * NCOLOURS, float);
1646     int i;
1647
1648     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1649
1650     for (i = 0; i < 3; i++) {
1651         ret[COL_GRID    * 3 + i] = 0.3F;
1652         ret[COL_UNKNOWN * 3 + i] = 0.5F;
1653         ret[COL_TEXT    * 3 + i] = 0.0F;
1654         ret[COL_FULL    * 3 + i] = 0.0F;
1655         ret[COL_EMPTY   * 3 + i] = 1.0F;
1656     }
1657     ret[COL_CURSOR * 3 + 0] = 1.0F;
1658     ret[COL_CURSOR * 3 + 1] = 0.25F;
1659     ret[COL_CURSOR * 3 + 2] = 0.25F;
1660     ret[COL_ERROR * 3 + 0] = 1.0F;
1661     ret[COL_ERROR * 3 + 1] = 0.0F;
1662     ret[COL_ERROR * 3 + 2] = 0.0F;
1663
1664     *ncolours = NCOLOURS;
1665     return ret;
1666 }
1667
1668 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1669 {
1670     struct game_drawstate *ds = snew(struct game_drawstate);
1671
1672     ds->started = FALSE;
1673     ds->w = state->common->w;
1674     ds->h = state->common->h;
1675     ds->visible = snewn(ds->w * ds->h, unsigned char);
1676     ds->tilesize = 0;                  /* not decided yet */
1677     memset(ds->visible, 255, ds->w * ds->h);
1678     ds->numcolours = snewn(ds->w + ds->h, unsigned char);
1679     memset(ds->numcolours, 255, ds->w + ds->h);
1680     ds->cur_x = ds->cur_y = 0;
1681
1682     return ds;
1683 }
1684
1685 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1686 {
1687     sfree(ds->visible);
1688     sfree(ds);
1689 }
1690
1691 static void grid_square(drawing *dr, game_drawstate *ds,
1692                         int y, int x, int state, int cur)
1693 {
1694     int xl, xr, yt, yb, dx, dy, dw, dh;
1695
1696     draw_rect(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1697               TILE_SIZE, TILE_SIZE, COL_GRID);
1698
1699     xl = (x % 5 == 0 ? 1 : 0);
1700     yt = (y % 5 == 0 ? 1 : 0);
1701     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1702     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1703
1704     dx = TOCOORD(ds->w, x) + 1 + xl;
1705     dy = TOCOORD(ds->h, y) + 1 + yt;
1706     dw = TILE_SIZE - xl - xr - 1;
1707     dh = TILE_SIZE - yt - yb - 1;
1708
1709     draw_rect(dr, dx, dy, dw, dh,
1710               (state == GRID_FULL ? COL_FULL :
1711                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1712     if (cur) {
1713         draw_rect_outline(dr, dx, dy, dw, dh, COL_CURSOR);
1714         draw_rect_outline(dr, dx+1, dy+1, dw-2, dh-2, COL_CURSOR);
1715     }
1716
1717     draw_update(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1718                 TILE_SIZE, TILE_SIZE);
1719 }
1720
1721 /*
1722  * Draw the numbers for a single row or column.
1723  */
1724 static void draw_numbers(drawing *dr, game_drawstate *ds,
1725                          const game_state *state, int i, int erase, int colour)
1726 {
1727     int rowlen = state->common->rowlen[i];
1728     int *rowdata = state->common->rowdata + state->common->rowsize * i;
1729     int nfit;
1730     int j;
1731
1732     if (erase) {
1733         if (i < state->common->w) {
1734             draw_rect(dr, TOCOORD(state->common->w, i), 0,
1735                       TILE_SIZE, BORDER + TLBORDER(state->common->h) * TILE_SIZE,
1736                       COL_BACKGROUND);
1737         } else {
1738             draw_rect(dr, 0, TOCOORD(state->common->h, i - state->common->w),
1739                       BORDER + TLBORDER(state->common->w) * TILE_SIZE, TILE_SIZE,
1740                       COL_BACKGROUND);
1741         }
1742     }
1743
1744     /*
1745      * Normally I space the numbers out by the same distance as the
1746      * tile size. However, if there are more numbers than available
1747      * spaces, I have to squash them up a bit.
1748      */
1749     if (i < state->common->w)
1750         nfit = TLBORDER(state->common->h);
1751     else
1752         nfit = TLBORDER(state->common->w);
1753     nfit = max(rowlen, nfit) - 1;
1754     assert(nfit > 0);
1755
1756     for (j = 0; j < rowlen; j++) {
1757         int x, y;
1758         char str[80];
1759
1760         if (i < state->common->w) {
1761             x = TOCOORD(state->common->w, i);
1762             y = BORDER + TILE_SIZE * (TLBORDER(state->common->h)-1);
1763             y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->common->h)-1) / nfit;
1764         } else {
1765             y = TOCOORD(state->common->h, i - state->common->w);
1766             x = BORDER + TILE_SIZE * (TLBORDER(state->common->w)-1);
1767             x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->common->w)-1) / nfit;
1768         }
1769
1770         sprintf(str, "%d", rowdata[j]);
1771         draw_text(dr, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1772                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, colour, str);
1773     }
1774
1775     if (i < state->common->w) {
1776         draw_update(dr, TOCOORD(state->common->w, i), 0,
1777                     TILE_SIZE, BORDER + TLBORDER(state->common->h) * TILE_SIZE);
1778     } else {
1779         draw_update(dr, 0, TOCOORD(state->common->h, i - state->common->w),
1780                     BORDER + TLBORDER(state->common->w) * TILE_SIZE, TILE_SIZE);
1781     }
1782 }
1783
1784 static void game_redraw(drawing *dr, game_drawstate *ds,
1785                         const game_state *oldstate, const game_state *state,
1786                         int dir, const game_ui *ui,
1787                         float animtime, float flashtime)
1788 {
1789     int i, j;
1790     int x1, x2, y1, y2;
1791     int cx, cy, cmoved;
1792
1793     if (!ds->started) {
1794         /*
1795          * The initial contents of the window are not guaranteed
1796          * and can vary with front ends. To be on the safe side,
1797          * all games should start by drawing a big background-
1798          * colour rectangle covering the whole window.
1799          */
1800         draw_rect(dr, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1801
1802         /*
1803          * Draw the grid outline.
1804          */
1805         draw_rect(dr, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1806                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1807                   COL_GRID);
1808
1809         ds->started = TRUE;
1810
1811         draw_update(dr, 0, 0, SIZE(ds->w), SIZE(ds->h));
1812     }
1813
1814     if (ui->dragging) {
1815         x1 = min(ui->drag_start_x, ui->drag_end_x);
1816         x2 = max(ui->drag_start_x, ui->drag_end_x);
1817         y1 = min(ui->drag_start_y, ui->drag_end_y);
1818         y2 = max(ui->drag_start_y, ui->drag_end_y);
1819     } else {
1820         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
1821     }
1822
1823     if (ui->cur_visible) {
1824         cx = ui->cur_x; cy = ui->cur_y;
1825     } else {
1826         cx = cy = -1;
1827     }
1828     cmoved = (cx != ds->cur_x || cy != ds->cur_y);
1829
1830     /*
1831      * Now draw any grid squares which have changed since last
1832      * redraw.
1833      */
1834     for (i = 0; i < ds->h; i++) {
1835         for (j = 0; j < ds->w; j++) {
1836             int val, cc = 0;
1837
1838             /*
1839              * Work out what state this square should be drawn in,
1840              * taking any current drag operation into account.
1841              */
1842             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2 &&
1843                 !state->common->immutable[i * state->common->w + j])
1844                 val = ui->state;
1845             else
1846                 val = state->grid[i * state->common->w + j];
1847
1848             if (cmoved) {
1849                 /* the cursor has moved; if we were the old or
1850                  * the new cursor position we need to redraw. */
1851                 if (j == cx && i == cy) cc = 1;
1852                 if (j == ds->cur_x && i == ds->cur_y) cc = 1;
1853             }
1854
1855             /*
1856              * Briefly invert everything twice during a completion
1857              * flash.
1858              */
1859             if (flashtime > 0 &&
1860                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1861                 val != GRID_UNKNOWN)
1862                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1863
1864             if (ds->visible[i * ds->w + j] != val || cc) {
1865                 grid_square(dr, ds, i, j, val,
1866                             (j == cx && i == cy));
1867                 ds->visible[i * ds->w + j] = val;
1868             }
1869         }
1870     }
1871     ds->cur_x = cx; ds->cur_y = cy;
1872
1873     /*
1874      * Redraw any numbers which have changed their colour due to error
1875      * indication.
1876      */
1877     for (i = 0; i < state->common->w + state->common->h; i++) {
1878         int colour = check_errors(state, i) ? COL_ERROR : COL_TEXT;
1879         if (ds->numcolours[i] != colour) {
1880             draw_numbers(dr, ds, state, i, TRUE, colour);
1881             ds->numcolours[i] = colour;
1882         }
1883     }
1884 }
1885
1886 static float game_anim_length(const game_state *oldstate,
1887                               const game_state *newstate, int dir, game_ui *ui)
1888 {
1889     return 0.0F;
1890 }
1891
1892 static float game_flash_length(const game_state *oldstate,
1893                                const game_state *newstate, int dir, game_ui *ui)
1894 {
1895     if (!oldstate->completed && newstate->completed &&
1896         !oldstate->cheated && !newstate->cheated)
1897         return FLASH_TIME;
1898     return 0.0F;
1899 }
1900
1901 static int game_status(const game_state *state)
1902 {
1903     return state->completed ? +1 : 0;
1904 }
1905
1906 static int game_timing_state(const game_state *state, game_ui *ui)
1907 {
1908     return TRUE;
1909 }
1910
1911 static void game_print_size(const game_params *params, float *x, float *y)
1912 {
1913     int pw, ph;
1914
1915     /*
1916      * I'll use 5mm squares by default.
1917      */
1918     game_compute_size(params, 500, &pw, &ph);
1919     *x = pw / 100.0F;
1920     *y = ph / 100.0F;
1921 }
1922
1923 static void game_print(drawing *dr, const game_state *state, int tilesize)
1924 {
1925     int w = state->common->w, h = state->common->h;
1926     int ink = print_mono_colour(dr, 0);
1927     int x, y, i;
1928
1929     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1930     game_drawstate ads, *ds = &ads;
1931     game_set_size(dr, ds, NULL, tilesize);
1932
1933     /*
1934      * Border.
1935      */
1936     print_line_width(dr, TILE_SIZE / 16);
1937     draw_rect_outline(dr, TOCOORD(w, 0), TOCOORD(h, 0),
1938                       w*TILE_SIZE, h*TILE_SIZE, ink);
1939
1940     /*
1941      * Grid.
1942      */
1943     for (x = 1; x < w; x++) {
1944         print_line_width(dr, TILE_SIZE / (x % 5 ? 128 : 24));
1945         draw_line(dr, TOCOORD(w, x), TOCOORD(h, 0),
1946                   TOCOORD(w, x), TOCOORD(h, h), ink);
1947     }
1948     for (y = 1; y < h; y++) {
1949         print_line_width(dr, TILE_SIZE / (y % 5 ? 128 : 24));
1950         draw_line(dr, TOCOORD(w, 0), TOCOORD(h, y),
1951                   TOCOORD(w, w), TOCOORD(h, y), ink);
1952     }
1953
1954     /*
1955      * Clues.
1956      */
1957     for (i = 0; i < state->common->w + state->common->h; i++)
1958         draw_numbers(dr, ds, state, i, FALSE, ink);
1959
1960     /*
1961      * Solution.
1962      */
1963     print_line_width(dr, TILE_SIZE / 128);
1964     for (y = 0; y < h; y++)
1965         for (x = 0; x < w; x++) {
1966             if (state->grid[y*w+x] == GRID_FULL)
1967                 draw_rect(dr, TOCOORD(w, x), TOCOORD(h, y),
1968                           TILE_SIZE, TILE_SIZE, ink);
1969             else if (state->grid[y*w+x] == GRID_EMPTY)
1970                 draw_circle(dr, TOCOORD(w, x) + TILE_SIZE/2,
1971                             TOCOORD(h, y) + TILE_SIZE/2,
1972                             TILE_SIZE/12, ink, ink);
1973         }
1974 }
1975
1976 #ifdef COMBINED
1977 #define thegame pattern
1978 #endif
1979
1980 const struct game thegame = {
1981     "Pattern", "games.pattern", "pattern",
1982     default_params,
1983     game_fetch_preset, NULL,
1984     decode_params,
1985     encode_params,
1986     free_params,
1987     dup_params,
1988     TRUE, game_configure, custom_params,
1989     validate_params,
1990     new_game_desc,
1991     validate_desc,
1992     new_game,
1993     dup_game,
1994     free_game,
1995     TRUE, solve_game,
1996     TRUE, game_can_format_as_text_now, game_text_format,
1997     new_ui,
1998     free_ui,
1999     encode_ui,
2000     decode_ui,
2001     game_changed_state,
2002     interpret_move,
2003     execute_move,
2004     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2005     game_colours,
2006     game_new_drawstate,
2007     game_free_drawstate,
2008     game_redraw,
2009     game_anim_length,
2010     game_flash_length,
2011     game_status,
2012     TRUE, FALSE, game_print_size, game_print,
2013     FALSE,                             /* wants_statusbar */
2014     FALSE, game_timing_state,
2015     REQUIRE_RBUTTON,                   /* flags */
2016 };
2017
2018 #ifdef STANDALONE_SOLVER
2019
2020 int main(int argc, char **argv)
2021 {
2022     game_params *p;
2023     game_state *s;
2024     char *id = NULL, *desc;
2025     const char *err;
2026
2027     while (--argc > 0) {
2028         char *p = *++argv;
2029         if (*p == '-') {
2030             if (!strcmp(p, "-v")) {
2031                 verbose = TRUE;
2032             } else {
2033                 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2034                 return 1;
2035             }
2036         } else {
2037             id = p;
2038         }
2039     }
2040
2041     if (!id) {
2042         fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
2043         return 1;
2044     }
2045
2046     desc = strchr(id, ':');
2047     if (!desc) {
2048         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2049         return 1;
2050     }
2051     *desc++ = '\0';
2052
2053     p = default_params();
2054     decode_params(p, id);
2055     err = validate_desc(p, desc);
2056     if (err) {
2057         fprintf(stderr, "%s: %s\n", argv[0], err);
2058         return 1;
2059     }
2060     s = new_game(NULL, p, desc);
2061
2062     {
2063         int w = p->w, h = p->h, i, j, max, cluewid = 0;
2064         unsigned char *matrix, *workspace;
2065         unsigned int *changed_h, *changed_w;
2066         int *rowdata;
2067
2068         matrix = snewn(w*h, unsigned char);
2069         max = max(w, h);
2070         workspace = snewn(max*7, unsigned char);
2071         changed_h = snewn(max+1, unsigned int);
2072         changed_w = snewn(max+1, unsigned int);
2073         rowdata = snewn(max+1, int);
2074
2075         if (verbose) {
2076             int thiswid;
2077             /*
2078              * Work out the maximum text width of the clue numbers
2079              * in a row or column, so we can print the solver's
2080              * working in a nicely lined up way.
2081              */
2082             for (i = 0; i < (w+h); i++) {
2083                 char buf[80];
2084                 for (thiswid = -1, j = 0; j < s->common->rowlen[i]; j++)
2085                     thiswid += sprintf
2086                         (buf, " %d",
2087                          s->common->rowdata[s->common->rowsize*i+j]);
2088                 if (cluewid < thiswid)
2089                     cluewid = thiswid;
2090             }
2091         }
2092
2093         solve_puzzle(s, NULL, w, h, matrix, workspace,
2094                      changed_h, changed_w, rowdata, cluewid);
2095
2096         for (i = 0; i < h; i++) {
2097             for (j = 0; j < w; j++) {
2098                 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
2099                          matrix[i*w+j] == BLOCK ? '#' :
2100                          matrix[i*w+j] == DOT ? '.' :
2101                          '!');
2102                 putchar(c);
2103             }
2104             printf("\n");
2105         }
2106     }
2107
2108     return 0;
2109 }
2110
2111 #endif
2112
2113 #ifdef STANDALONE_PICTURE_GENERATOR
2114
2115 /*
2116  * Main program for the standalone picture generator. To use it,
2117  * simply provide it with an XBM-format bitmap file (note XBM, not
2118  * XPM) on standard input, and it will output a game ID in return.
2119  * For example:
2120  *
2121  *   $ ./patternpicture < calligraphic-A.xbm
2122  *   15x15:2/4/2/2/2/3/3/3.1/3.1/3.1/11/14/12/6/1/2/2/3/4/5/1.3/2.3/1.3/2.3/1.4/9/1.1.3/2.2.3/5.4/3.2
2123  *
2124  * That looks easy, of course - all the program has done is to count
2125  * up the clue numbers! But in fact, it's done more than that: it's
2126  * also checked that the result is uniquely soluble from just the
2127  * numbers. If it hadn't been, then it would have also left some
2128  * filled squares in the playing area as extra clues.
2129  *
2130  *   $ ./patternpicture < cube.xbm
2131  *   15x15:10/2.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.10/1.1.1/1.1.1/1.1.1/2.1/10/10/1.2/1.1.1/1.1.1/1.1.1/10.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.2/10,TNINzzzzGNzw
2132  *
2133  * This enables a reasonably convenient design workflow for coming up
2134  * with pictorial Pattern puzzles which _are_ uniquely soluble without
2135  * those inelegant pre-filled squares. Fire up a bitmap editor (X11
2136  * bitmap(1) is good enough), save a trial .xbm, and then test it by
2137  * running a command along the lines of
2138  *
2139  *   $ ./pattern $(./patternpicture < test.xbm)
2140  *
2141  * If the resulting window pops up with some pre-filled squares, then
2142  * that tells you which parts of the image are giving rise to
2143  * ambiguities, so try making tweaks in those areas, try the test
2144  * command again, and see if it helps. Once you have a design for
2145  * which the Pattern starting grid comes out empty, there's your game
2146  * ID.
2147  */
2148
2149 #include <time.h>
2150
2151 int main(int argc, char **argv)
2152 {
2153     game_params *par;
2154     char *params, *desc;
2155     random_state *rs;
2156     time_t seed = time(NULL);
2157     char buf[4096];
2158     int i;
2159     int x, y;
2160
2161     par = default_params();
2162     if (argc > 1)
2163         decode_params(par, argv[1]);   /* get difficulty */
2164     par->w = par->h = -1;
2165
2166     /*
2167      * Now read an XBM file from standard input. This is simple and
2168      * hacky and will do very little error detection, so don't feed
2169      * it bogus data.
2170      */
2171     picture = NULL;
2172     x = y = 0;
2173     while (fgets(buf, sizeof(buf), stdin)) {
2174         buf[strcspn(buf, "\r\n")] = '\0';
2175         if (!strncmp(buf, "#define", 7)) {
2176             /*
2177              * Lines starting `#define' give the width and height.
2178              */
2179             char *num = buf + strlen(buf);
2180             char *symend;
2181
2182             while (num > buf && isdigit((unsigned char)num[-1]))
2183                 num--;
2184             symend = num;
2185             while (symend > buf && isspace((unsigned char)symend[-1]))
2186                 symend--;
2187
2188             if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
2189                 par->w = atoi(num);
2190             else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
2191                 par->h = atoi(num);
2192         } else {
2193             /*
2194              * Otherwise, break the string up into words and take
2195              * any word of the form `0x' plus hex digits to be a
2196              * byte.
2197              */
2198             char *p, *wordstart;
2199
2200             if (!picture) {
2201                 if (par->w < 0 || par->h < 0) {
2202                     printf("failed to read width and height\n");
2203                     return 1;
2204                 }
2205                 picture = snewn(par->w * par->h, unsigned char);
2206                 for (i = 0; i < par->w * par->h; i++)
2207                     picture[i] = GRID_UNKNOWN;
2208             }
2209
2210             p = buf;
2211             while (*p) {
2212                 while (*p && (*p == ',' || isspace((unsigned char)*p)))
2213                     p++;
2214                 wordstart = p;
2215                 while (*p && !(*p == ',' || *p == '}' ||
2216                                isspace((unsigned char)*p)))
2217                     p++;
2218                 if (*p)
2219                     *p++ = '\0';
2220
2221                 if (wordstart[0] == '0' &&
2222                     (wordstart[1] == 'x' || wordstart[1] == 'X') &&
2223                     !wordstart[2 + strspn(wordstart+2,
2224                                           "0123456789abcdefABCDEF")]) {
2225                     unsigned long byte = strtoul(wordstart+2, NULL, 16);
2226                     for (i = 0; i < 8; i++) {
2227                         int bit = (byte >> i) & 1;
2228                         if (y < par->h && x < par->w)
2229                             picture[y * par->w + x] =
2230                                 bit ? GRID_FULL : GRID_EMPTY;
2231                         x++;
2232                     }
2233
2234                     if (x >= par->w) {
2235                         x = 0;
2236                         y++;
2237                     }
2238                 }
2239             }
2240         }
2241     }
2242
2243     for (i = 0; i < par->w * par->h; i++)
2244         if (picture[i] == GRID_UNKNOWN) {
2245             fprintf(stderr, "failed to read enough bitmap data\n");
2246             return 1;
2247         }
2248
2249     rs = random_new((void*)&seed, sizeof(time_t));
2250
2251     desc = new_game_desc(par, rs, NULL, FALSE);
2252     params = encode_params(par, FALSE);
2253     printf("%s:%s\n", params, desc);
2254
2255     sfree(desc);
2256     sfree(params);
2257     free_params(par);
2258     random_free(rs);
2259
2260     return 0;
2261 }
2262
2263 #endif
2264
2265 /* vim: set shiftwidth=4 tabstop=8: */