chiark / gitweb /
Implemented text and clipping primitives in the frontend, and added
[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             int n = rand_upto(data.nsquares[i]);
515
516             assert(!flags[data.gridptrs[i][n]]);
517             flags[data.gridptrs[i][n]] = TRUE;
518
519             /*
520              * Move everything else up the array. I ought to use a
521              * better data structure for this, but for such small
522              * numbers it hardly seems worth the effort.
523              */
524             while (n < data.nsquares[i]-1) {
525                 data.gridptrs[i][n] = data.gridptrs[i][n+1];
526                 n++;
527             }
528             data.nsquares[i]--;
529         }
530     }
531
532     /*
533      * Now we know precisely which squares are blue. Encode this
534      * information in hex. While we're looping over this, collect
535      * the non-blue squares into a list in the now-unused gridptrs
536      * array.
537      */
538     seed = snewn(area / 4 + 40, char);
539     p = seed;
540     j = 0;
541     k = 8;
542     m = 0;
543     for (i = 0; i < area; i++) {
544         if (flags[i]) {
545             j |= k;
546         } else {
547             data.gridptrs[0][m++] = i;
548         }
549         k >>= 1;
550         if (!k) {
551             *p++ = "0123456789ABCDEF"[j];
552             k = 8;
553             j = 0;
554         }
555     }
556     if (k != 8)
557         *p++ = "0123456789ABCDEF"[j];
558
559     /*
560      * Choose a non-blue square for the polyhedron.
561      */
562     sprintf(p, ":%d", rand_upto(m));
563
564     sfree(data.gridptrs[0]);
565     sfree(flags);
566
567     return seed;
568 }
569
570 static void add_grid_square_callback(void *ctx, struct grid_square *sq)
571 {
572     game_state *state = (game_state *)ctx;
573
574     state->squares[state->nsquares] = *sq;   /* structure copy */
575     state->squares[state->nsquares].blue = FALSE;
576     state->nsquares++;
577 }
578
579 static int lowest_face(const struct solid *solid)
580 {
581     int i, j, best;
582     float zmin;
583
584     best = 0;
585     zmin = 0.0;
586     for (i = 0; i < solid->nfaces; i++) {
587         float z = 0;
588
589         for (j = 0; j < solid->order; j++) {
590             int f = solid->faces[i*solid->order + j];
591             z += solid->vertices[f*3+2];
592         }
593
594         if (i == 0 || zmin > z) {
595             zmin = z;
596             best = i;
597         }
598     }
599
600     return best;
601 }
602
603 static int align_poly(const struct solid *solid, struct grid_square *sq,
604                       int *pkey)
605 {
606     float zmin;
607     int i, j;
608     int flip = (sq->flip ? -1 : +1);
609
610     /*
611      * First, find the lowest z-coordinate present in the solid.
612      */
613     zmin = 0.0;
614     for (i = 0; i < solid->nvertices; i++)
615         if (zmin > solid->vertices[i*3+2])
616             zmin = solid->vertices[i*3+2];
617
618     /*
619      * Now go round the grid square. For each point in the grid
620      * square, we're looking for a point of the polyhedron with the
621      * same x- and y-coordinates (relative to the square's centre),
622      * and z-coordinate equal to zmin (near enough).
623      */
624     for (j = 0; j < sq->npoints; j++) {
625         int matches, index;
626
627         matches = 0;
628         index = -1;
629
630         for (i = 0; i < solid->nvertices; i++) {
631             float dist = 0;
632
633             dist += SQ(solid->vertices[i*3+0] * flip - sq->points[j*2+0] + sq->x);
634             dist += SQ(solid->vertices[i*3+1] * flip - sq->points[j*2+1] + sq->y);
635             dist += SQ(solid->vertices[i*3+2] - zmin);
636
637             if (dist < 0.1) {
638                 matches++;
639                 index = i;
640             }
641         }
642
643         if (matches != 1 || index < 0)
644             return FALSE;
645         pkey[j] = index;
646     }
647
648     return TRUE;
649 }
650
651 static void flip_poly(struct solid *solid, int flip)
652 {
653     int i;
654
655     if (flip) {
656         for (i = 0; i < solid->nvertices; i++) {
657             solid->vertices[i*3+0] *= -1;
658             solid->vertices[i*3+1] *= -1;
659         }
660         for (i = 0; i < solid->nfaces; i++) {
661             solid->normals[i*3+0] *= -1;
662             solid->normals[i*3+1] *= -1;
663         }
664     }
665 }
666
667 static struct solid *transform_poly(const struct solid *solid, int flip,
668                                     int key0, int key1, float angle)
669 {
670     struct solid *ret = snew(struct solid);
671     float vx, vy, ax, ay;
672     float vmatrix[9], amatrix[9], vmatrix2[9];
673     int i;
674
675     *ret = *solid;                     /* structure copy */
676
677     flip_poly(ret, flip);
678
679     /*
680      * Now rotate the polyhedron through the given angle. We must
681      * rotate about the Z-axis to bring the two vertices key0 and
682      * key1 into horizontal alignment, then rotate about the
683      * X-axis, then rotate back again.
684      */
685     vx = ret->vertices[key1*3+0] - ret->vertices[key0*3+0];
686     vy = ret->vertices[key1*3+1] - ret->vertices[key0*3+1];
687     assert(APPROXEQ(vx*vx + vy*vy, 1.0));
688
689     vmatrix[0] =  vx; vmatrix[3] = vy; vmatrix[6] = 0;
690     vmatrix[1] = -vy; vmatrix[4] = vx; vmatrix[7] = 0;
691     vmatrix[2] =   0; vmatrix[5] =  0; vmatrix[8] = 1;
692
693     ax = (float)cos(angle);
694     ay = (float)sin(angle);
695
696     amatrix[0] = 1; amatrix[3] =   0; amatrix[6] =  0;
697     amatrix[1] = 0; amatrix[4] =  ax; amatrix[7] = ay;
698     amatrix[2] = 0; amatrix[5] = -ay; amatrix[8] = ax;
699
700     memcpy(vmatrix2, vmatrix, sizeof(vmatrix));
701     vmatrix2[1] = vy;
702     vmatrix2[3] = -vy;
703
704     for (i = 0; i < ret->nvertices; i++) {
705         MATMUL(ret->vertices + 3*i, vmatrix, ret->vertices + 3*i);
706         MATMUL(ret->vertices + 3*i, amatrix, ret->vertices + 3*i);
707         MATMUL(ret->vertices + 3*i, vmatrix2, ret->vertices + 3*i);
708     }
709     for (i = 0; i < ret->nfaces; i++) {
710         MATMUL(ret->normals + 3*i, vmatrix, ret->normals + 3*i);
711         MATMUL(ret->normals + 3*i, amatrix, ret->normals + 3*i);
712         MATMUL(ret->normals + 3*i, vmatrix2, ret->normals + 3*i);
713     }
714
715     return ret;
716 }
717
718 game_state *new_game(game_params *params, char *seed)
719 {
720     game_state *state = snew(game_state);
721     int area;
722
723     state->params = *params;           /* structure copy */
724     state->solid = solids[params->solid];
725
726     area = grid_area(params->d1, params->d2, state->solid->order);
727     state->squares = snewn(area, struct grid_square);
728     state->nsquares = 0;
729     enum_grid_squares(params, add_grid_square_callback, state);
730     assert(state->nsquares == area);
731
732     state->facecolours = snewn(state->solid->nfaces, int);
733     memset(state->facecolours, 0, state->solid->nfaces * sizeof(int));
734
735     /*
736      * Set up the blue squares and polyhedron position according to
737      * the game seed.
738      */
739     {
740         char *p = seed;
741         int i, j, v;
742
743         j = 8;
744         v = 0;
745         for (i = 0; i < state->nsquares; i++) {
746             if (j == 8) {
747                 v = *p++;
748                 if (v >= '0' && v <= '9')
749                     v -= '0';
750                 else if (v >= 'A' && v <= 'F')
751                     v -= 'A' - 10;
752                 else if (v >= 'a' && v <= 'f')
753                     v -= 'a' - 10;
754                 else
755                     break;
756             }
757             if (v & j)
758                 state->squares[i].blue = TRUE;
759             j >>= 1;
760             if (j == 0)
761                 j = 8;
762         }
763
764         if (*p == ':')
765             p++;
766
767         state->current = atoi(p);
768         if (state->current < 0 || state->current >= state->nsquares)
769             state->current = 0;        /* got to do _something_ */
770     }
771
772     /*
773      * Align the polyhedron with its grid square and determine
774      * initial key points.
775      */
776     {
777         int pkey[4];
778         int ret;
779
780         ret = align_poly(state->solid, &state->squares[state->current], pkey);
781         assert(ret);
782
783         state->dpkey[0] = state->spkey[0] = pkey[0];
784         state->dpkey[1] = state->spkey[0] = pkey[1];
785         state->dgkey[0] = state->sgkey[0] = 0;
786         state->dgkey[1] = state->sgkey[0] = 1;
787     }
788
789     state->previous = state->current;
790     state->angle = 0.0;
791     state->completed = FALSE;
792     state->movecount = 0;
793
794     return state;
795 }
796
797 game_state *dup_game(game_state *state)
798 {
799     game_state *ret = snew(game_state);
800
801     ret->params = state->params;           /* structure copy */
802     ret->solid = state->solid;
803     ret->facecolours = snewn(ret->solid->nfaces, int);
804     memcpy(ret->facecolours, state->facecolours,
805            ret->solid->nfaces * sizeof(int));
806     ret->nsquares = state->nsquares;
807     ret->squares = snewn(ret->nsquares, struct grid_square);
808     memcpy(ret->squares, state->squares,
809            ret->nsquares * sizeof(struct grid_square));
810     ret->dpkey[0] = state->dpkey[0];
811     ret->dpkey[1] = state->dpkey[1];
812     ret->dgkey[0] = state->dgkey[0];
813     ret->dgkey[1] = state->dgkey[1];
814     ret->spkey[0] = state->spkey[0];
815     ret->spkey[1] = state->spkey[1];
816     ret->sgkey[0] = state->sgkey[0];
817     ret->sgkey[1] = state->sgkey[1];
818     ret->previous = state->previous;
819     ret->angle = state->angle;
820     ret->completed = state->completed;
821     ret->movecount = state->movecount;
822
823     return ret;
824 }
825
826 void free_game(game_state *state)
827 {
828     sfree(state);
829 }
830
831 game_state *make_move(game_state *from, int x, int y, int button)
832 {
833     int direction;
834     int pkey[2], skey[2], dkey[2];
835     float points[4];
836     game_state *ret;
837     float angle;
838     int i, j, dest, mask;
839     struct solid *poly;
840
841     /*
842      * All moves are made with the cursor keys.
843      */
844     if (button == CURSOR_UP)
845         direction = UP;
846     else if (button == CURSOR_DOWN)
847         direction = DOWN;
848     else if (button == CURSOR_LEFT)
849         direction = LEFT;
850     else if (button == CURSOR_RIGHT)
851         direction = RIGHT;
852     else if (button == CURSOR_UP_LEFT)
853         direction = UP_LEFT;
854     else if (button == CURSOR_DOWN_LEFT)
855         direction = DOWN_LEFT;
856     else if (button == CURSOR_UP_RIGHT)
857         direction = UP_RIGHT;
858     else if (button == CURSOR_DOWN_RIGHT)
859         direction = DOWN_RIGHT;
860     else
861         return NULL;
862
863     /*
864      * Find the two points in the current grid square which
865      * correspond to this move.
866      */
867     mask = from->squares[from->current].directions[direction];
868     if (mask == 0)
869         return NULL;
870     for (i = j = 0; i < from->squares[from->current].npoints; i++)
871         if (mask & (1 << i)) {
872             points[j*2] = from->squares[from->current].points[i*2];
873             points[j*2+1] = from->squares[from->current].points[i*2+1];
874             skey[j] = i;
875             j++;
876         }
877     assert(j == 2);
878
879     /*
880      * Now find the other grid square which shares those points.
881      * This is our move destination.
882      */
883     dest = -1;
884     for (i = 0; i < from->nsquares; i++)
885         if (i != from->current) {
886             int match = 0;
887             float dist;
888
889             for (j = 0; j < from->squares[i].npoints; j++) {
890                 dist = (SQ(from->squares[i].points[j*2] - points[0]) +
891                         SQ(from->squares[i].points[j*2+1] - points[1]));
892                 if (dist < 0.1)
893                     dkey[match++] = j;
894                 dist = (SQ(from->squares[i].points[j*2] - points[2]) +
895                         SQ(from->squares[i].points[j*2+1] - points[3]));
896                 if (dist < 0.1)
897                     dkey[match++] = j;
898             }
899
900             if (match == 2) {
901                 dest = i;
902                 break;
903             }
904         }
905
906     if (dest < 0)
907         return NULL;
908
909     ret = dup_game(from);
910     ret->current = i;
911
912     /*
913      * So we know what grid square we're aiming for, and we also
914      * know the two key points (as indices in both the source and
915      * destination grid squares) which are invariant between source
916      * and destination.
917      * 
918      * Next we must roll the polyhedron on to that square. So we
919      * find the indices of the key points within the polyhedron's
920      * vertex array, then use those in a call to transform_poly,
921      * and align the result on the new grid square.
922      */
923     {
924         int all_pkey[4];
925         align_poly(from->solid, &from->squares[from->current], all_pkey);
926         pkey[0] = all_pkey[skey[0]];
927         pkey[1] = all_pkey[skey[1]];
928         /*
929          * Now pkey[0] corresponds to skey[0] and dkey[0], and
930          * likewise [1].
931          */
932     }
933
934     /*
935      * Now find the angle through which to rotate the polyhedron.
936      * Do this by finding the two faces that share the two vertices
937      * we've found, and taking the dot product of their normals.
938      */
939     {
940         int f[2], nf = 0;
941         float dp;
942
943         for (i = 0; i < from->solid->nfaces; i++) {
944             int match = 0;
945             for (j = 0; j < from->solid->order; j++)
946                 if (from->solid->faces[i*from->solid->order + j] == pkey[0] ||
947                     from->solid->faces[i*from->solid->order + j] == pkey[1])
948                     match++;
949             if (match == 2) {
950                 assert(nf < 2);
951                 f[nf++] = i;
952             }
953         }
954
955         assert(nf == 2);
956
957         dp = 0;
958         for (i = 0; i < 3; i++)
959             dp += (from->solid->normals[f[0]*3+i] *
960                    from->solid->normals[f[1]*3+i]);
961         angle = (float)acos(dp);
962     }
963
964     /*
965      * Now transform the polyhedron. We aren't entirely sure
966      * whether we need to rotate through angle or -angle, and the
967      * simplest way round this is to try both and see which one
968      * aligns successfully!
969      * 
970      * Unfortunately, _both_ will align successfully if this is a
971      * cube, which won't tell us anything much. So for that
972      * particular case, I resort to gross hackery: I simply negate
973      * the angle before trying the alignment, depending on the
974      * direction. Which directions work which way is determined by
975      * pure trial and error. I said it was gross :-/
976      */
977     {
978         int all_pkey[4];
979         int success;
980
981         if (from->solid->order == 4 && direction == UP)
982             angle = -angle;            /* HACK */
983
984         poly = transform_poly(from->solid,
985                               from->squares[from->current].flip,
986                               pkey[0], pkey[1], angle);
987         flip_poly(poly, from->squares[ret->current].flip);
988         success = align_poly(poly, &from->squares[ret->current], all_pkey);
989
990         if (!success) {
991             angle = -angle;
992             poly = transform_poly(from->solid,
993                                   from->squares[from->current].flip,
994                                   pkey[0], pkey[1], angle);
995             flip_poly(poly, from->squares[ret->current].flip);
996             success = align_poly(poly, &from->squares[ret->current], all_pkey);
997         }
998
999         assert(success);
1000     }
1001
1002     /*
1003      * Now we have our rotated polyhedron, which we expect to be
1004      * exactly congruent to the one we started with - but with the
1005      * faces permuted. So we map that congruence and thereby figure
1006      * out how to permute the faces as a result of the polyhedron
1007      * having rolled.
1008      */
1009     {
1010         int *newcolours = snewn(from->solid->nfaces, int);
1011
1012         for (i = 0; i < from->solid->nfaces; i++)
1013             newcolours[i] = -1;
1014
1015         for (i = 0; i < from->solid->nfaces; i++) {
1016             int nmatch = 0;
1017
1018             /*
1019              * Now go through the transformed polyhedron's faces
1020              * and figure out which one's normal is approximately
1021              * equal to this one.
1022              */
1023             for (j = 0; j < poly->nfaces; j++) {
1024                 float dist;
1025                 int k;
1026
1027                 dist = 0;
1028
1029                 for (k = 0; k < 3; k++)
1030                     dist += SQ(poly->normals[j*3+k] -
1031                                from->solid->normals[i*3+k]);
1032
1033                 if (APPROXEQ(dist, 0)) {
1034                     nmatch++;
1035                     newcolours[i] = ret->facecolours[j];
1036                 }
1037             }
1038
1039             assert(nmatch == 1);
1040         }
1041
1042         for (i = 0; i < from->solid->nfaces; i++)
1043             assert(newcolours[i] != -1);
1044
1045         sfree(ret->facecolours);
1046         ret->facecolours = newcolours;
1047     }
1048
1049     /*
1050      * And finally, swap the colour between the bottom face of the
1051      * polyhedron and the face we've just landed on.
1052      * 
1053      * We don't do this if the game is already complete, since we
1054      * allow the user to roll the fully blue polyhedron around the
1055      * grid as a feeble reward.
1056      */
1057     if (!ret->completed) {
1058         i = lowest_face(from->solid);
1059         j = ret->facecolours[i];
1060         ret->facecolours[i] = ret->squares[ret->current].blue;
1061         ret->squares[ret->current].blue = j;
1062
1063         /*
1064          * Detect game completion.
1065          */
1066         j = 0;
1067         for (i = 0; i < ret->solid->nfaces; i++)
1068             if (ret->facecolours[i])
1069                 j++;
1070         if (j == ret->solid->nfaces)
1071             ret->completed = TRUE;
1072     }
1073
1074     sfree(poly);
1075
1076     /*
1077      * Align the normal polyhedron with its grid square, to get key
1078      * points for non-animated display.
1079      */
1080     {
1081         int pkey[4];
1082         int success;
1083
1084         success = align_poly(ret->solid, &ret->squares[ret->current], pkey);
1085         assert(success);
1086
1087         ret->dpkey[0] = pkey[0];
1088         ret->dpkey[1] = pkey[1];
1089         ret->dgkey[0] = 0;
1090         ret->dgkey[1] = 1;
1091     }
1092
1093
1094     ret->spkey[0] = pkey[0];
1095     ret->spkey[1] = pkey[1];
1096     ret->sgkey[0] = skey[0];
1097     ret->sgkey[1] = skey[1];
1098     ret->previous = from->current;
1099     ret->angle = angle;
1100     ret->movecount++;
1101
1102     return ret;
1103 }
1104
1105 /* ----------------------------------------------------------------------
1106  * Drawing routines.
1107  */
1108
1109 struct bbox {
1110     float l, r, u, d;
1111 };
1112
1113 struct game_drawstate {
1114     int ox, oy;                        /* pixel position of float origin */
1115 };
1116
1117 static void find_bbox_callback(void *ctx, struct grid_square *sq)
1118 {
1119     struct bbox *bb = (struct bbox *)ctx;
1120     int i;
1121
1122     for (i = 0; i < sq->npoints; i++) {
1123         if (bb->l > sq->points[i*2]) bb->l = sq->points[i*2];
1124         if (bb->r < sq->points[i*2]) bb->r = sq->points[i*2];
1125         if (bb->u > sq->points[i*2+1]) bb->u = sq->points[i*2+1];
1126         if (bb->d < sq->points[i*2+1]) bb->d = sq->points[i*2+1];
1127     }
1128 }
1129
1130 static struct bbox find_bbox(game_params *params)
1131 {
1132     struct bbox bb;
1133
1134     /*
1135      * These should be hugely more than the real bounding box will
1136      * be.
1137      */
1138     bb.l = 2.0F * (params->d1 + params->d2);
1139     bb.r = -2.0F * (params->d1 + params->d2);
1140     bb.u = 2.0F * (params->d1 + params->d2);
1141     bb.d = -2.0F * (params->d1 + params->d2);
1142     enum_grid_squares(params, find_bbox_callback, &bb);
1143
1144     return bb;
1145 }
1146
1147 void game_size(game_params *params, int *x, int *y)
1148 {
1149     struct bbox bb = find_bbox(params);
1150     *x = (int)((bb.r - bb.l + 2*solids[params->solid]->border) * GRID_SCALE);
1151     *y = (int)((bb.d - bb.u + 2*solids[params->solid]->border) * GRID_SCALE);
1152 }
1153
1154 float *game_colours(frontend *fe, game_state *state, int *ncolours)
1155 {
1156     float *ret = snewn(3 * NCOLOURS, float);
1157
1158     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1159
1160     ret[COL_BORDER * 3 + 0] = 0.0;
1161     ret[COL_BORDER * 3 + 1] = 0.0;
1162     ret[COL_BORDER * 3 + 2] = 0.0;
1163
1164     ret[COL_BLUE * 3 + 0] = 0.0;
1165     ret[COL_BLUE * 3 + 1] = 0.0;
1166     ret[COL_BLUE * 3 + 2] = 1.0;
1167
1168     *ncolours = NCOLOURS;
1169     return ret;
1170 }
1171
1172 game_drawstate *game_new_drawstate(game_state *state)
1173 {
1174     struct game_drawstate *ds = snew(struct game_drawstate);
1175     struct bbox bb = find_bbox(&state->params);
1176
1177     ds->ox = (int)(-(bb.l - state->solid->border) * GRID_SCALE);
1178     ds->oy = (int)(-(bb.u - state->solid->border) * GRID_SCALE);
1179
1180     return ds;
1181 }
1182
1183 void game_free_drawstate(game_drawstate *ds)
1184 {
1185     sfree(ds);
1186 }
1187
1188 void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1189                  game_state *state, float animtime, float flashtime)
1190 {
1191     int i, j;
1192     struct bbox bb = find_bbox(&state->params);
1193     struct solid *poly;
1194     int *pkey, *gkey;
1195     float t[3];
1196     float angle;
1197     game_state *newstate;
1198     int square;
1199
1200     draw_rect(fe, 0, 0, (int)((bb.r-bb.l+2.0F) * GRID_SCALE),
1201               (int)((bb.d-bb.u+2.0F) * GRID_SCALE), COL_BACKGROUND);
1202
1203     if (oldstate && oldstate->movecount > state->movecount) {
1204         game_state *t;
1205
1206         /*
1207          * This is an Undo. So reverse the order of the states, and
1208          * run the roll timer backwards.
1209          */
1210         t = oldstate;
1211         oldstate = state;
1212         state = t;
1213
1214         animtime = ROLLTIME - animtime;
1215     }
1216
1217     if (!oldstate) {
1218         oldstate = state;
1219         angle = 0.0;
1220         square = state->current;
1221         pkey = state->dpkey;
1222         gkey = state->dgkey;
1223     } else {
1224         angle = state->angle * animtime / ROLLTIME;
1225         square = state->previous;
1226         pkey = state->spkey;
1227         gkey = state->sgkey;
1228     }
1229     newstate = state;
1230     state = oldstate;
1231
1232     for (i = 0; i < state->nsquares; i++) {
1233         int coords[8];
1234
1235         for (j = 0; j < state->squares[i].npoints; j++) {
1236             coords[2*j] = ((int)(state->squares[i].points[2*j] * GRID_SCALE)
1237                            + ds->ox);
1238             coords[2*j+1] = ((int)(state->squares[i].points[2*j+1]*GRID_SCALE)
1239                              + ds->oy);
1240         }
1241
1242         draw_polygon(fe, coords, state->squares[i].npoints, TRUE,
1243                      state->squares[i].blue ? COL_BLUE : COL_BACKGROUND);
1244         draw_polygon(fe, coords, state->squares[i].npoints, FALSE, COL_BORDER);
1245     }
1246
1247     /*
1248      * Now compute and draw the polyhedron.
1249      */
1250     poly = transform_poly(state->solid, state->squares[square].flip,
1251                           pkey[0], pkey[1], angle);
1252
1253     /*
1254      * Compute the translation required to align the two key points
1255      * on the polyhedron with the same key points on the current
1256      * face.
1257      */
1258     for (i = 0; i < 3; i++) {
1259         float tc = 0.0;
1260
1261         for (j = 0; j < 2; j++) {
1262             float grid_coord;
1263
1264             if (i < 2) {
1265                 grid_coord =
1266                     state->squares[square].points[gkey[j]*2+i];
1267             } else {
1268                 grid_coord = 0.0;
1269             }
1270
1271             tc += (grid_coord - poly->vertices[pkey[j]*3+i]);
1272         }
1273
1274         t[i] = tc / 2;
1275     }
1276     for (i = 0; i < poly->nvertices; i++)
1277         for (j = 0; j < 3; j++)
1278             poly->vertices[i*3+j] += t[j];
1279
1280     /*
1281      * Now actually draw each face.
1282      */
1283     for (i = 0; i < poly->nfaces; i++) {
1284         float points[8];
1285         int coords[8];
1286
1287         for (j = 0; j < poly->order; j++) {
1288             int f = poly->faces[i*poly->order + j];
1289             points[j*2] = (poly->vertices[f*3+0] -
1290                            poly->vertices[f*3+2] * poly->shear);
1291             points[j*2+1] = (poly->vertices[f*3+1] -
1292                              poly->vertices[f*3+2] * poly->shear);
1293         }
1294
1295         for (j = 0; j < poly->order; j++) {
1296             coords[j*2] = (int)(points[j*2] * GRID_SCALE) + ds->ox;
1297             coords[j*2+1] = (int)(points[j*2+1] * GRID_SCALE) + ds->oy;
1298         }
1299
1300         /*
1301          * Find out whether these points are in a clockwise or
1302          * anticlockwise arrangement. If the latter, discard the
1303          * face because it's facing away from the viewer.
1304          *
1305          * This would involve fiddly winding-number stuff for a
1306          * general polygon, but for the simple parallelograms we'll
1307          * be seeing here, all we have to do is check whether the
1308          * corners turn right or left. So we'll take the vector
1309          * from point 0 to point 1, turn it right 90 degrees,
1310          * and check the sign of the dot product with that and the
1311          * next vector (point 1 to point 2).
1312          */
1313         {
1314             float v1x = points[2]-points[0];
1315             float v1y = points[3]-points[1];
1316             float v2x = points[4]-points[2];
1317             float v2y = points[5]-points[3];
1318             float dp = v1x * v2y - v1y * v2x;
1319
1320             if (dp <= 0)
1321                 continue;
1322         }
1323
1324         draw_polygon(fe, coords, poly->order, TRUE,
1325                      state->facecolours[i] ? COL_BLUE : COL_BACKGROUND);
1326         draw_polygon(fe, coords, poly->order, FALSE, COL_BORDER);
1327     }
1328     sfree(poly);
1329
1330     draw_update(fe, 0, 0, (int)((bb.r-bb.l+2.0F) * GRID_SCALE),
1331                 (int)((bb.d-bb.u+2.0F) * GRID_SCALE));
1332 }
1333
1334 float game_anim_length(game_state *oldstate, game_state *newstate)
1335 {
1336     return ROLLTIME;
1337 }
1338
1339 float game_flash_length(game_state *oldstate, game_state *newstate)
1340 {
1341     return 0.0F;
1342 }