summaryrefslogtreecommitdiff
path: root/apps/plugins/puzzles/untangle.c
blob: d46afcbe66536cb707bc0ce06d923f20953c2130 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
/*
 * untangle.c: Game about planar graphs. You are given a graph
 * represented by points and straight lines, with some lines
 * crossing; your task is to drag the points into a configuration
 * where none of the lines cross.
 * 
 * Cloned from a Flash game called `Planarity', by John Tantalo.
 * <http://home.cwru.edu/~jnt5/Planarity> at the time of writing
 * this. The Flash game had a fixed set of levels; my added value,
 * as usual, is automatic generation of random games to order.
 */

/*
 * TODO:
 *
 *  - This puzzle, perhaps uniquely among the collection, could use
 *    support for non-aspect-ratio-preserving resizes. This would
 *    require some sort of fairly large redesign, unfortunately (since
 *    it would invalidate the basic assumption that puzzles' size
 *    requirements are adequately expressed by a single scalar tile
 *    size), and probably complicate the rest of the puzzles' API as a
 *    result. So I'm not sure I really want to do it.
 *
 *  - It would be nice if we could somehow auto-detect a real `long
 *    long' type on the host platform and use it in place of my
 *    hand-hacked int64s. It'd be faster and more reliable.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rbassert.h"
#include <ctype.h>
#include <math.h>

#include "puzzles.h"
#include "tree234.h"

#define CIRCLE_RADIUS 6
#define DRAG_THRESHOLD (CIRCLE_RADIUS * 2)
#define PREFERRED_TILESIZE 64
#define CURSOR_GRANULARITY 5

#define FLASH_TIME 0.30F
#define ANIM_TIME 0.13F
#define SOLVEANIM_TIME 0.50F

enum {
    COL_SYSBACKGROUND,
    COL_BACKGROUND,
    COL_LINE,
#ifdef SHOW_CROSSINGS
    COL_CROSSEDLINE,
#endif
    COL_OUTLINE,
    COL_POINT,
    COL_DRAGPOINT,
    COL_CURSORPOINT,
    COL_NEIGHBOUR,
    COL_FLASH1,
    COL_FLASH2,
    NCOLOURS
};

typedef struct point {
    /*
     * Points are stored using rational coordinates, with the same
     * denominator for both coordinates.
     */
    long x, y, d;
} point;

typedef struct edge {
    /*
     * This structure is implicitly associated with a particular
     * point set, so all it has to do is to store two point
     * indices. It is required to store them in the order (lower,
     * higher), i.e. a < b always.
     */
    int a, b;
} edge;

struct game_params {
    int n;			       /* number of points */
};

struct graph {
    int refcount;		       /* for deallocation */
    tree234 *edges;		       /* stores `edge' structures */
};

struct game_state {
    game_params params;
    int w, h;			       /* extent of coordinate system only */
    point *pts;
#ifdef SHOW_CROSSINGS
    int *crosses;		       /* mark edges which are crossed */
#endif
    struct graph *graph;
    int completed, cheated, just_solved;
};

static int edgecmpC(const void *av, const void *bv)
{
    const edge *a = (const edge *)av;
    const edge *b = (const edge *)bv;

    if (a->a < b->a)
	return -1;
    else if (a->a > b->a)
	return +1;
    else if (a->b < b->b)
	return -1;
    else if (a->b > b->b)
	return +1;
    return 0;
}

static int edgecmp(void *av, void *bv) { return edgecmpC(av, bv); }

static game_params *default_params(void)
{
    game_params *ret = snew(game_params);

    ret->n = 10;

    return ret;
}

static int game_fetch_preset(int i, char **name, game_params **params)
{
    game_params *ret;
    int n;
    char buf[80];

    switch (i) {
      case 0: n = 6; break;
      case 1: n = 10; break;
      case 2: n = 15; break;
      case 3: n = 20; break;
      case 4: n = 25; break;
      default: return FALSE;
    }

    sprintf(buf, "%d points", n);
    *name = dupstr(buf);

    *params = ret = snew(game_params);
    ret->n = n;

    return TRUE;
}

static void free_params(game_params *params)
{
    sfree(params);
}

static game_params *dup_params(const game_params *params)
{
    game_params *ret = snew(game_params);
    *ret = *params;		       /* structure copy */
    return ret;
}

static void decode_params(game_params *params, char const *string)
{
    params->n = atoi(string);
}

static char *encode_params(const game_params *params, int full)
{
    char buf[80];

    sprintf(buf, "%d", params->n);

    return dupstr(buf);
}

static config_item *game_configure(const game_params *params)
{
    config_item *ret;
    char buf[80];

    ret = snewn(3, config_item);

    ret[0].name = "Number of points";
    ret[0].type = C_STRING;
    sprintf(buf, "%d", params->n);
    ret[0].sval = dupstr(buf);
    ret[0].ival = 0;

    ret[1].name = NULL;
    ret[1].type = C_END;
    ret[1].sval = NULL;
    ret[1].ival = 0;

    return ret;
}

static game_params *custom_params(const config_item *cfg)
{
    game_params *ret = snew(game_params);

    ret->n = atoi(cfg[0].sval);

    return ret;
}

static char *validate_params(const game_params *params, int full)
{
    if (params->n < 4)
        return "Number of points must be at least four";
    return NULL;
}

/* ----------------------------------------------------------------------
 * Small number of 64-bit integer arithmetic operations, to prevent
 * integer overflow at the very core of cross().
 */

typedef struct {
    long hi;
    unsigned long lo;
} int64;

#define greater64(i,j) ( (i).hi>(j).hi || ((i).hi==(j).hi && (i).lo>(j).lo))
#define sign64(i) ((i).hi < 0 ? -1 : (i).hi==0 && (i).lo==0 ? 0 : +1)

static int64 mulu32to64(unsigned long x, unsigned long y)
{
    unsigned long a, b, c, d, t;
    int64 ret;

    a = (x & 0xFFFF) * (y & 0xFFFF);
    b = (x & 0xFFFF) * (y >> 16);
    c = (x >> 16) * (y & 0xFFFF);
    d = (x >> 16) * (y >> 16);

    ret.lo = a;
    ret.hi = d + (b >> 16) + (c >> 16);
    t = (b & 0xFFFF) << 16;
    ret.lo += t;
    if (ret.lo < t)
	ret.hi++;
    t = (c & 0xFFFF) << 16;
    ret.lo += t;
    if (ret.lo < t)
	ret.hi++;

#ifdef DIAGNOSTIC_VIA_LONGLONG
    assert(((unsigned long long)ret.hi << 32) + ret.lo ==
	   (unsigned long long)x * y);
#endif

    return ret;
}

static int64 mul32to64(long x, long y)
{
    int sign = +1;
    int64 ret;
#ifdef DIAGNOSTIC_VIA_LONGLONG
    long long realret = (long long)x * y;
#endif

    if (x < 0)
	x = -x, sign = -sign;
    if (y < 0)
	y = -y, sign = -sign;

    ret = mulu32to64(x, y);

    if (sign < 0) {
	ret.hi = -ret.hi;
	ret.lo = -ret.lo;
	if (ret.lo)
	    ret.hi--;
    }

#ifdef DIAGNOSTIC_VIA_LONGLONG
    assert(((unsigned long long)ret.hi << 32) + ret.lo == realret);
#endif

    return ret;
}

static int64 dotprod64(long a, long b, long p, long q)
{
    int64 ab, pq;

    ab = mul32to64(a, b);
    pq = mul32to64(p, q);
    ab.hi += pq.hi;
    ab.lo += pq.lo;
    if (ab.lo < pq.lo)
	ab.hi++;
    return ab;
}

/*
 * Determine whether the line segments between a1 and a2, and
 * between b1 and b2, intersect. We count it as an intersection if
 * any of the endpoints lies _on_ the other line.
 */
static int cross(point a1, point a2, point b1, point b2)
{
    long b1x, b1y, b2x, b2y, px, py;
    int64 d1, d2, d3;

    /*
     * The condition for crossing is that b1 and b2 are on opposite
     * sides of the line a1-a2, and vice versa. We determine this
     * by taking the dot product of b1-a1 with a vector
     * perpendicular to a2-a1, and similarly with b2-a1, and seeing
     * if they have different signs.
     */

    /*
     * Construct the vector b1-a1. We don't have to worry too much
     * about the denominator, because we're only going to check the
     * sign of this vector; we just need to get the numerator
     * right.
     */
    b1x = b1.x * a1.d - a1.x * b1.d;
    b1y = b1.y * a1.d - a1.y * b1.d;
    /* Now construct b2-a1, and a vector perpendicular to a2-a1,
     * in the same way. */
    b2x = b2.x * a1.d - a1.x * b2.d;
    b2y = b2.y * a1.d - a1.y * b2.d;
    px = a1.y * a2.d - a2.y * a1.d;
    py = a2.x * a1.d - a1.x * a2.d;
    /* Take the dot products. Here we resort to 64-bit arithmetic. */
    d1 = dotprod64(b1x, px, b1y, py);
    d2 = dotprod64(b2x, px, b2y, py);
    /* If they have the same non-zero sign, the lines do not cross. */
    if ((sign64(d1) > 0 && sign64(d2) > 0) ||
	(sign64(d1) < 0 && sign64(d2) < 0))
	return FALSE;

    /*
     * If the dot products are both exactly zero, then the two line
     * segments are collinear. At this point the intersection
     * condition becomes whether or not they overlap within their
     * line.
     */
    if (sign64(d1) == 0 && sign64(d2) == 0) {
	/* Construct the vector a2-a1. */
	px = a2.x * a1.d - a1.x * a2.d;
	py = a2.y * a1.d - a1.y * a2.d;
	/* Determine the dot products of b1-a1 and b2-a1 with this. */
	d1 = dotprod64(b1x, px, b1y, py);
	d2 = dotprod64(b2x, px, b2y, py);
	/* If they're both strictly negative, the lines do not cross. */
	if (sign64(d1) < 0 && sign64(d2) < 0)
	    return FALSE;
	/* Otherwise, take the dot product of a2-a1 with itself. If
	 * the other two dot products both exceed this, the lines do
	 * not cross. */
	d3 = dotprod64(px, px, py, py);
	if (greater64(d1, d3) && greater64(d2, d3))
	    return FALSE;
    }

    /*
     * We've eliminated the only important special case, and we
     * have determined that b1 and b2 are on opposite sides of the
     * line a1-a2. Now do the same thing the other way round and
     * we're done.
     */
    b1x = a1.x * b1.d - b1.x * a1.d;
    b1y = a1.y * b1.d - b1.y * a1.d;
    b2x = a2.x * b1.d - b1.x * a2.d;
    b2y = a2.y * b1.d - b1.y * a2.d;
    px = b1.y * b2.d - b2.y * b1.d;
    py = b2.x * b1.d - b1.x * b2.d;
    d1 = dotprod64(b1x, px, b1y, py);
    d2 = dotprod64(b2x, px, b2y, py);
    if ((sign64(d1) > 0 && sign64(d2) > 0) ||
	(sign64(d1) < 0 && sign64(d2) < 0))
	return FALSE;

    /*
     * The lines must cross.
     */
    return TRUE;
}

static unsigned long squarert(unsigned long n) {
    unsigned long d, a, b, di;

    d = n;
    a = 0;
    b = 1L << 30;		       /* largest available power of 4 */
    do {
        a >>= 1;
        di = 2*a + b;
        if (di <= d) {
            d -= di;
            a += b;
        }
        b >>= 2;
    } while (b);

    return a;
}

/*
 * Our solutions are arranged on a square grid big enough that n
 * points occupy about 1/POINTDENSITY of the grid.
 */
#define POINTDENSITY 3
#define MAXDEGREE 4
#define COORDLIMIT(n) squarert((n) * POINTDENSITY)

static void addedge(tree234 *edges, int a, int b)
{
    edge *e = snew(edge);

    assert(a != b);

    e->a = min(a, b);
    e->b = max(a, b);

    add234(edges, e);
}

static int isedge(tree234 *edges, int a, int b)
{
    edge e;

    assert(a != b);

    e.a = min(a, b);
    e.b = max(a, b);

    return find234(edges, &e, NULL) != NULL;
}

typedef struct vertex {
    int param;
    int vindex;
} vertex;

static int vertcmpC(const void *av, const void *bv)
{
    const vertex *a = (vertex *)av;
    const vertex *b = (vertex *)bv;

    if (a->param < b->param)
	return -1;
    else if (a->param > b->param)
	return +1;
    else if (a->vindex < b->vindex)
	return -1;
    else if (a->vindex > b->vindex)
	return +1;
    return 0;
}
static int vertcmp(void *av, void *bv) { return vertcmpC(av, bv); }

/*
 * Construct point coordinates for n points arranged in a circle,
 * within the bounding box (0,0) to (w,w).
 */
static void make_circle(point *pts, int n, int w)
{
    long d, r, c, i;

    /*
     * First, decide on a denominator. Although in principle it
     * would be nice to set this really high so as to finely
     * distinguish all the points on the circle, I'm going to set
     * it at a fixed size to prevent integer overflow problems.
     */
    d = PREFERRED_TILESIZE;

    /*
     * Leave a little space outside the circle.
     */
    c = d * w / 2;
    r = d * w * 3 / 7;

    /*
     * Place the points.
     */
    for (i = 0; i < n; i++) {
	double angle = i * 2 * PI / n;
	double x = r * sin(angle), y = - r * cos(angle);
	pts[i].x = (long)(c + x + 0.5);
	pts[i].y = (long)(c + y + 0.5);
	pts[i].d = d;
    }
}

static char *new_game_desc(const game_params *params, random_state *rs,
			   char **aux, int interactive)
{
    int n = params->n, i;
    long w, h, j, k, m;
    point *pts, *pts2;
    long *tmp;
    tree234 *edges, *vertices;
    edge *e, *e2;
    vertex *v, *vs, *vlist;
    char *ret;

    w = h = COORDLIMIT(n);

    /*
     * Choose n points from this grid.
     */
    pts = snewn(n, point);
    tmp = snewn(w*h, long);
    for (i = 0; i < w*h; i++)
	tmp[i] = i;
    shuffle(tmp, w*h, sizeof(*tmp), rs);
    for (i = 0; i < n; i++) {
	pts[i].x = tmp[i] % w;
	pts[i].y = tmp[i] / w;
	pts[i].d = 1;
    }
    sfree(tmp);

    /*
     * Now start adding edges between the points.
     * 
     * At all times, we attempt to add an edge to the lowest-degree
     * vertex we currently have, and we try the other vertices as
     * candidate second endpoints in order of distance from this
     * one. We stop as soon as we find an edge which
     * 
     *  (a) does not increase any vertex's degree beyond MAXDEGREE
     *  (b) does not cross any existing edges
     *  (c) does not intersect any actual point.
     */
    vs = snewn(n, vertex);
    vertices = newtree234(vertcmp);
    for (i = 0; i < n; i++) {
	v = vs + i;
	v->param = 0;		       /* in this tree, param is the degree */
	v->vindex = i;
	add234(vertices, v);
    }
    edges = newtree234(edgecmp);
    vlist = snewn(n, vertex);
    while (1) {
	int added = FALSE;

	for (i = 0; i < n; i++) {
	    v = index234(vertices, i);
	    j = v->vindex;

	    if (v->param >= MAXDEGREE)
		break;		       /* nothing left to add! */

	    /*
	     * Sort the other vertices into order of their distance
	     * from this one. Don't bother looking below i, because
	     * we've already tried those edges the other way round.
	     * Also here we rule out target vertices with too high
	     * a degree, and (of course) ones to which we already
	     * have an edge.
	     */
	    m = 0;
	    for (k = i+1; k < n; k++) {
		vertex *kv = index234(vertices, k);
		int ki = kv->vindex;
		int dx, dy;

		if (kv->param >= MAXDEGREE || isedge(edges, ki, j))
		    continue;

		vlist[m].vindex = ki;
		dx = pts[ki].x - pts[j].x;
		dy = pts[ki].y - pts[j].y;
		vlist[m].param = dx*dx + dy*dy;
		m++;
	    }

	    qsort(vlist, m, sizeof(*vlist), vertcmpC);

	    for (k = 0; k < m; k++) {
		int p;
		int ki = vlist[k].vindex;

		/*
		 * Check to see whether this edge intersects any
		 * existing edge or point.
		 */
		for (p = 0; p < n; p++)
		    if (p != ki && p != j && cross(pts[ki], pts[j],
						   pts[p], pts[p]))
			break;
		if (p < n)
		    continue;
		for (p = 0; (e = index234(edges, p)) != NULL; p++)
		    if (e->a != ki && e->a != j &&
			e->b != ki && e->b != j &&
			cross(pts[ki], pts[j], pts[e->a], pts[e->b]))
			break;
		if (e)
		    continue;

		/*
		 * We're done! Add this edge, modify the degrees of
		 * the two vertices involved, and break.
		 */
		addedge(edges, j, ki);
		added = TRUE;
		del234(vertices, vs+j);
		vs[j].param++;
		add234(vertices, vs+j);
		del234(vertices, vs+ki);
		vs[ki].param++;
		add234(vertices, vs+ki);
		break;
	    }

	    if (k < m)
		break;
	}

	if (!added)
	    break;		       /* we're done. */
    }

    /*
     * That's our graph. Now shuffle the points, making sure that
     * they come out with at least one crossed line when arranged
     * in a circle (so that the puzzle isn't immediately solved!).
     */
    tmp = snewn(n, long);
    for (i = 0; i < n; i++)
	tmp[i] = i;
    pts2 = snewn(n, point);
    make_circle(pts2, n, w);
    while (1) {
	shuffle(tmp, n, sizeof(*tmp), rs);
	for (i = 0; (e = index234(edges, i)) != NULL; i++) {
	    for (j = i+1; (e2 = index234(edges, j)) != NULL; j++) {
		if (e2->a == e->a || e2->a == e->b ||
		    e2->b == e->a || e2->b == e->b)
		    continue;
		if (cross(pts2[tmp[e2->a]], pts2[tmp[e2->b]],
			  pts2[tmp[e->a]], pts2[tmp[e->b]]))
		    break;
	    }
	    if (e2)
		break;
	}
	if (e)
	    break;		       /* we've found a crossing */
    }

    /*
     * We're done. Now encode the graph in a string format. Let's
     * use a comma-separated list of dash-separated vertex number
     * pairs, numbered from zero. We'll sort the list to prevent
     * side channels.
     */
    ret = NULL;
    {
	char *sep;
	char buf[80];
	int retlen;
	edge *ea;

	retlen = 0;
	m = count234(edges);
	ea = snewn(m, edge);
	for (i = 0; (e = index234(edges, i)) != NULL; i++) {
	    assert(i < m);
	    ea[i].a = min(tmp[e->a], tmp[e->b]);
	    ea[i].b = max(tmp[e->a], tmp[e->b]);
	    retlen += 1 + sprintf(buf, "%d-%d", ea[i].a, ea[i].b);
	}
	assert(i == m);
	qsort(ea, m, sizeof(*ea), edgecmpC);

	ret = snewn(retlen, char);
	sep = "";
	k = 0;

	for (i = 0; i < m; i++) {
	    k += sprintf(ret + k, "%s%d-%d", sep, ea[i].a, ea[i].b);
	    sep = ",";
	}
	assert(k < retlen);

	sfree(ea);
    }

    /*
     * Encode the solution we started with as an aux_info string.
     */
    {
	char buf[80];
	char *auxstr;
	int auxlen;

	auxlen = 2;		       /* leading 'S' and trailing '\0' */
	for (i = 0; i < n; i++) {
	    j = tmp[i];
	    pts2[j] = pts[i];
	    if (pts2[j].d & 1) {
		pts2[j].x *= 2;
		pts2[j].y *= 2;
		pts2[j].d *= 2;
	    }
	    pts2[j].x += pts2[j].d / 2;
	    pts2[j].y += pts2[j].d / 2;
	    auxlen += sprintf(buf, ";P%d:%ld,%ld/%ld", i,
			      pts2[j].x, pts2[j].y, pts2[j].d);
	}
	k = 0;
	auxstr = snewn(auxlen, char);
	auxstr[k++] = 'S';
	for (i = 0; i < n; i++)
	    k += sprintf(auxstr+k, ";P%d:%ld,%ld/%ld", i,
			 pts2[i].x, pts2[i].y, pts2[i].d);
	assert(k < auxlen);
	*aux = auxstr;
    }
    sfree(pts2);

    sfree(tmp);
    sfree(vlist);
    freetree234(vertices);
    sfree(vs);
    while ((e = delpos234(edges, 0)) != NULL)
	sfree(e);
    freetree234(edges);
    sfree(pts);

    return ret;
}

static char *validate_desc(const game_params *params, const char *desc)
{
    int a, b;

    while (*desc) {
	a = atoi(desc);
	if (a < 0 || a >= params->n)
	    return "Number out of range in game description";
	while (*desc && isdigit((unsigned char)*desc)) desc++;
	if (*desc != '-')
	    return "Expected '-' after number in game description";
	desc++;			       /* eat dash */
	b = atoi(desc);
	if (b < 0 || b >= params->n)
	    return "Number out of range in game description";
	while (*desc && isdigit((unsigned char)*desc)) desc++;
	if (*desc) {
	    if (*desc != ',')
		return "Expected ',' after number in game description";
	    desc++;		       /* eat comma */
	}
    }

    return NULL;
}

static void mark_crossings(game_state *state)
{
    int ok = TRUE;
    int i, j;
    edge *e, *e2;

#ifdef SHOW_CROSSINGS
    for (i = 0; (e = index234(state->graph->edges, i)) != NULL; i++)
	state->crosses[i] = FALSE;
#endif

    /*
     * Check correctness: for every pair of edges, see whether they
     * cross.
     */
    for (i = 0; (e = index234(state->graph->edges, i)) != NULL; i++) {
	for (j = i+1; (e2 = index234(state->graph->edges, j)) != NULL; j++) {
	    if (e2->a == e->a || e2->a == e->b ||
		e2->b == e->a || e2->b == e->b)
		continue;
	    if (cross(state->pts[e2->a], state->pts[e2->b],
		      state->pts[e->a], state->pts[e->b])) {
		ok = FALSE;
#ifdef SHOW_CROSSINGS
		state->crosses[i] = state->crosses[j] = TRUE;
#else
		goto done;	       /* multi-level break - sorry */
#endif
	    }
	}
    }

    /*
     * e == NULL if we've gone through all the edge pairs
     * without finding a crossing.
     */
#ifndef SHOW_CROSSINGS
    done:
#endif
    if (ok)
	state->completed = TRUE;
}

static game_state *new_game(midend *me, const game_params *params,
                            const char *desc)
{
    int n = params->n;
    game_state *state = snew(game_state);
    int a, b;

    state->params = *params;
    state->w = state->h = COORDLIMIT(n);
    state->pts = snewn(n, point);
    make_circle(state->pts, n, state->w);
    state->graph = snew(struct graph);
    state->graph->refcount = 1;
    state->graph->edges = newtree234(edgecmp);
    state->completed = state->cheated = state->just_solved = FALSE;

    while (*desc) {
	a = atoi(desc);
	assert(a >= 0 && a < params->n);
	while (*desc && isdigit((unsigned char)*desc)) desc++;
	assert(*desc == '-');
	desc++;			       /* eat dash */
	b = atoi(desc);
	assert(b >= 0 && b < params->n);
	while (*desc && isdigit((unsigned char)*desc)) desc++;
	if (*desc) {
	    assert(*desc == ',');
	    desc++;		       /* eat comma */
	}
	addedge(state->graph->edges, a, b);
    }

#ifdef SHOW_CROSSINGS
    state->crosses = snewn(count234(state->graph->edges), int);
    mark_crossings(state);	       /* sets up `crosses' and `completed' */
#endif

    return state;
}

static game_state *dup_game(const game_state *state)
{
    int n = state->params.n;
    game_state *ret = snew(game_state);

    ret->params = state->params;
    ret->w = state->w;
    ret->h = state->h;
    ret->pts = snewn(n, point);
    memcpy(ret->pts, state->pts, n * sizeof(point));
    ret->graph = state->graph;
    ret->graph->refcount++;
    ret->completed = state->completed;
    ret->cheated = state->cheated;
    ret->just_solved = state->just_solved;
#ifdef SHOW_CROSSINGS
    ret->crosses = snewn(count234(ret->graph->edges), int);
    memcpy(ret->crosses, state->crosses,
	   count234(ret->graph->edges) * sizeof(int));
#endif

    return ret;
}

static void free_game(game_state *state)
{
    if (--state->graph->refcount <= 0) {
	edge *e;
	while ((e = delpos234(state->graph->edges, 0)) != NULL)
	    sfree(e);
	freetree234(state->graph->edges);
	sfree(state->graph);
    }
    sfree(state->pts);
    sfree(state);
}

static char *solve_game(const game_state *state, const game_state *currstate,
                        const char *aux, char **error)
{
    int n = state->params.n;
    int matrix[4];
    point *pts;
    int i, j, besti;
    float bestd;
    char buf[80], *ret;
    int retlen, retsize;

    if (!aux) {
	*error = "Solution not known for this puzzle";
	return NULL;
    }

    /*
     * Decode the aux_info to get the original point positions.
     */
    pts = snewn(n, point);
    aux++;                             /* eat 'S' */
    for (i = 0; i < n; i++) {
        int p, k;
        long x, y, d;
	int ret = sscanf(aux, ";P%d:%ld,%ld/%ld%n", &p, &x, &y, &d, &k);
        if (ret != 4 || p != i) {
            *error = "Internal error: aux_info badly formatted";
            sfree(pts);
            return NULL;
        }
        pts[i].x = x;
        pts[i].y = y;
        pts[i].d = d;
        aux += k;
    }

    /*
     * Now go through eight possible symmetries of the point set.
     * For each one, work out the sum of the Euclidean distances
     * between the points' current positions and their new ones.
     * 
     * We're squaring distances here, which means we're at risk of
     * integer overflow. Fortunately, there's no real need to be
     * massively careful about rounding errors, since this is a
     * non-essential bit of the code; so I'll just work in floats
     * internally.
     */
    besti = -1;
    bestd = 0.0F;

    for (i = 0; i < 8; i++) {
        float d;

        matrix[0] = matrix[1] = matrix[2] = matrix[3] = 0;
        matrix[i & 1] = (i & 2) ? +1 : -1;
        matrix[3-(i&1)] = (i & 4) ? +1 : -1;

        d = 0.0F;
        for (j = 0; j < n; j++) {
            float px = (float)pts[j].x / pts[j].d;
            float py = (float)pts[j].y / pts[j].d;
            float sx = (float)currstate->pts[j].x / currstate->pts[j].d;
            float sy = (float)currstate->pts[j].y / currstate->pts[j].d;
            float cx = (float)currstate->w / 2;
            float cy = (float)currstate->h / 2;
            float ox, oy, dx, dy;

            px -= cx;
            py -= cy;

            ox = matrix[0] * px + matrix[1] * py;
            oy = matrix[2] * px + matrix[3] * py;

            ox += cx;
            oy += cy;

            dx = ox - sx;
            dy = oy - sy;

            d += dx*dx + dy*dy;
        }

        if (besti < 0 || bestd > d) {
            besti = i;
            bestd = d;
        }
    }

    assert(besti >= 0);

    /*
     * Now we know which symmetry is closest to the points' current
     * positions. Use it.
     */
    matrix[0] = matrix[1] = matrix[2] = matrix[3] = 0;
    matrix[besti & 1] = (besti & 2) ? +1 : -1;
    matrix[3-(besti&1)] = (besti & 4) ? +1 : -1;

    retsize = 256;
    ret = snewn(retsize, char);
    retlen = 0;
    ret[retlen++] = 'S';
    ret[retlen] = '\0';

    for (i = 0; i < n; i++) {
        float px = (float)pts[i].x / pts[i].d;
        float py = (float)pts[i].y / pts[i].d;
        float cx = (float)currstate->w / 2;
        float cy = (float)currstate->h / 2;
        float ox, oy;
        int extra;

        px -= cx;
        py -= cy;

        ox = matrix[0] * px + matrix[1] * py;
        oy = matrix[2] * px + matrix[3] * py;

        ox += cx;
        oy += cy;

        /*
         * Use a fixed denominator of 2, because we know the
         * original points were on an integer grid offset by 1/2.
         */
        pts[i].d = 2;
        ox *= pts[i].d;
        oy *= pts[i].d;
        pts[i].x = (long)(ox + 0.5F);
        pts[i].y = (long)(oy + 0.5F);

        extra = sprintf(buf, ";P%d:%ld,%ld/%ld", i,
                        pts[i].x, pts[i].y, pts[i].d);
        if (retlen + extra >= retsize) {
            retsize = retlen + extra + 256;
            ret = sresize(ret, retsize, char);
        }
        strcpy(ret + retlen, buf);
        retlen += extra;
    }

    sfree(pts);

    return ret;
}

static int game_can_format_as_text_now(const game_params *params)
{
    return TRUE;
}

static char *game_text_format(const game_state *state)
{
    return NULL;
}

struct game_ui {
    int dragpoint;		       /* point being dragged; -1 if none */

    int cursorpoint;                   /* point being highlighted, but
                                        * not dragged by the cursor,
                                        * again -1 if none */

    point newpoint;		       /* where it's been dragged to so far */
    int just_dragged;		       /* reset in game_changed_state */
    int just_moved;		       /* _set_ in game_changed_state */
    float anim_length;
};

static game_ui *new_ui(const game_state *state)
{
    game_ui *ui = snew(game_ui);
    ui->dragpoint = -1;
    ui->cursorpoint = -1;
    ui->just_moved = ui->just_dragged = FALSE;
    return ui;
}

static void free_ui(game_ui *ui)
{
    sfree(ui);
}

static char *encode_ui(const game_ui *ui)
{
    return NULL;
}

static void decode_ui(game_ui *ui, const char *encoding)
{
}

static void game_changed_state(game_ui *ui, const game_state *oldstate,
                               const game_state *newstate)
{
    ui->dragpoint = -1;
    ui->just_moved = ui->just_dragged;
    ui->just_dragged = FALSE;
}

struct game_drawstate {
    long tilesize;
    int bg, dragpoint, cursorpoint;
    long *x, *y;
};

static char *interpret_move(const game_state *state, game_ui *ui,
                            const game_drawstate *ds,
                            int x, int y, int button)
{
    int n = state->params.n;

    if (IS_MOUSE_DOWN(button)) {
	int i, best;
        long bestd;

	/*
	 * Begin drag. We drag the vertex _nearest_ to the pointer,
	 * just in case one is nearly on top of another and we want
	 * to drag the latter. However, we drag nothing at all if
	 * the nearest vertex is outside DRAG_THRESHOLD.
	 */
	best = -1;
	bestd = 0;

	for (i = 0; i < n; i++) {
	    long px = state->pts[i].x * ds->tilesize / state->pts[i].d;
	    long py = state->pts[i].y * ds->tilesize / state->pts[i].d;
	    long dx = px - x;
	    long dy = py - y;
	    long d = dx*dx + dy*dy;

	    if (best == -1 || bestd > d) {
		best = i;
		bestd = d;
	    }
	}

	if (bestd <= DRAG_THRESHOLD * DRAG_THRESHOLD) {
	    ui->dragpoint = best;
	    ui->newpoint.x = x;
	    ui->newpoint.y = y;
	    ui->newpoint.d = ds->tilesize;
	    return "";
	}

    } else if (IS_MOUSE_DRAG(button) && ui->dragpoint >= 0) {
	ui->newpoint.x = x;
	ui->newpoint.y = y;
	ui->newpoint.d = ds->tilesize;
	return "";
    } else if (IS_MOUSE_RELEASE(button) && ui->dragpoint >= 0) {
	int p = ui->dragpoint;
	char buf[80];

	ui->dragpoint = -1;	       /* terminate drag, no matter what */

	/*
	 * First, see if we're within range. The user can cancel a
	 * drag by dragging the point right off the window.
	 */
	if (ui->newpoint.x < 0 ||
            ui->newpoint.x >= (long)state->w*ui->newpoint.d ||
	    ui->newpoint.y < 0 ||
            ui->newpoint.y >= (long)state->h*ui->newpoint.d)
	    return "";

	/*
	 * We aren't cancelling the drag. Construct a move string
	 * indicating where this point is going to.
	 */
	sprintf(buf, "P%d:%ld,%ld/%ld", p,
		ui->newpoint.x, ui->newpoint.y, ui->newpoint.d);
	ui->just_dragged = TRUE;
	return dupstr(buf);
    }
    else if(IS_CURSOR_MOVE(button))
    {
        if(ui->dragpoint < 0)
        {
            /* We're selecting a point here. */
            /* Search all the points and find the closest one (2-D) in
             * the given direction. */
            int i, best;
            long bestd;

            if(ui->cursorpoint < 0)
            {
                ui->cursorpoint = 0;
            }

            /*
             * Begin drag. We drag the vertex _nearest_ to the pointer,
             * just in case one is nearly on top of another and we want
             * to drag the latter. However, we drag nothing at all if
             * the nearest vertex is outside DRAG_THRESHOLD.
             */
            best = -1;
            bestd = 0;

            for (i = 0; i < n; i++) {
                if(i == ui->cursorpoint)
                    continue;

                long px = state->pts[i].x * ds->tilesize / state->pts[i].d;
                long py = state->pts[i].y * ds->tilesize / state->pts[i].d;
                long dx = px - state->pts[ui->cursorpoint].x * ds->tilesize / state->pts[ui->cursorpoint].d;
                long dy = py - state->pts[ui->cursorpoint].y * ds->tilesize / state->pts[ui->cursorpoint].d;
                long d = dx*dx + dy*dy;

                /* Figure out if this point falls into a 90 degree
                 * range extending from the current point */

                float angle = atan2(-dy, dx); /* negate y to adjust for raster coordinates */

                /* offset to [0..2*PI] */
                if(angle < 0)
                    angle += 2*PI;

                int right_direction = FALSE;

                if((button == CURSOR_UP && (1*PI/4 <= angle && angle <= 3*PI/4))   ||
                   (button == CURSOR_LEFT && (3*PI/4 <= angle && angle <= 5*PI/4)) ||
                   (button == CURSOR_DOWN && (5*PI/4 <= angle && angle <= 7*PI/4)) ||
                   (button == CURSOR_RIGHT && (angle >= 7*PI/4 || angle <= 1*PI/4)))
                    right_direction = TRUE;

                if ((best == -1 || bestd > d) && right_direction) {
                    best = i;
                    bestd = d;
                }
            }

            if(best >= 0)
            {
                ui->cursorpoint = best;
                return "";
            }
        }
        else if(ui->dragpoint >= 0)
        {
            /* dragging */
            switch(button)
            {
            case CURSOR_UP:
                ui->newpoint.y -= ds->tilesize / CURSOR_GRANULARITY;
                return "";
            case CURSOR_DOWN:
                ui->newpoint.y += ds->tilesize / CURSOR_GRANULARITY;
                return "";
            case CURSOR_LEFT:
                ui->newpoint.x -= ds->tilesize / CURSOR_GRANULARITY;
                return "";
            case CURSOR_RIGHT:
                ui->newpoint.x += ds->tilesize / CURSOR_GRANULARITY;
                return "";
            default:
                break;
            }
        }
    }
    else if(IS_CURSOR_SELECT(button))
    {
        if(ui->dragpoint < 0 && ui->cursorpoint >= 0)
        {
            /* begin drag */
            ui->dragpoint = ui->cursorpoint;
            ui->cursorpoint = -1;
            ui->newpoint.x = state->pts[ui->dragpoint].x * ds->tilesize / state->pts[ui->dragpoint].d;
            ui->newpoint.y = state->pts[ui->dragpoint].y * ds->tilesize / state->pts[ui->dragpoint].d;
            ui->newpoint.d = ds->tilesize;
            return "";
        }
        else if(ui->dragpoint >= 0)
        {
            /* end drag */
            int p = ui->dragpoint;
            char buf[80];

            ui->cursorpoint = ui->dragpoint;
            ui->dragpoint = -1;	       /* terminate drag, no matter what */

            /*
             * First, see if we're within range. The user can cancel a
             * drag by dragging the point right off the window.
             */
            if (ui->newpoint.x < 0 ||
                ui->newpoint.x >= (long)state->w*ui->newpoint.d ||
                ui->newpoint.y < 0 ||
                ui->newpoint.y >= (long)state->h*ui->newpoint.d)
                return "";

            /*
             * We aren't cancelling the drag. Construct a move string
             * indicating where this point is going to.
             */
            sprintf(buf, "P%d:%ld,%ld/%ld", p,
                    ui->newpoint.x, ui->newpoint.y, ui->newpoint.d);
            ui->just_dragged = TRUE;
            return dupstr(buf);
        }
        else if(ui->cursorpoint < 0)
            ui->cursorpoint = 0;
    }

    return NULL;
}

static game_state *execute_move(const game_state *state, const char *move)
{
    int n = state->params.n;
    int p, k;
    long x, y, d;
    game_state *ret = dup_game(state);

    ret->just_solved = FALSE;

    while (*move) {
	if (*move == 'S') {
	    move++;
	    if (*move == ';') move++;
	    ret->cheated = ret->just_solved = TRUE;
	}
	if (*move == 'P' &&
	    sscanf(move+1, "%d:%ld,%ld/%ld%n", &p, &x, &y, &d, &k) == 4 &&
	    p >= 0 && p < n && d > 0) {
	    ret->pts[p].x = x;
	    ret->pts[p].y = y;
	    ret->pts[p].d = d;

	    move += k+1;
	    if (*move == ';') move++;
	} else {
	    free_game(ret);
	    return NULL;
	}
    }

    mark_crossings(ret);

    return ret;
}

/* ----------------------------------------------------------------------
 * Drawing routines.
 */

static void game_compute_size(const game_params *params, int tilesize,
                              int *x, int *y)
{
    *x = *y = COORDLIMIT(params->n) * tilesize;
}

static void game_set_size(drawing *dr, game_drawstate *ds,
                          const game_params *params, int tilesize)
{
    ds->tilesize = tilesize;
}

static float *game_colours(frontend *fe, int *ncolours)
{
    float *ret = snewn(3 * NCOLOURS, float);

    /*
     * COL_BACKGROUND is what we use as the normal background colour.
     * Unusually, though, it isn't colour #0: COL_SYSBACKGROUND, a bit
     * darker, takes that place. This means that if the user resizes
     * an Untangle window so as to change its aspect ratio, the
     * still-square playable area will be distinguished from the dead
     * space around it.
     */
    game_mkhighlight(fe, ret, COL_BACKGROUND, -1, COL_SYSBACKGROUND);

    ret[COL_LINE * 3 + 0] = 0.0F;
    ret[COL_LINE * 3 + 1] = 0.0F;
    ret[COL_LINE * 3 + 2] = 0.0F;

#ifdef SHOW_CROSSINGS
    ret[COL_CROSSEDLINE * 3 + 0] = 1.0F;
    ret[COL_CROSSEDLINE * 3 + 1] = 0.0F;
    ret[COL_CROSSEDLINE * 3 + 2] = 0.0F;
#endif

    ret[COL_OUTLINE * 3 + 0] = 0.0F;
    ret[COL_OUTLINE * 3 + 1] = 0.0F;
    ret[COL_OUTLINE * 3 + 2] = 0.0F;

    ret[COL_POINT * 3 + 0] = 0.0F;
    ret[COL_POINT * 3 + 1] = 0.0F;
    ret[COL_POINT * 3 + 2] = 1.0F;

    ret[COL_DRAGPOINT * 3 + 0] = 1.0F;
    ret[COL_DRAGPOINT * 3 + 1] = 1.0F;
    ret[COL_DRAGPOINT * 3 + 2] = 1.0F;

    ret[COL_CURSORPOINT * 3 + 0] = 0.5F;
    ret[COL_CURSORPOINT * 3 + 1] = 0.5F;
    ret[COL_CURSORPOINT * 3 + 2] = 0.5F;

    ret[COL_NEIGHBOUR * 3 + 0] = 1.0F;
    ret[COL_NEIGHBOUR * 3 + 1] = 0.0F;
    ret[COL_NEIGHBOUR * 3 + 2] = 0.0F;

    ret[COL_FLASH1 * 3 + 0] = 0.5F;
    ret[COL_FLASH1 * 3 + 1] = 0.5F;
    ret[COL_FLASH1 * 3 + 2] = 0.5F;

    ret[COL_FLASH2 * 3 + 0] = 1.0F;
    ret[COL_FLASH2 * 3 + 1] = 1.0F;
    ret[COL_FLASH2 * 3 + 2] = 1.0F;

    *ncolours = NCOLOURS;
    return ret;
}

static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
{
    struct game_drawstate *ds = snew(struct game_drawstate);
    int i;

    ds->tilesize = 0;
    ds->x = snewn(state->params.n, long);
    ds->y = snewn(state->params.n, long);
    for (i = 0; i < state->params.n; i++)
        ds->x[i] = ds->y[i] = -1;
    ds->bg = -1;
    ds->dragpoint = -1;
    ds->cursorpoint = -1;

    return ds;
}

static void game_free_drawstate(drawing *dr, game_drawstate *ds)
{
    sfree(ds->y);
    sfree(ds->x);
    sfree(ds);
}

static point mix(point a, point b, float distance)
{
    point ret;

    ret.d = a.d * b.d;
    ret.x = (long)(a.x * b.d + distance * (b.x * a.d - a.x * b.d));
    ret.y = (long)(a.y * b.d + distance * (b.y * a.d - a.y * b.d));

    return ret;
}

static void game_redraw(drawing *dr, game_drawstate *ds,
                        const game_state *oldstate, const game_state *state,
                        int dir, const game_ui *ui,
                        float animtime, float flashtime)
{
    int w, h;
    edge *e;
    int i, j;
    int bg, points_moved;

    /*
     * There's no terribly sensible way to do partial redraws of
     * this game, so I'm going to have to resort to redrawing the
     * whole thing every time.
     */

    if (flashtime == 0)
        bg = COL_BACKGROUND;
    else if ((int)(flashtime * 4 / FLASH_TIME) % 2 == 0)
        bg = COL_FLASH1;
    else
        bg = COL_FLASH2;

    /*
     * To prevent excessive spinning on redraw during a completion
     * flash, we first check to see if _either_ the flash
     * background colour has changed _or_ at least one point has
     * moved _or_ a drag has begun or ended, and abandon the redraw
     * if neither is the case.
     * 
     * Also in this loop we work out the coordinates of all the
     * points for this redraw.
     */
    points_moved = FALSE;
    for (i = 0; i < state->params.n; i++) {
        point p = state->pts[i];
        long x, y;

        if (ui->dragpoint == i)
            p = ui->newpoint;

        if (oldstate)
            p = mix(oldstate->pts[i], p, animtime / ui->anim_length);

	x = p.x * ds->tilesize / p.d;
	y = p.y * ds->tilesize / p.d;

        if (ds->x[i] != x || ds->y[i] != y)
            points_moved = TRUE;

        ds->x[i] = x;
        ds->y[i] = y;
    }

    if (ds->bg == bg && ds->dragpoint == ui->dragpoint && ds->cursorpoint == ui->cursorpoint && !points_moved)
        return;                        /* nothing to do */

    ds->dragpoint = ui->dragpoint;
    ds->bg = bg;

    game_compute_size(&state->params, ds->tilesize, &w, &h);

    clip(dr, 0, 0, w, h);
    draw_rect(dr, 0, 0, w, h, bg);

    /*
     * Draw the edges.
     */

    for (i = 0; (e = index234(state->graph->edges, i)) != NULL; i++) {
	draw_line(dr, ds->x[e->a], ds->y[e->a], ds->x[e->b], ds->y[e->b],
#ifdef SHOW_CROSSINGS
		  (oldstate?oldstate:state)->crosses[i] ?
		  COL_CROSSEDLINE :
#endif
		  COL_LINE);
    }

    /*
     * Draw the points.
     * 
     * When dragging, we should not only vary the colours, but
     * leave the point being dragged until last.
     */
    for (j = 0; j < 4; j++) {
	int thisc = (j == 0 ? COL_POINT :
		     (j == 1 ? COL_NEIGHBOUR :
                      j == 2 ? COL_CURSORPOINT : COL_DRAGPOINT));
	for (i = 0; i < state->params.n; i++) {
            int c;

	    if (ui->dragpoint == i) {
		c = COL_DRAGPOINT;
	    } else if(ui->cursorpoint == i) {
                c = COL_CURSORPOINT;
            } else if (ui->dragpoint >= 0 &&
		       isedge(state->graph->edges, ui->dragpoint, i)) {
		c = COL_NEIGHBOUR;
	    } else {
		c = COL_POINT;
	    }

	    if (c == thisc) {
#ifdef VERTEX_NUMBERS
		draw_circle(dr, ds->x[i], ds->y[i], DRAG_THRESHOLD, bg, bg);
		{
		    char buf[80];
		    sprintf(buf, "%d", i);
		    draw_text(dr, ds->x[i], ds->y[i], FONT_VARIABLE,
                              DRAG_THRESHOLD*3/2,
			      ALIGN_VCENTRE|ALIGN_HCENTRE, c, buf);
		}
#else
		draw_circle(dr, ds->x[i], ds->y[i], CIRCLE_RADIUS,
                            c, COL_OUTLINE);
#endif
	    }
	}
    }

    draw_update(dr, 0, 0, w, h);
}

static float game_anim_length(const game_state *oldstate,
                              const game_state *newstate, int dir, game_ui *ui)
{
    if (ui->just_moved)
	return 0.0F;
    if ((dir < 0 ? oldstate : newstate)->just_solved)
	ui->anim_length = SOLVEANIM_TIME;
    else
	ui->anim_length = ANIM_TIME;
    return ui->anim_length;
}

static float game_flash_length(const game_state *oldstate,
                               const game_state *newstate, int dir, game_ui *ui)
{
    if (!oldstate->completed && newstate->completed &&
	!oldstate->cheated && !newstate->cheated)
        return FLASH_TIME;
    return 0.0F;
}

static int game_status(const game_state *state)
{
    return state->completed ? +1 : 0;
}

static int game_timing_state(const game_state *state, game_ui *ui)
{
    return TRUE;
}

static void game_print_size(const game_params *params, float *x, float *y)
{
}

static void game_print(drawing *dr, const game_state *state, int tilesize)
{
}

#ifdef COMBINED
#define thegame untangle
#endif

const struct game thegame = {
    "Untangle", "games.untangle", "untangle",
    default_params,
    game_fetch_preset,
    decode_params,
    encode_params,
    free_params,
    dup_params,
    TRUE, game_configure, custom_params,
    validate_params,
    new_game_desc,
    validate_desc,
    new_game,
    dup_game,
    free_game,
    TRUE, solve_game,
    FALSE, game_can_format_as_text_now, game_text_format,
    new_ui,
    free_ui,
    encode_ui,
    decode_ui,
    game_changed_state,
    interpret_move,
    execute_move,
    PREFERRED_TILESIZE, game_compute_size, game_set_size,
    game_colours,
    game_new_drawstate,
    game_free_drawstate,
    game_redraw,
    game_anim_length,
    game_flash_length,
    game_status,
    FALSE, FALSE, game_print_size, game_print,
    FALSE,			       /* wants_statusbar */
    FALSE, game_timing_state,
    SOLVE_ANIMATES,		       /* flags */
};