chiark / gitweb /
Have each game declare a name which is used for window titles etc.
[sgt-puzzles.git] / cube.c
1 /*
2  * cube.c: Cube game.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <math.h>
10
11 #include "puzzles.h"
12
13 const char *const game_name = "Cube";
14
15 #define MAXVERTICES 20
16 #define MAXFACES 20
17 #define MAXORDER 4
18 struct solid {
19     int nvertices;
20     float vertices[MAXVERTICES * 3];   /* 3*npoints coordinates */
21     int order;
22     int nfaces;
23     int faces[MAXFACES * MAXORDER];    /* order*nfaces point indices */
24     float normals[MAXFACES * 3];       /* 3*npoints vector components */
25     float shear;                       /* isometric shear for nice drawing */
26     float border;                      /* border required around arena */
27 };
28
29 static const struct solid tetrahedron = {
30     4,
31     {
32         0.0F, -0.57735026919F, -0.20412414523F,
33         -0.5F, 0.28867513459F, -0.20412414523F,
34         0.0F, -0.0F, 0.6123724357F,
35         0.5F, 0.28867513459F, -0.20412414523F,
36     },
37     3, 4,
38     {
39         0,2,1, 3,1,2, 2,0,3, 1,3,0
40     },
41     {
42         -0.816496580928F, -0.471404520791F, 0.333333333334F,
43         0.0F, 0.942809041583F, 0.333333333333F,
44         0.816496580928F, -0.471404520791F, 0.333333333334F,
45         0.0F, 0.0F, -1.0F,
46     },
47     0.0F, 0.3F
48 };
49
50 static const struct solid cube = {
51     8,
52     {
53         -0.5F,-0.5F,-0.5F, -0.5F,-0.5F,+0.5F,
54         -0.5F,+0.5F,-0.5F, -0.5F,+0.5F,+0.5F,
55         +0.5F,-0.5F,-0.5F, +0.5F,-0.5F,+0.5F,
56         +0.5F,+0.5F,-0.5F, +0.5F,+0.5F,+0.5F,
57     },
58     4, 6,
59     {
60         0,1,3,2, 1,5,7,3, 5,4,6,7, 4,0,2,6, 0,4,5,1, 3,7,6,2
61     },
62     {
63         -1.0F,0.0F,0.0F, 0.0F,0.0F,+1.0F,
64         +1.0F,0.0F,0.0F, 0.0F,0.0F,-1.0F,
65         0.0F,-1.0F,0.0F, 0.0F,+1.0F,0.0F
66     },
67     0.3F, 0.5F
68 };
69
70 static const struct solid octahedron = {
71     6,
72     {
73         -0.5F, -0.28867513459472505F, 0.4082482904638664F,
74         0.5F, 0.28867513459472505F, -0.4082482904638664F,
75         -0.5F, 0.28867513459472505F, -0.4082482904638664F,
76         0.5F, -0.28867513459472505F, 0.4082482904638664F,
77         0.0F, -0.57735026918945009F, -0.4082482904638664F,
78         0.0F, 0.57735026918945009F, 0.4082482904638664F,
79     },
80     3, 8,
81     {
82         4,0,2, 0,5,2, 0,4,3, 5,0,3, 1,4,2, 5,1,2, 4,1,3, 1,5,3
83     },
84     {
85         -0.816496580928F, -0.471404520791F, -0.333333333334F,
86         -0.816496580928F, 0.471404520791F, 0.333333333334F,
87         0.0F, -0.942809041583F, 0.333333333333F,
88         0.0F, 0.0F, 1.0F,
89         0.0F, 0.0F, -1.0F,
90         0.0F, 0.942809041583F, -0.333333333333F,
91         0.816496580928F, -0.471404520791F, -0.333333333334F,
92         0.816496580928F, 0.471404520791F, 0.333333333334F,
93     },
94     0.0F, 0.5F
95 };
96
97 static const struct solid icosahedron = {
98     12,
99     {
100         0.0F, 0.57735026919F, 0.75576131408F,
101         0.0F, -0.93417235896F, 0.17841104489F,
102         0.0F, 0.93417235896F, -0.17841104489F,
103         0.0F, -0.57735026919F, -0.75576131408F,
104         -0.5F, -0.28867513459F, 0.75576131408F,
105         -0.5F, 0.28867513459F, -0.75576131408F,
106         0.5F, -0.28867513459F, 0.75576131408F,
107         0.5F, 0.28867513459F, -0.75576131408F,
108         -0.80901699437F, 0.46708617948F, 0.17841104489F,
109         0.80901699437F, 0.46708617948F, 0.17841104489F,
110         -0.80901699437F, -0.46708617948F, -0.17841104489F,
111         0.80901699437F, -0.46708617948F, -0.17841104489F,
112     },
113     3, 20,
114     {
115         8,0,2,  0,9,2,  1,10,3, 11,1,3,  0,4,6,
116         4,1,6,  5,2,7,  3,5,7,  4,8,10,  8,5,10,
117         9,6,11, 7,9,11,  0,8,4,  9,0,6,  10,1,4,
118         1,11,6, 8,2,5,  2,9,7,  3,10,5, 11,3,7,
119     },
120     {
121         -0.356822089773F, 0.87267799625F, 0.333333333333F,
122         0.356822089773F, 0.87267799625F, 0.333333333333F,
123         -0.356822089773F, -0.87267799625F, -0.333333333333F,
124         0.356822089773F, -0.87267799625F, -0.333333333333F,
125         -0.0F, 0.0F, 1.0F,
126         0.0F, -0.666666666667F, 0.745355992501F,
127         0.0F, 0.666666666667F, -0.745355992501F,
128         0.0F, 0.0F, -1.0F,
129         -0.934172358963F, -0.12732200375F, 0.333333333333F,
130         -0.934172358963F, 0.12732200375F, -0.333333333333F,
131         0.934172358963F, -0.12732200375F, 0.333333333333F,
132         0.934172358963F, 0.12732200375F, -0.333333333333F,
133         -0.57735026919F, 0.333333333334F, 0.745355992501F,
134         0.57735026919F, 0.333333333334F, 0.745355992501F,
135         -0.57735026919F, -0.745355992501F, 0.333333333334F,
136         0.57735026919F, -0.745355992501F, 0.333333333334F,
137         -0.57735026919F, 0.745355992501F, -0.333333333334F,
138         0.57735026919F, 0.745355992501F, -0.333333333334F,
139         -0.57735026919F, -0.333333333334F, -0.745355992501F,
140         0.57735026919F, -0.333333333334F, -0.745355992501F,
141     },
142     0.0F, 0.8F
143 };
144
145 enum {
146     TETRAHEDRON, CUBE, OCTAHEDRON, ICOSAHEDRON
147 };
148 static const struct solid *solids[] = {
149     &tetrahedron, &cube, &octahedron, &icosahedron
150 };
151
152 enum {
153     COL_BACKGROUND,
154     COL_BORDER,
155     COL_BLUE,
156     NCOLOURS
157 };
158
159 enum { LEFT, RIGHT, UP, DOWN, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT };
160
161 #define GRID_SCALE 48.0F
162 #define ROLLTIME 0.1F
163
164 #define SQ(x) ( (x) * (x) )
165
166 #define MATMUL(ra,m,a) do { \
167     float rx, ry, rz, xx = (a)[0], yy = (a)[1], zz = (a)[2], *mat = (m); \
168     rx = mat[0] * xx + mat[3] * yy + mat[6] * zz; \
169     ry = mat[1] * xx + mat[4] * yy + mat[7] * zz; \
170     rz = mat[2] * xx + mat[5] * yy + mat[8] * zz; \
171     (ra)[0] = rx; (ra)[1] = ry; (ra)[2] = rz; \
172 } while (0)
173
174 #define APPROXEQ(x,y) ( SQ(x-y) < 0.1 )
175
176 struct grid_square {
177     float x, y;
178     int npoints;
179     float points[8];                   /* maximum */
180     int directions[8];                 /* bit masks showing point pairs */
181     int flip;
182     int blue;
183     int tetra_class;
184 };
185
186 struct game_params {
187     int solid;
188     /*
189      * Grid dimensions. For a square grid these are width and
190      * height respectively; otherwise the grid is a hexagon, with
191      * the top side and the two lower diagonals having length d1
192      * and the remaining three sides having length d2 (so that
193      * d1==d2 gives a regular hexagon, and d2==0 gives a triangle).
194      */
195     int d1, d2;
196 };
197
198 struct game_state {
199     struct game_params params;
200     const struct solid *solid;
201     int *facecolours;
202     struct grid_square *squares;
203     int nsquares;
204     int current;                       /* index of current grid square */
205     int sgkey[2];                      /* key-point indices into grid sq */
206     int dgkey[2];                      /* key-point indices into grid sq */
207     int spkey[2];                      /* key-point indices into polyhedron */
208     int dpkey[2];                      /* key-point indices into polyhedron */
209     int previous;
210     float angle;
211     int completed;
212     int movecount;
213 };
214
215 game_params *default_params(void)
216 {
217     game_params *ret = snew(game_params);
218
219     ret->solid = CUBE;
220     ret->d1 = 4;
221     ret->d2 = 4;
222
223     return ret;
224 }
225
226 int game_fetch_preset(int i, char **name, game_params **params)
227 {
228     game_params *ret = snew(game_params);
229     char *str;
230
231     switch (i) {
232       case 0:
233         str = "Cube";
234         ret->solid = CUBE;
235         ret->d1 = 4;
236         ret->d2 = 4;
237         break;
238       case 1:
239         str = "Tetrahedron";
240         ret->solid = TETRAHEDRON;
241         ret->d1 = 2;
242         ret->d2 = 1;
243         break;
244       case 2:
245         str = "Octahedron";
246         ret->solid = OCTAHEDRON;
247         ret->d1 = 2;
248         ret->d2 = 2;
249         break;
250       case 3:
251         str = "Icosahedron";
252         ret->solid = ICOSAHEDRON;
253         ret->d1 = 3;
254         ret->d2 = 3;
255         break;
256       default:
257         sfree(ret);
258         return FALSE;
259     }
260
261     *name = dupstr(str);
262     *params = ret;
263     return TRUE;
264 }
265
266 void free_params(game_params *params)
267 {
268     sfree(params);
269 }
270
271 game_params *dup_params(game_params *params)
272 {
273     game_params *ret = snew(game_params);
274     *ret = *params;                    /* structure copy */
275     return ret;
276 }
277
278 static void enum_grid_squares(game_params *params,
279                               void (*callback)(void *, struct grid_square *),
280                               void *ctx)
281 {
282     const struct solid *solid = solids[params->solid];
283
284     if (solid->order == 4) {
285         int x, y;
286
287         for (x = 0; x < params->d1; x++)
288             for (y = 0; y < params->d2; y++) {
289                 struct grid_square sq;
290
291                 sq.x = (float)x;
292                 sq.y = (float)y;
293                 sq.points[0] = x - 0.5F;
294                 sq.points[1] = y - 0.5F;
295                 sq.points[2] = x - 0.5F;
296                 sq.points[3] = y + 0.5F;
297                 sq.points[4] = x + 0.5F;
298                 sq.points[5] = y + 0.5F;
299                 sq.points[6] = x + 0.5F;
300                 sq.points[7] = y - 0.5F;
301                 sq.npoints = 4;
302
303                 sq.directions[LEFT]  = 0x03;   /* 0,1 */
304                 sq.directions[RIGHT] = 0x0C;   /* 2,3 */
305                 sq.directions[UP]    = 0x09;   /* 0,3 */
306                 sq.directions[DOWN]  = 0x06;   /* 1,2 */
307                 sq.directions[UP_LEFT] = 0;   /* no diagonals in a square */
308                 sq.directions[UP_RIGHT] = 0;   /* no diagonals in a square */
309                 sq.directions[DOWN_LEFT] = 0;   /* no diagonals in a square */
310                 sq.directions[DOWN_RIGHT] = 0;   /* no diagonals in a square */
311
312                 sq.flip = FALSE;
313
314                 /*
315                  * This is supremely irrelevant, but just to avoid
316                  * having any uninitialised structure members...
317                  */
318                 sq.tetra_class = 0;
319
320                 callback(ctx, &sq);
321             }
322     } else {
323         int row, rowlen, other, i, firstix = -1;
324         float theight = (float)(sqrt(3) / 2.0);
325
326         for (row = 0; row < params->d1 + params->d2; row++) {
327             if (row < params->d1) {
328                 other = +1;
329                 rowlen = row + params->d2;
330             } else {
331                 other = -1;
332                 rowlen = 2*params->d1 + params->d2 - row;
333             }
334
335             /*
336              * There are `rowlen' down-pointing triangles.
337              */
338             for (i = 0; i < rowlen; i++) {
339                 struct grid_square sq;
340                 int ix;
341                 float x, y;
342
343                 ix = (2 * i - (rowlen-1));
344                 x = ix * 0.5F;
345                 y = theight * row;
346                 sq.x = x;
347                 sq.y = y + theight / 3;
348                 sq.points[0] = x - 0.5F;
349                 sq.points[1] = y;
350                 sq.points[2] = x;
351                 sq.points[3] = y + theight;
352                 sq.points[4] = x + 0.5F;
353                 sq.points[5] = y;
354                 sq.npoints = 3;
355
356                 sq.directions[LEFT]  = 0x03;   /* 0,1 */
357                 sq.directions[RIGHT] = 0x06;   /* 1,2 */
358                 sq.directions[UP]    = 0x05;   /* 0,2 */
359                 sq.directions[DOWN]  = 0;      /* invalid move */
360
361                 /*
362                  * Down-pointing triangle: both the up diagonals go
363                  * up, and the down ones go left and right.
364                  */
365                 sq.directions[UP_LEFT] = sq.directions[UP_RIGHT] =
366                     sq.directions[UP];
367                 sq.directions[DOWN_LEFT] = sq.directions[LEFT];
368                 sq.directions[DOWN_RIGHT] = sq.directions[RIGHT];
369
370                 sq.flip = TRUE;
371
372                 if (firstix < 0)
373                     firstix = ix & 3;
374                 ix -= firstix;
375                 sq.tetra_class = ((row+(ix&1)) & 2) ^ (ix & 3);
376
377                 callback(ctx, &sq);
378             }
379
380             /*
381              * There are `rowlen+other' up-pointing triangles.
382              */
383             for (i = 0; i < rowlen+other; i++) {
384                 struct grid_square sq;
385                 int ix;
386                 float x, y;
387
388                 ix = (2 * i - (rowlen+other-1));
389                 x = ix * 0.5F;
390                 y = theight * row;
391                 sq.x = x;
392                 sq.y = y + 2*theight / 3;
393                 sq.points[0] = x + 0.5F;
394                 sq.points[1] = y + theight;
395                 sq.points[2] = x;
396                 sq.points[3] = y;
397                 sq.points[4] = x - 0.5F;
398                 sq.points[5] = y + theight;
399                 sq.npoints = 3;
400
401                 sq.directions[LEFT]  = 0x06;   /* 1,2 */
402                 sq.directions[RIGHT] = 0x03;   /* 0,1 */
403                 sq.directions[DOWN]  = 0x05;   /* 0,2 */
404                 sq.directions[UP]    = 0;      /* invalid move */
405
406                 /*
407                  * Up-pointing triangle: both the down diagonals go
408                  * down, and the up ones go left and right.
409                  */
410                 sq.directions[DOWN_LEFT] = sq.directions[DOWN_RIGHT] =
411                     sq.directions[DOWN];
412                 sq.directions[UP_LEFT] = sq.directions[LEFT];
413                 sq.directions[UP_RIGHT] = sq.directions[RIGHT];
414
415                 sq.flip = FALSE;
416
417                 if (firstix < 0)
418                     firstix = ix;
419                 ix -= firstix;
420                 sq.tetra_class = ((row+(ix&1)) & 2) ^ (ix & 3);
421
422                 callback(ctx, &sq);
423             }
424         }
425     }
426 }
427
428 static int grid_area(int d1, int d2, int order)
429 {
430     /*
431      * An NxM grid of squares has NM squares in it.
432      * 
433      * A grid of triangles with dimensions A and B has a total of
434      * A^2 + B^2 + 4AB triangles in it. (You can divide it up into
435      * a side-A triangle containing A^2 subtriangles, a side-B
436      * triangle containing B^2, and two congruent parallelograms,
437      * each with side lengths A and B, each therefore containing AB
438      * two-triangle rhombuses.)
439      */
440     if (order == 4)
441         return d1 * d2;
442     else
443         return d1*d1 + d2*d2 + 4*d1*d2;
444 }
445
446 struct grid_data {
447     int *gridptrs[4];
448     int nsquares[4];
449     int nclasses;
450     int squareindex;
451 };
452
453 static void classify_grid_square_callback(void *ctx, struct grid_square *sq)
454 {
455     struct grid_data *data = (struct grid_data *)ctx;
456     int thisclass;
457
458     if (data->nclasses == 4)
459         thisclass = sq->tetra_class;
460     else if (data->nclasses == 2)
461         thisclass = sq->flip;
462     else
463         thisclass = 0;
464
465     data->gridptrs[thisclass][data->nsquares[thisclass]++] =
466         data->squareindex++;
467 }
468
469 char *new_game_seed(game_params *params)
470 {
471     struct grid_data data;
472     int i, j, k, m, area, facesperclass;
473     int *flags;
474     char *seed, *p;
475
476     /*
477      * Enumerate the grid squares, dividing them into equivalence
478      * classes as appropriate. (For the tetrahedron, there is one
479      * equivalence class for each face; for the octahedron there
480      * are two classes; for the other two solids there's only one.)
481      */
482
483     area = grid_area(params->d1, params->d2, solids[params->solid]->order);
484     if (params->solid == TETRAHEDRON)
485         data.nclasses = 4;
486     else if (params->solid == OCTAHEDRON)
487         data.nclasses = 2;
488     else
489         data.nclasses = 1;
490     data.gridptrs[0] = snewn(data.nclasses * area, int);
491     for (i = 0; i < data.nclasses; i++) {
492         data.gridptrs[i] = data.gridptrs[0] + i * area;
493         data.nsquares[i] = 0;
494     }
495     data.squareindex = 0;
496     enum_grid_squares(params, classify_grid_square_callback, &data);
497
498     facesperclass = solids[params->solid]->nfaces / data.nclasses;
499
500     for (i = 0; i < data.nclasses; i++)
501         assert(data.nsquares[i] >= facesperclass);
502     assert(data.squareindex == area);
503
504     /*
505      * So now we know how many faces to allocate in each class. Get
506      * on with it.
507      */
508     flags = snewn(area, int);
509     for (i = 0; i < area; i++)
510         flags[i] = FALSE;
511
512     for (i = 0; i < data.nclasses; i++) {
513         for (j = 0; j < facesperclass; j++) {
514             unsigned long divisor = RAND_MAX / data.nsquares[i];
515             unsigned long max = divisor * data.nsquares[i];
516             unsigned long n;
517
518             do {
519                 n = rand();
520             } while (n >= max);
521
522             n /= divisor;
523
524             assert(!flags[data.gridptrs[i][n]]);
525             flags[data.gridptrs[i][n]] = TRUE;
526
527             /*
528              * Move everything else up the array. I ought to use a
529              * better data structure for this, but for such small
530              * numbers it hardly seems worth the effort.
531              */
532             while ((int)n < data.nsquares[i]-1) {
533                 data.gridptrs[i][n] = data.gridptrs[i][n+1];
534                 n++;
535             }
536             data.nsquares[i]--;
537         }
538     }
539
540     /*
541      * Now we know precisely which squares are blue. Encode this
542      * information in hex. While we're looping over this, collect
543      * the non-blue squares into a list in the now-unused gridptrs
544      * array.
545      */
546     seed = snewn(area / 4 + 40, char);
547     p = seed;
548     j = 0;
549     k = 8;
550     m = 0;
551     for (i = 0; i < area; i++) {
552         if (flags[i]) {
553             j |= k;
554         } else {
555             data.gridptrs[0][m++] = i;
556         }
557         k >>= 1;
558         if (!k) {
559             *p++ = "0123456789ABCDEF"[j];
560             k = 8;
561             j = 0;
562         }
563     }
564     if (k != 8)
565         *p++ = "0123456789ABCDEF"[j];
566
567     /*
568      * Choose a non-blue square for the polyhedron.
569      */
570     {
571         unsigned long divisor = RAND_MAX / m;
572         unsigned long max = divisor * m;
573         unsigned long n;
574
575         do {
576             n = rand();
577         } while (n >= max);
578
579         n /= divisor;
580
581         sprintf(p, ":%d", data.gridptrs[0][n]);
582     }
583
584     sfree(data.gridptrs[0]);
585     sfree(flags);
586
587     return seed;
588 }
589
590 static void add_grid_square_callback(void *ctx, struct grid_square *sq)
591 {
592     game_state *state = (game_state *)ctx;
593
594     state->squares[state->nsquares] = *sq;   /* structure copy */
595     state->squares[state->nsquares].blue = FALSE;
596     state->nsquares++;
597 }
598
599 static int lowest_face(const struct solid *solid)
600 {
601     int i, j, best;
602     float zmin;
603
604     best = 0;
605     zmin = 0.0;
606     for (i = 0; i < solid->nfaces; i++) {
607         float z = 0;
608
609         for (j = 0; j < solid->order; j++) {
610             int f = solid->faces[i*solid->order + j];
611             z += solid->vertices[f*3+2];
612         }
613
614         if (i == 0 || zmin > z) {
615             zmin = z;
616             best = i;
617         }
618     }
619
620     return best;
621 }
622
623 static int align_poly(const struct solid *solid, struct grid_square *sq,
624                       int *pkey)
625 {
626     float zmin;
627     int i, j;
628     int flip = (sq->flip ? -1 : +1);
629
630     /*
631      * First, find the lowest z-coordinate present in the solid.
632      */
633     zmin = 0.0;
634     for (i = 0; i < solid->nvertices; i++)
635         if (zmin > solid->vertices[i*3+2])
636             zmin = solid->vertices[i*3+2];
637
638     /*
639      * Now go round the grid square. For each point in the grid
640      * square, we're looking for a point of the polyhedron with the
641      * same x- and y-coordinates (relative to the square's centre),
642      * and z-coordinate equal to zmin (near enough).
643      */
644     for (j = 0; j < sq->npoints; j++) {
645         int matches, index;
646
647         matches = 0;
648         index = -1;
649
650         for (i = 0; i < solid->nvertices; i++) {
651             float dist = 0;
652
653             dist += SQ(solid->vertices[i*3+0] * flip - sq->points[j*2+0] + sq->x);
654             dist += SQ(solid->vertices[i*3+1] * flip - sq->points[j*2+1] + sq->y);
655             dist += SQ(solid->vertices[i*3+2] - zmin);
656
657             if (dist < 0.1) {
658                 matches++;
659                 index = i;
660             }
661         }
662
663         if (matches != 1 || index < 0)
664             return FALSE;
665         pkey[j] = index;
666     }
667
668     return TRUE;
669 }
670
671 static void flip_poly(struct solid *solid, int flip)
672 {
673     int i;
674
675     if (flip) {
676         for (i = 0; i < solid->nvertices; i++) {
677             solid->vertices[i*3+0] *= -1;
678             solid->vertices[i*3+1] *= -1;
679         }
680         for (i = 0; i < solid->nfaces; i++) {
681             solid->normals[i*3+0] *= -1;
682             solid->normals[i*3+1] *= -1;
683         }
684     }
685 }
686
687 static struct solid *transform_poly(const struct solid *solid, int flip,
688                                     int key0, int key1, float angle)
689 {
690     struct solid *ret = snew(struct solid);
691     float vx, vy, ax, ay;
692     float vmatrix[9], amatrix[9], vmatrix2[9];
693     int i;
694
695     *ret = *solid;                     /* structure copy */
696
697     flip_poly(ret, flip);
698
699     /*
700      * Now rotate the polyhedron through the given angle. We must
701      * rotate about the Z-axis to bring the two vertices key0 and
702      * key1 into horizontal alignment, then rotate about the
703      * X-axis, then rotate back again.
704      */
705     vx = ret->vertices[key1*3+0] - ret->vertices[key0*3+0];
706     vy = ret->vertices[key1*3+1] - ret->vertices[key0*3+1];
707     assert(APPROXEQ(vx*vx + vy*vy, 1.0));
708
709     vmatrix[0] =  vx; vmatrix[3] = vy; vmatrix[6] = 0;
710     vmatrix[1] = -vy; vmatrix[4] = vx; vmatrix[7] = 0;
711     vmatrix[2] =   0; vmatrix[5] =  0; vmatrix[8] = 1;
712
713     ax = (float)cos(angle);
714     ay = (float)sin(angle);
715
716     amatrix[0] = 1; amatrix[3] =   0; amatrix[6] =  0;
717     amatrix[1] = 0; amatrix[4] =  ax; amatrix[7] = ay;
718     amatrix[2] = 0; amatrix[5] = -ay; amatrix[8] = ax;
719
720     memcpy(vmatrix2, vmatrix, sizeof(vmatrix));
721     vmatrix2[1] = vy;
722     vmatrix2[3] = -vy;
723
724     for (i = 0; i < ret->nvertices; i++) {
725         MATMUL(ret->vertices + 3*i, vmatrix, ret->vertices + 3*i);
726         MATMUL(ret->vertices + 3*i, amatrix, ret->vertices + 3*i);
727         MATMUL(ret->vertices + 3*i, vmatrix2, ret->vertices + 3*i);
728     }
729     for (i = 0; i < ret->nfaces; i++) {
730         MATMUL(ret->normals + 3*i, vmatrix, ret->normals + 3*i);
731         MATMUL(ret->normals + 3*i, amatrix, ret->normals + 3*i);
732         MATMUL(ret->normals + 3*i, vmatrix2, ret->normals + 3*i);
733     }
734
735     return ret;
736 }
737
738 game_state *new_game(game_params *params, char *seed)
739 {
740     game_state *state = snew(game_state);
741     int area;
742
743     state->params = *params;           /* structure copy */
744     state->solid = solids[params->solid];
745
746     area = grid_area(params->d1, params->d2, state->solid->order);
747     state->squares = snewn(area, struct grid_square);
748     state->nsquares = 0;
749     enum_grid_squares(params, add_grid_square_callback, state);
750     assert(state->nsquares == area);
751
752     state->facecolours = snewn(state->solid->nfaces, int);
753     memset(state->facecolours, 0, state->solid->nfaces * sizeof(int));
754
755     /*
756      * Set up the blue squares and polyhedron position according to
757      * the game seed.
758      */
759     {
760         char *p = seed;
761         int i, j, v;
762
763         j = 8;
764         v = 0;
765         for (i = 0; i < state->nsquares; i++) {
766             if (j == 8) {
767                 v = *p++;
768                 if (v >= '0' && v <= '9')
769                     v -= '0';
770                 else if (v >= 'A' && v <= 'F')
771                     v -= 'A' - 10;
772                 else if (v >= 'a' && v <= 'f')
773                     v -= 'a' - 10;
774                 else
775                     break;
776             }
777             if (v & j)
778                 state->squares[i].blue = TRUE;
779             j >>= 1;
780             if (j == 0)
781                 j = 8;
782         }
783
784         if (*p == ':')
785             p++;
786
787         state->current = atoi(p);
788         if (state->current < 0 || state->current >= state->nsquares)
789             state->current = 0;        /* got to do _something_ */
790     }
791
792     /*
793      * Align the polyhedron with its grid square and determine
794      * initial key points.
795      */
796     {
797         int pkey[4];
798         int ret;
799
800         ret = align_poly(state->solid, &state->squares[state->current], pkey);
801         assert(ret);
802
803         state->dpkey[0] = state->spkey[0] = pkey[0];
804         state->dpkey[1] = state->spkey[0] = pkey[1];
805         state->dgkey[0] = state->sgkey[0] = 0;
806         state->dgkey[1] = state->sgkey[0] = 1;
807     }
808
809     state->previous = state->current;
810     state->angle = 0.0;
811     state->completed = FALSE;
812     state->movecount = 0;
813
814     return state;
815 }
816
817 game_state *dup_game(game_state *state)
818 {
819     game_state *ret = snew(game_state);
820
821     ret->params = state->params;           /* structure copy */
822     ret->solid = state->solid;
823     ret->facecolours = snewn(ret->solid->nfaces, int);
824     memcpy(ret->facecolours, state->facecolours,
825            ret->solid->nfaces * sizeof(int));
826     ret->nsquares = state->nsquares;
827     ret->squares = snewn(ret->nsquares, struct grid_square);
828     memcpy(ret->squares, state->squares,
829            ret->nsquares * sizeof(struct grid_square));
830     ret->dpkey[0] = state->dpkey[0];
831     ret->dpkey[1] = state->dpkey[1];
832     ret->dgkey[0] = state->dgkey[0];
833     ret->dgkey[1] = state->dgkey[1];
834     ret->spkey[0] = state->spkey[0];
835     ret->spkey[1] = state->spkey[1];
836     ret->sgkey[0] = state->sgkey[0];
837     ret->sgkey[1] = state->sgkey[1];
838     ret->previous = state->previous;
839     ret->angle = state->angle;
840     ret->completed = state->completed;
841     ret->movecount = state->movecount;
842
843     return ret;
844 }
845
846 void free_game(game_state *state)
847 {
848     sfree(state);
849 }
850
851 game_state *make_move(game_state *from, int x, int y, int button)
852 {
853     int direction;
854     int pkey[2], skey[2], dkey[2];
855     float points[4];
856     game_state *ret;
857     float angle;
858     int i, j, dest, mask;
859     struct solid *poly;
860
861     /*
862      * All moves are made with the cursor keys.
863      */
864     if (button == CURSOR_UP)
865         direction = UP;
866     else if (button == CURSOR_DOWN)
867         direction = DOWN;
868     else if (button == CURSOR_LEFT)
869         direction = LEFT;
870     else if (button == CURSOR_RIGHT)
871         direction = RIGHT;
872     else if (button == CURSOR_UP_LEFT)
873         direction = UP_LEFT;
874     else if (button == CURSOR_DOWN_LEFT)
875         direction = DOWN_LEFT;
876     else if (button == CURSOR_UP_RIGHT)
877         direction = UP_RIGHT;
878     else if (button == CURSOR_DOWN_RIGHT)
879         direction = DOWN_RIGHT;
880     else
881         return NULL;
882
883     /*
884      * Find the two points in the current grid square which
885      * correspond to this move.
886      */
887     mask = from->squares[from->current].directions[direction];
888     if (mask == 0)
889         return NULL;
890     for (i = j = 0; i < from->squares[from->current].npoints; i++)
891         if (mask & (1 << i)) {
892             points[j*2] = from->squares[from->current].points[i*2];
893             points[j*2+1] = from->squares[from->current].points[i*2+1];
894             skey[j] = i;
895             j++;
896         }
897     assert(j == 2);
898
899     /*
900      * Now find the other grid square which shares those points.
901      * This is our move destination.
902      */
903     dest = -1;
904     for (i = 0; i < from->nsquares; i++)
905         if (i != from->current) {
906             int match = 0;
907             float dist;
908
909             for (j = 0; j < from->squares[i].npoints; j++) {
910                 dist = (SQ(from->squares[i].points[j*2] - points[0]) +
911                         SQ(from->squares[i].points[j*2+1] - points[1]));
912                 if (dist < 0.1)
913                     dkey[match++] = j;
914                 dist = (SQ(from->squares[i].points[j*2] - points[2]) +
915                         SQ(from->squares[i].points[j*2+1] - points[3]));
916                 if (dist < 0.1)
917                     dkey[match++] = j;
918             }
919
920             if (match == 2) {
921                 dest = i;
922                 break;
923             }
924         }
925
926     if (dest < 0)
927         return NULL;
928
929     ret = dup_game(from);
930     ret->current = i;
931
932     /*
933      * So we know what grid square we're aiming for, and we also
934      * know the two key points (as indices in both the source and
935      * destination grid squares) which are invariant between source
936      * and destination.
937      * 
938      * Next we must roll the polyhedron on to that square. So we
939      * find the indices of the key points within the polyhedron's
940      * vertex array, then use those in a call to transform_poly,
941      * and align the result on the new grid square.
942      */
943     {
944         int all_pkey[4];
945         align_poly(from->solid, &from->squares[from->current], all_pkey);
946         pkey[0] = all_pkey[skey[0]];
947         pkey[1] = all_pkey[skey[1]];
948         /*
949          * Now pkey[0] corresponds to skey[0] and dkey[0], and
950          * likewise [1].
951          */
952     }
953
954     /*
955      * Now find the angle through which to rotate the polyhedron.
956      * Do this by finding the two faces that share the two vertices
957      * we've found, and taking the dot product of their normals.
958      */
959     {
960         int f[2], nf = 0;
961         float dp;
962
963         for (i = 0; i < from->solid->nfaces; i++) {
964             int match = 0;
965             for (j = 0; j < from->solid->order; j++)
966                 if (from->solid->faces[i*from->solid->order + j] == pkey[0] ||
967                     from->solid->faces[i*from->solid->order + j] == pkey[1])
968                     match++;
969             if (match == 2) {
970                 assert(nf < 2);
971                 f[nf++] = i;
972             }
973         }
974
975         assert(nf == 2);
976
977         dp = 0;
978         for (i = 0; i < 3; i++)
979             dp += (from->solid->normals[f[0]*3+i] *
980                    from->solid->normals[f[1]*3+i]);
981         angle = (float)acos(dp);
982     }
983
984     /*
985      * Now transform the polyhedron. We aren't entirely sure
986      * whether we need to rotate through angle or -angle, and the
987      * simplest way round this is to try both and see which one
988      * aligns successfully!
989      * 
990      * Unfortunately, _both_ will align successfully if this is a
991      * cube, which won't tell us anything much. So for that
992      * particular case, I resort to gross hackery: I simply negate
993      * the angle before trying the alignment, depending on the
994      * direction. Which directions work which way is determined by
995      * pure trial and error. I said it was gross :-/
996      */
997     {
998         int all_pkey[4];
999         int success;
1000
1001         if (from->solid->order == 4 && direction == UP)
1002             angle = -angle;            /* HACK */
1003
1004         poly = transform_poly(from->solid,
1005                               from->squares[from->current].flip,
1006                               pkey[0], pkey[1], angle);
1007         flip_poly(poly, from->squares[ret->current].flip);
1008         success = align_poly(poly, &from->squares[ret->current], all_pkey);
1009
1010         if (!success) {
1011             angle = -angle;
1012             poly = transform_poly(from->solid,
1013                                   from->squares[from->current].flip,
1014                                   pkey[0], pkey[1], angle);
1015             flip_poly(poly, from->squares[ret->current].flip);
1016             success = align_poly(poly, &from->squares[ret->current], all_pkey);
1017         }
1018
1019         assert(success);
1020     }
1021
1022     /*
1023      * Now we have our rotated polyhedron, which we expect to be
1024      * exactly congruent to the one we started with - but with the
1025      * faces permuted. So we map that congruence and thereby figure
1026      * out how to permute the faces as a result of the polyhedron
1027      * having rolled.
1028      */
1029     {
1030         int *newcolours = snewn(from->solid->nfaces, int);
1031
1032         for (i = 0; i < from->solid->nfaces; i++)
1033             newcolours[i] = -1;
1034
1035         for (i = 0; i < from->solid->nfaces; i++) {
1036             int nmatch = 0;
1037
1038             /*
1039              * Now go through the transformed polyhedron's faces
1040              * and figure out which one's normal is approximately
1041              * equal to this one.
1042              */
1043             for (j = 0; j < poly->nfaces; j++) {
1044                 float dist;
1045                 int k;
1046
1047                 dist = 0;
1048
1049                 for (k = 0; k < 3; k++)
1050                     dist += SQ(poly->normals[j*3+k] -
1051                                from->solid->normals[i*3+k]);
1052
1053                 if (APPROXEQ(dist, 0)) {
1054                     nmatch++;
1055                     newcolours[i] = ret->facecolours[j];
1056                 }
1057             }
1058
1059             assert(nmatch == 1);
1060         }
1061
1062         for (i = 0; i < from->solid->nfaces; i++)
1063             assert(newcolours[i] != -1);
1064
1065         sfree(ret->facecolours);
1066         ret->facecolours = newcolours;
1067     }
1068
1069     /*
1070      * And finally, swap the colour between the bottom face of the
1071      * polyhedron and the face we've just landed on.
1072      * 
1073      * We don't do this if the game is already complete, since we
1074      * allow the user to roll the fully blue polyhedron around the
1075      * grid as a feeble reward.
1076      */
1077     if (!ret->completed) {
1078         i = lowest_face(from->solid);
1079         j = ret->facecolours[i];
1080         ret->facecolours[i] = ret->squares[ret->current].blue;
1081         ret->squares[ret->current].blue = j;
1082
1083         /*
1084          * Detect game completion.
1085          */
1086         j = 0;
1087         for (i = 0; i < ret->solid->nfaces; i++)
1088             if (ret->facecolours[i])
1089                 j++;
1090         if (j == ret->solid->nfaces)
1091             ret->completed = TRUE;
1092     }
1093
1094     sfree(poly);
1095
1096     /*
1097      * Align the normal polyhedron with its grid square, to get key
1098      * points for non-animated display.
1099      */
1100     {
1101         int pkey[4];
1102         int success;
1103
1104         success = align_poly(ret->solid, &ret->squares[ret->current], pkey);
1105         assert(success);
1106
1107         ret->dpkey[0] = pkey[0];
1108         ret->dpkey[1] = pkey[1];
1109         ret->dgkey[0] = 0;
1110         ret->dgkey[1] = 1;
1111     }
1112
1113
1114     ret->spkey[0] = pkey[0];
1115     ret->spkey[1] = pkey[1];
1116     ret->sgkey[0] = skey[0];
1117     ret->sgkey[1] = skey[1];
1118     ret->previous = from->current;
1119     ret->angle = angle;
1120     ret->movecount++;
1121
1122     return ret;
1123 }
1124
1125 /* ----------------------------------------------------------------------
1126  * Drawing routines.
1127  */
1128
1129 struct bbox {
1130     float l, r, u, d;
1131 };
1132
1133 struct game_drawstate {
1134     int ox, oy;                        /* pixel position of float origin */
1135 };
1136
1137 static void find_bbox_callback(void *ctx, struct grid_square *sq)
1138 {
1139     struct bbox *bb = (struct bbox *)ctx;
1140     int i;
1141
1142     for (i = 0; i < sq->npoints; i++) {
1143         if (bb->l > sq->points[i*2]) bb->l = sq->points[i*2];
1144         if (bb->r < sq->points[i*2]) bb->r = sq->points[i*2];
1145         if (bb->u > sq->points[i*2+1]) bb->u = sq->points[i*2+1];
1146         if (bb->d < sq->points[i*2+1]) bb->d = sq->points[i*2+1];
1147     }
1148 }
1149
1150 static struct bbox find_bbox(game_params *params)
1151 {
1152     struct bbox bb;
1153
1154     /*
1155      * These should be hugely more than the real bounding box will
1156      * be.
1157      */
1158     bb.l = 2.0F * (params->d1 + params->d2);
1159     bb.r = -2.0F * (params->d1 + params->d2);
1160     bb.u = 2.0F * (params->d1 + params->d2);
1161     bb.d = -2.0F * (params->d1 + params->d2);
1162     enum_grid_squares(params, find_bbox_callback, &bb);
1163
1164     return bb;
1165 }
1166
1167 void game_size(game_params *params, int *x, int *y)
1168 {
1169     struct bbox bb = find_bbox(params);
1170     *x = (int)((bb.r - bb.l + 2*solids[params->solid]->border) * GRID_SCALE);
1171     *y = (int)((bb.d - bb.u + 2*solids[params->solid]->border) * GRID_SCALE);
1172 }
1173
1174 float *game_colours(frontend *fe, game_state *state, int *ncolours)
1175 {
1176     float *ret = snewn(3 * NCOLOURS, float);
1177
1178     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1179
1180     ret[COL_BORDER * 3 + 0] = 0.0;
1181     ret[COL_BORDER * 3 + 1] = 0.0;
1182     ret[COL_BORDER * 3 + 2] = 0.0;
1183
1184     ret[COL_BLUE * 3 + 0] = 0.0;
1185     ret[COL_BLUE * 3 + 1] = 0.0;
1186     ret[COL_BLUE * 3 + 2] = 1.0;
1187
1188     *ncolours = NCOLOURS;
1189     return ret;
1190 }
1191
1192 game_drawstate *game_new_drawstate(game_state *state)
1193 {
1194     struct game_drawstate *ds = snew(struct game_drawstate);
1195     struct bbox bb = find_bbox(&state->params);
1196
1197     ds->ox = (int)(-(bb.l - state->solid->border) * GRID_SCALE);
1198     ds->oy = (int)(-(bb.u - state->solid->border) * GRID_SCALE);
1199
1200     return ds;
1201 }
1202
1203 void game_free_drawstate(game_drawstate *ds)
1204 {
1205     sfree(ds);
1206 }
1207
1208 void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1209                  game_state *state, float animtime)
1210 {
1211     int i, j;
1212     struct bbox bb = find_bbox(&state->params);
1213     struct solid *poly;
1214     int *pkey, *gkey;
1215     float t[3];
1216     float angle;
1217     game_state *newstate;
1218     int square;
1219
1220     draw_rect(fe, 0, 0, (int)((bb.r-bb.l+2.0F) * GRID_SCALE),
1221               (int)((bb.d-bb.u+2.0F) * GRID_SCALE), COL_BACKGROUND);
1222
1223     if (oldstate && oldstate->movecount > state->movecount) {
1224         game_state *t;
1225
1226         /*
1227          * This is an Undo. So reverse the order of the states, and
1228          * run the roll timer backwards.
1229          */
1230         t = oldstate;
1231         oldstate = state;
1232         state = t;
1233
1234         animtime = ROLLTIME - animtime;
1235     }
1236
1237     if (!oldstate) {
1238         oldstate = state;
1239         angle = 0.0;
1240         square = state->current;
1241         pkey = state->dpkey;
1242         gkey = state->dgkey;
1243     } else {
1244         angle = state->angle * animtime / ROLLTIME;
1245         square = state->previous;
1246         pkey = state->spkey;
1247         gkey = state->sgkey;
1248     }
1249     newstate = state;
1250     state = oldstate;
1251
1252     for (i = 0; i < state->nsquares; i++) {
1253         int coords[8];
1254
1255         for (j = 0; j < state->squares[i].npoints; j++) {
1256             coords[2*j] = ((int)(state->squares[i].points[2*j] * GRID_SCALE)
1257                            + ds->ox);
1258             coords[2*j+1] = ((int)(state->squares[i].points[2*j+1]*GRID_SCALE)
1259                              + ds->oy);
1260         }
1261
1262         draw_polygon(fe, coords, state->squares[i].npoints, TRUE,
1263                      state->squares[i].blue ? COL_BLUE : COL_BACKGROUND);
1264         draw_polygon(fe, coords, state->squares[i].npoints, FALSE, COL_BORDER);
1265     }
1266
1267     /*
1268      * Now compute and draw the polyhedron.
1269      */
1270     poly = transform_poly(state->solid, state->squares[square].flip,
1271                           pkey[0], pkey[1], angle);
1272
1273     /*
1274      * Compute the translation required to align the two key points
1275      * on the polyhedron with the same key points on the current
1276      * face.
1277      */
1278     for (i = 0; i < 3; i++) {
1279         float tc = 0.0;
1280
1281         for (j = 0; j < 2; j++) {
1282             float grid_coord;
1283
1284             if (i < 2) {
1285                 grid_coord =
1286                     state->squares[square].points[gkey[j]*2+i];
1287             } else {
1288                 grid_coord = 0.0;
1289             }
1290
1291             tc += (grid_coord - poly->vertices[pkey[j]*3+i]);
1292         }
1293
1294         t[i] = tc / 2;
1295     }
1296     for (i = 0; i < poly->nvertices; i++)
1297         for (j = 0; j < 3; j++)
1298             poly->vertices[i*3+j] += t[j];
1299
1300     /*
1301      * Now actually draw each face.
1302      */
1303     for (i = 0; i < poly->nfaces; i++) {
1304         float points[8];
1305         int coords[8];
1306
1307         for (j = 0; j < poly->order; j++) {
1308             int f = poly->faces[i*poly->order + j];
1309             points[j*2] = (poly->vertices[f*3+0] -
1310                            poly->vertices[f*3+2] * poly->shear);
1311             points[j*2+1] = (poly->vertices[f*3+1] -
1312                              poly->vertices[f*3+2] * poly->shear);
1313         }
1314
1315         for (j = 0; j < poly->order; j++) {
1316             coords[j*2] = (int)(points[j*2] * GRID_SCALE) + ds->ox;
1317             coords[j*2+1] = (int)(points[j*2+1] * GRID_SCALE) + ds->oy;
1318         }
1319
1320         /*
1321          * Find out whether these points are in a clockwise or
1322          * anticlockwise arrangement. If the latter, discard the
1323          * face because it's facing away from the viewer.
1324          *
1325          * This would involve fiddly winding-number stuff for a
1326          * general polygon, but for the simple parallelograms we'll
1327          * be seeing here, all we have to do is check whether the
1328          * corners turn right or left. So we'll take the vector
1329          * from point 0 to point 1, turn it right 90 degrees,
1330          * and check the sign of the dot product with that and the
1331          * next vector (point 1 to point 2).
1332          */
1333         {
1334             float v1x = points[2]-points[0];
1335             float v1y = points[3]-points[1];
1336             float v2x = points[4]-points[2];
1337             float v2y = points[5]-points[3];
1338             float dp = v1x * v2y - v1y * v2x;
1339
1340             if (dp <= 0)
1341                 continue;
1342         }
1343
1344         draw_polygon(fe, coords, poly->order, TRUE,
1345                      state->facecolours[i] ? COL_BLUE : COL_BACKGROUND);
1346         draw_polygon(fe, coords, poly->order, FALSE, COL_BORDER);
1347     }
1348     sfree(poly);
1349
1350     draw_update(fe, 0, 0, (int)((bb.r-bb.l+2.0F) * GRID_SCALE),
1351                 (int)((bb.d-bb.u+2.0F) * GRID_SCALE));
1352 }
1353
1354 float game_anim_length(game_state *oldstate, game_state *newstate)
1355 {
1356     return ROLLTIME;
1357 }