-
Notifications
You must be signed in to change notification settings - Fork 6
/
grid.c
3261 lines (2846 loc) · 120 KB
/
grid.c
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
/*
* (c) Lambros Lambrou 2008
*
* Code for working with general grids, which can be any planar graph
* with faces, edges and vertices (dots). Includes generators for a few
* types of grid, including square, hexagonal, triangular and others.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <float.h>
#include "puzzles.h"
#include "tree234.h"
#include "grid.h"
#include "penrose.h"
/* Debugging options */
/*
#define DEBUG_GRID
*/
/* ----------------------------------------------------------------------
* Deallocate or dereference a grid
*/
void grid_free(grid *g)
{
assert(g->refcount);
g->refcount--;
if (g->refcount == 0) {
int i;
for (i = 0; i < g->num_faces; i++) {
sfree(g->faces[i].dots);
sfree(g->faces[i].edges);
}
for (i = 0; i < g->num_dots; i++) {
sfree(g->dots[i].faces);
sfree(g->dots[i].edges);
}
sfree(g->faces);
sfree(g->edges);
sfree(g->dots);
sfree(g);
}
}
/* Used by the other grid generators. Create a brand new grid with nothing
* initialised (all lists are NULL) */
static grid *grid_empty(void)
{
grid *g = snew(grid);
g->faces = NULL;
g->edges = NULL;
g->dots = NULL;
g->num_faces = g->num_edges = g->num_dots = 0;
g->refcount = 1;
g->lowest_x = g->lowest_y = g->highest_x = g->highest_y = 0;
return g;
}
/* Helper function to calculate perpendicular distance from
* a point P to a line AB. A and B mustn't be equal here.
*
* Well-known formula for area A of a triangle:
* / 1 1 1 \
* 2A = determinant of matrix | px ax bx |
* \ py ay by /
*
* Also well-known: 2A = base * height
* = perpendicular distance * line-length.
*
* Combining gives: distance = determinant / line-length(a,b)
*/
static double point_line_distance(long px, long py,
long ax, long ay,
long bx, long by)
{
long det = ax*by - bx*ay + bx*py - px*by + px*ay - ax*py;
double len;
det = max(det, -det);
len = sqrt(SQ(ax - bx) + SQ(ay - by));
return det / len;
}
/* Determine nearest edge to where the user clicked.
* (x, y) is the clicked location, converted to grid coordinates.
* Returns the nearest edge, or NULL if no edge is reasonably
* near the position.
*
* Just judging edges by perpendicular distance is not quite right -
* the edge might be "off to one side". So we insist that the triangle
* with (x,y) has acute angles at the edge's dots.
*
* edge1
* *---------*------
* |
* | *(x,y)
* edge2 |
* | edge2 is OK, but edge1 is not, even though
* | edge1 is perpendicularly closer to (x,y)
* *
*
*/
grid_edge *grid_nearest_edge(grid *g, int x, int y)
{
grid_edge *best_edge;
double best_distance = 0;
int i;
best_edge = NULL;
for (i = 0; i < g->num_edges; i++) {
grid_edge *e = &g->edges[i];
long e2; /* squared length of edge */
long a2, b2; /* squared lengths of other sides */
double dist;
/* See if edge e is eligible - the triangle must have acute angles
* at the edge's dots.
* Pythagoras formula h^2 = a^2 + b^2 detects right-angles,
* so detect acute angles by testing for h^2 < a^2 + b^2 */
e2 = SQ((long)e->dot1->x - (long)e->dot2->x) + SQ((long)e->dot1->y - (long)e->dot2->y);
a2 = SQ((long)e->dot1->x - (long)x) + SQ((long)e->dot1->y - (long)y);
b2 = SQ((long)e->dot2->x - (long)x) + SQ((long)e->dot2->y - (long)y);
if (a2 >= e2 + b2) continue;
if (b2 >= e2 + a2) continue;
/* e is eligible so far. Now check the edge is reasonably close
* to where the user clicked. Don't want to toggle an edge if the
* click was way off the grid.
* There is room for experimentation here. We could check the
* perpendicular distance is within a certain fraction of the length
* of the edge. That amounts to testing a rectangular region around
* the edge.
* Alternatively, we could check that the angle at the point is obtuse.
* That would amount to testing a circular region with the edge as
* diameter. */
dist = point_line_distance((long)x, (long)y,
(long)e->dot1->x, (long)e->dot1->y,
(long)e->dot2->x, (long)e->dot2->y);
/* Is dist more than half edge length ? */
if (4 * SQ(dist) > e2)
continue;
if (best_edge == NULL || dist < best_distance) {
best_edge = e;
best_distance = dist;
}
}
return best_edge;
}
/* ----------------------------------------------------------------------
* Grid generation
*/
#ifdef SVG_GRID
#define SVG_DOTS 1
#define SVG_EDGES 2
#define SVG_FACES 4
#define FACE_COLOUR "red"
#define EDGE_COLOUR "blue"
#define DOT_COLOUR "black"
static void grid_output_svg(FILE *fp, grid *g, int which)
{
int i, j;
fprintf(fp,"\
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n\
<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 20010904//EN\"\n\
\"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n\
\n\
<svg xmlns=\"http://www.w3.org/2000/svg\"\n\
xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n\n");
if (which & SVG_FACES) {
fprintf(fp, "<g>\n");
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
fprintf(fp, "<polygon points=\"");
for (j = 0; j < f->order; j++) {
grid_dot *d = f->dots[j];
fprintf(fp, "%s%d,%d", (j == 0) ? "" : " ",
d->x, d->y);
}
fprintf(fp, "\" style=\"fill: %s; fill-opacity: 0.2; stroke: %s\" />\n",
FACE_COLOUR, FACE_COLOUR);
}
fprintf(fp, "</g>\n");
}
if (which & SVG_EDGES) {
fprintf(fp, "<g>\n");
for (i = 0; i < g->num_edges; i++) {
grid_edge *e = g->edges + i;
grid_dot *d1 = e->dot1, *d2 = e->dot2;
fprintf(fp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" "
"style=\"stroke: %s\" />\n",
d1->x, d1->y, d2->x, d2->y, EDGE_COLOUR);
}
fprintf(fp, "</g>\n");
}
if (which & SVG_DOTS) {
fprintf(fp, "<g>\n");
for (i = 0; i < g->num_dots; i++) {
grid_dot *d = g->dots + i;
fprintf(fp, "<ellipse cx=\"%d\" cy=\"%d\" rx=\"%d\" ry=\"%d\" fill=\"%s\" />",
d->x, d->y, g->tilesize/20, g->tilesize/20, DOT_COLOUR);
}
fprintf(fp, "</g>\n");
}
fprintf(fp, "</svg>\n");
}
#endif
#ifdef SVG_GRID
#include <errno.h>
static void grid_try_svg(grid *g, int which)
{
char *svg = getenv("PUZZLES_SVG_GRID");
if (svg) {
FILE *svgf = fopen(svg, "w");
if (svgf) {
grid_output_svg(svgf, g, which);
fclose(svgf);
} else {
fprintf(stderr, "Unable to open file `%s': %s", svg, strerror(errno));
}
}
}
#endif
/* Show the basic grid information, before doing grid_make_consistent */
static void grid_debug_basic(grid *g)
{
/* TODO: Maybe we should generate an SVG image of the dots and lines
* of the grid here, before grid_make_consistent.
* Would help with debugging grid generation. */
#ifdef DEBUG_GRID
int i;
printf("--- Basic Grid Data ---\n");
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
printf("Face %d: dots[", i);
int j;
for (j = 0; j < f->order; j++) {
grid_dot *d = f->dots[j];
printf("%s%d", j ? "," : "", (int)(d - g->dots));
}
printf("]\n");
}
#endif
#ifdef SVG_GRID
grid_try_svg(g, SVG_FACES);
#endif
}
/* Show the derived grid information, computed by grid_make_consistent */
static void grid_debug_derived(grid *g)
{
#ifdef DEBUG_GRID
/* edges */
int i;
printf("--- Derived Grid Data ---\n");
for (i = 0; i < g->num_edges; i++) {
grid_edge *e = g->edges + i;
printf("Edge %d: dots[%d,%d] faces[%d,%d]\n",
i, (int)(e->dot1 - g->dots), (int)(e->dot2 - g->dots),
e->face1 ? (int)(e->face1 - g->faces) : -1,
e->face2 ? (int)(e->face2 - g->faces) : -1);
}
/* faces */
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
int j;
printf("Face %d: faces[", i);
for (j = 0; j < f->order; j++) {
grid_edge *e = f->edges[j];
grid_face *f2 = (e->face1 == f) ? e->face2 : e->face1;
printf("%s%d", j ? "," : "", f2 ? (int)(f2 - g->faces) : -1);
}
printf("]\n");
}
/* dots */
for (i = 0; i < g->num_dots; i++) {
grid_dot *d = g->dots + i;
int j;
printf("Dot %d: dots[", i);
for (j = 0; j < d->order; j++) {
grid_edge *e = d->edges[j];
grid_dot *d2 = (e->dot1 == d) ? e->dot2 : e->dot1;
printf("%s%d", j ? "," : "", (int)(d2 - g->dots));
}
printf("] faces[");
for (j = 0; j < d->order; j++) {
grid_face *f = d->faces[j];
printf("%s%d", j ? "," : "", f ? (int)(f - g->faces) : -1);
}
printf("]\n");
}
#endif
#ifdef SVG_GRID
grid_try_svg(g, SVG_DOTS | SVG_EDGES | SVG_FACES);
#endif
}
/* Helper function for building incomplete-edges list in
* grid_make_consistent() */
static int grid_edge_bydots_cmpfn(void *v1, void *v2)
{
grid_edge *a = v1;
grid_edge *b = v2;
grid_dot *da, *db;
/* Pointer subtraction is valid here, because all dots point into the
* same dot-list (g->dots).
* Edges are not "normalised" - the 2 dots could be stored in any order,
* so we need to take this into account when comparing edges. */
/* Compare first dots */
da = (a->dot1 < a->dot2) ? a->dot1 : a->dot2;
db = (b->dot1 < b->dot2) ? b->dot1 : b->dot2;
if (da != db)
return db - da;
/* Compare last dots */
da = (a->dot1 < a->dot2) ? a->dot2 : a->dot1;
db = (b->dot1 < b->dot2) ? b->dot2 : b->dot1;
if (da != db)
return db - da;
return 0;
}
/*
* 'Vigorously trim' a grid, by which I mean deleting any isolated or
* uninteresting faces. By which, in turn, I mean: ensure that the
* grid is composed solely of faces adjacent to at least one
* 'landlocked' dot (i.e. one not in contact with the infinite
* exterior face), and that all those dots are in a single connected
* component.
*
* This function operates on, and returns, a grid satisfying the
* preconditions to grid_make_consistent() rather than the
* postconditions. (So call it first.)
*/
static void grid_trim_vigorously(grid *g)
{
int *dotpairs, *faces, *dots;
int *dsf;
int i, j, k, size, newfaces, newdots;
/*
* First construct a matrix in which each ordered pair of dots is
* mapped to the index of the face in which those dots occur in
* that order.
*/
dotpairs = snewn(g->num_dots * g->num_dots, int);
for (i = 0; i < g->num_dots; i++)
for (j = 0; j < g->num_dots; j++)
dotpairs[i*g->num_dots+j] = -1;
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
int dot0 = f->dots[f->order-1] - g->dots;
for (j = 0; j < f->order; j++) {
int dot1 = f->dots[j] - g->dots;
dotpairs[dot0 * g->num_dots + dot1] = i;
dot0 = dot1;
}
}
/*
* Now we can identify landlocked dots: they're the ones all of
* whose edges have a mirror-image counterpart in this matrix.
*/
dots = snewn(g->num_dots, int);
for (i = 0; i < g->num_dots; i++) {
dots[i] = 1;
for (j = 0; j < g->num_dots; j++) {
if ((dotpairs[i*g->num_dots+j] >= 0) ^
(dotpairs[j*g->num_dots+i] >= 0))
dots[i] = 0; /* non-duplicated edge: coastal dot */
}
}
/*
* Now identify connected pairs of landlocked dots, and form a dsf
* unifying them.
*/
dsf = snew_dsf(g->num_dots);
for (i = 0; i < g->num_dots; i++)
for (j = 0; j < i; j++)
if (dots[i] && dots[j] &&
dotpairs[i*g->num_dots+j] >= 0 &&
dotpairs[j*g->num_dots+i] >= 0)
dsf_merge(dsf, i, j);
/*
* Now look for the largest component.
*/
size = 0;
j = -1;
for (i = 0; i < g->num_dots; i++) {
int newsize;
if (dots[i] && dsf_canonify(dsf, i) == i &&
(newsize = dsf_size(dsf, i)) > size) {
j = i;
size = newsize;
}
}
/*
* Work out which faces we're going to keep (precisely those with
* at least one dot in the same connected component as j) and
* which dots (those required by any face we're keeping).
*
* At this point we reuse the 'dots' array to indicate the dots
* we're keeping, rather than the ones that are landlocked.
*/
faces = snewn(g->num_faces, int);
for (i = 0; i < g->num_faces; i++)
faces[i] = 0;
for (i = 0; i < g->num_dots; i++)
dots[i] = 0;
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
bool keep = false;
for (k = 0; k < f->order; k++)
if (dsf_canonify(dsf, f->dots[k] - g->dots) == j)
keep = true;
if (keep) {
faces[i] = 1;
for (k = 0; k < f->order; k++)
dots[f->dots[k]-g->dots] = 1;
}
}
/*
* Work out the new indices of those faces and dots, when we
* compact the arrays containing them.
*/
for (i = newfaces = 0; i < g->num_faces; i++)
faces[i] = (faces[i] ? newfaces++ : -1);
for (i = newdots = 0; i < g->num_dots; i++)
dots[i] = (dots[i] ? newdots++ : -1);
/*
* Free the dynamically allocated 'dots' pointer lists in faces
* we're going to discard.
*/
for (i = 0; i < g->num_faces; i++)
if (faces[i] < 0)
sfree(g->faces[i].dots);
/*
* Go through and compact the arrays.
*/
for (i = 0; i < g->num_dots; i++)
if (dots[i] >= 0) {
grid_dot *dnew = g->dots + dots[i], *dold = g->dots + i;
*dnew = *dold; /* structure copy */
}
for (i = 0; i < g->num_faces; i++)
if (faces[i] >= 0) {
grid_face *fnew = g->faces + faces[i], *fold = g->faces + i;
*fnew = *fold; /* structure copy */
for (j = 0; j < fnew->order; j++) {
/*
* Reindex the dots in this face.
*/
k = fnew->dots[j] - g->dots;
fnew->dots[j] = g->dots + dots[k];
}
}
g->num_faces = newfaces;
g->num_dots = newdots;
sfree(dotpairs);
sfree(dsf);
sfree(dots);
sfree(faces);
}
/* Input: grid has its dots and faces initialised:
* - dots have (optionally) x and y coordinates, but no edges or faces
* (pointers are NULL).
* - edges not initialised at all
* - faces initialised and know which dots they have (but no edges yet). The
* dots around each face are assumed to be clockwise.
*
* Output: grid is complete and valid with all relationships defined.
*/
static void grid_make_consistent(grid *g)
{
int i;
tree234 *incomplete_edges;
grid_edge *next_new_edge; /* Where new edge will go into g->edges */
grid_debug_basic(g);
/* ====== Stage 1 ======
* Generate edges
*/
/* We know how many dots and faces there are, so we can find the exact
* number of edges from Euler's polyhedral formula: F + V = E + 2 .
* We use "-1", not "-2" here, because Euler's formula includes the
* infinite face, which we don't count. */
g->num_edges = g->num_faces + g->num_dots - 1;
g->edges = snewn(g->num_edges, grid_edge);
next_new_edge = g->edges;
/* Iterate over faces, and over each face's dots, generating edges as we
* go. As we find each new edge, we can immediately fill in the edge's
* dots, but only one of the edge's faces. Later on in the iteration, we
* will find the same edge again (unless it's on the border), but we will
* know the other face.
* For efficiency, maintain a list of the incomplete edges, sorted by
* their dots. */
incomplete_edges = newtree234(grid_edge_bydots_cmpfn);
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
int j;
for (j = 0; j < f->order; j++) {
grid_edge e; /* fake edge for searching */
grid_edge *edge_found;
int j2 = j + 1;
if (j2 == f->order)
j2 = 0;
e.dot1 = f->dots[j];
e.dot2 = f->dots[j2];
/* Use del234 instead of find234, because we always want to
* remove the edge if found */
edge_found = del234(incomplete_edges, &e);
if (edge_found) {
/* This edge already added, so fill out missing face.
* Edge is already removed from incomplete_edges. */
edge_found->face2 = f;
} else {
assert(next_new_edge - g->edges < g->num_edges);
next_new_edge->dot1 = e.dot1;
next_new_edge->dot2 = e.dot2;
next_new_edge->face1 = f;
next_new_edge->face2 = NULL; /* potentially infinite face */
add234(incomplete_edges, next_new_edge);
++next_new_edge;
}
}
}
freetree234(incomplete_edges);
/* ====== Stage 2 ======
* For each face, build its edge list.
*/
/* Allocate space for each edge list. Can do this, because each face's
* edge-list is the same size as its dot-list. */
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
int j;
f->edges = snewn(f->order, grid_edge*);
/* Preload with NULLs, to help detect potential bugs. */
for (j = 0; j < f->order; j++)
f->edges[j] = NULL;
}
/* Iterate over each edge, and over both its faces. Add this edge to
* the face's edge-list, after finding where it should go in the
* sequence. */
for (i = 0; i < g->num_edges; i++) {
grid_edge *e = g->edges + i;
int j;
for (j = 0; j < 2; j++) {
grid_face *f = j ? e->face2 : e->face1;
int k, k2;
if (f == NULL) continue;
/* Find one of the dots around the face */
for (k = 0; k < f->order; k++) {
if (f->dots[k] == e->dot1)
break; /* found dot1 */
}
assert(k != f->order); /* Must find the dot around this face */
/* Labelling scheme: as we walk clockwise around the face,
* starting at dot0 (f->dots[0]), we hit:
* (dot0), edge0, dot1, edge1, dot2,...
*
* 0
* 0-----1
* |
* |1
* |
* 3-----2
* 2
*
* Therefore, edgeK joins dotK and dot{K+1}
*/
/* Around this face, either the next dot or the previous dot
* must be e->dot2. Otherwise the edge is wrong. */
k2 = k + 1;
if (k2 == f->order)
k2 = 0;
if (f->dots[k2] == e->dot2) {
/* dot1(k) and dot2(k2) go clockwise around this face, so add
* this edge at position k (see diagram). */
assert(f->edges[k] == NULL);
f->edges[k] = e;
continue;
}
/* Try previous dot */
k2 = k - 1;
if (k2 == -1)
k2 = f->order - 1;
if (f->dots[k2] == e->dot2) {
/* dot1(k) and dot2(k2) go anticlockwise around this face. */
assert(f->edges[k2] == NULL);
f->edges[k2] = e;
continue;
}
assert(!"Grid broken: bad edge-face relationship");
}
}
/* ====== Stage 3 ======
* For each dot, build its edge-list and face-list.
*/
/* We don't know how many edges/faces go around each dot, so we can't
* allocate the right space for these lists. Pre-compute the sizes by
* iterating over each edge and recording a tally against each dot. */
for (i = 0; i < g->num_dots; i++) {
g->dots[i].order = 0;
}
for (i = 0; i < g->num_edges; i++) {
grid_edge *e = g->edges + i;
++(e->dot1->order);
++(e->dot2->order);
}
/* Now we have the sizes, pre-allocate the edge and face lists. */
for (i = 0; i < g->num_dots; i++) {
grid_dot *d = g->dots + i;
int j;
assert(d->order >= 2); /* sanity check */
d->edges = snewn(d->order, grid_edge*);
d->faces = snewn(d->order, grid_face*);
for (j = 0; j < d->order; j++) {
d->edges[j] = NULL;
d->faces[j] = NULL;
}
}
/* For each dot, need to find a face that touches it, so we can seed
* the edge-face-edge-face process around each dot. */
for (i = 0; i < g->num_faces; i++) {
grid_face *f = g->faces + i;
int j;
for (j = 0; j < f->order; j++) {
grid_dot *d = f->dots[j];
d->faces[0] = f;
}
}
/* Each dot now has a face in its first slot. Generate the remaining
* faces and edges around the dot, by searching both clockwise and
* anticlockwise from the first face. Need to do both directions,
* because of the possibility of hitting the infinite face, which
* blocks progress. But there's only one such face, so we will
* succeed in finding every edge and face this way. */
for (i = 0; i < g->num_dots; i++) {
grid_dot *d = g->dots + i;
int current_face1 = 0; /* ascends clockwise */
int current_face2 = 0; /* descends anticlockwise */
/* Labelling scheme: as we walk clockwise around the dot, starting
* at face0 (d->faces[0]), we hit:
* (face0), edge0, face1, edge1, face2,...
*
* 0
* |
* 0 | 1
* |
* -----d-----1
* |
* | 2
* |
* 2
*
* So, for example, face1 should be joined to edge0 and edge1,
* and those edges should appear in an anticlockwise sense around
* that face (see diagram). */
/* clockwise search */
while (true) {
grid_face *f = d->faces[current_face1];
grid_edge *e;
int j;
assert(f != NULL);
/* find dot around this face */
for (j = 0; j < f->order; j++) {
if (f->dots[j] == d)
break;
}
assert(j != f->order); /* must find dot */
/* Around f, required edge is anticlockwise from the dot. See
* the other labelling scheme higher up, for why we subtract 1
* from j. */
j--;
if (j == -1)
j = f->order - 1;
e = f->edges[j];
d->edges[current_face1] = e; /* set edge */
current_face1++;
if (current_face1 == d->order)
break;
else {
/* set face */
d->faces[current_face1] =
(e->face1 == f) ? e->face2 : e->face1;
if (d->faces[current_face1] == NULL)
break; /* cannot progress beyond infinite face */
}
}
/* If the clockwise search made it all the way round, don't need to
* bother with the anticlockwise search. */
if (current_face1 == d->order)
continue; /* this dot is complete, move on to next dot */
/* anticlockwise search */
while (true) {
grid_face *f = d->faces[current_face2];
grid_edge *e;
int j;
assert(f != NULL);
/* find dot around this face */
for (j = 0; j < f->order; j++) {
if (f->dots[j] == d)
break;
}
assert(j != f->order); /* must find dot */
/* Around f, required edge is clockwise from the dot. */
e = f->edges[j];
current_face2--;
if (current_face2 == -1)
current_face2 = d->order - 1;
d->edges[current_face2] = e; /* set edge */
/* set face */
if (current_face2 == current_face1)
break;
d->faces[current_face2] =
(e->face1 == f) ? e->face2 : e->face1;
/* There's only 1 infinite face, so we must get all the way
* to current_face1 before we hit it. */
assert(d->faces[current_face2]);
}
}
/* ====== Stage 4 ======
* Compute other grid settings
*/
/* Bounding rectangle */
for (i = 0; i < g->num_dots; i++) {
grid_dot *d = g->dots + i;
if (i == 0) {
g->lowest_x = g->highest_x = d->x;
g->lowest_y = g->highest_y = d->y;
} else {
g->lowest_x = min(g->lowest_x, d->x);
g->highest_x = max(g->highest_x, d->x);
g->lowest_y = min(g->lowest_y, d->y);
g->highest_y = max(g->highest_y, d->y);
}
}
grid_debug_derived(g);
}
/* Helpers for making grid-generation easier. These functions are only
* intended for use during grid generation. */
/* Comparison function for the (tree234) sorted dot list */
static int grid_point_cmp_fn(void *v1, void *v2)
{
grid_dot *p1 = v1;
grid_dot *p2 = v2;
if (p1->y != p2->y)
return p2->y - p1->y;
else
return p2->x - p1->x;
}
/* Add a new face to the grid, with its dot list allocated.
* Assumes there's enough space allocated for the new face in grid->faces */
static void grid_face_add_new(grid *g, int face_size)
{
int i;
grid_face *new_face = g->faces + g->num_faces;
new_face->order = face_size;
new_face->dots = snewn(face_size, grid_dot*);
for (i = 0; i < face_size; i++)
new_face->dots[i] = NULL;
new_face->edges = NULL;
new_face->has_incentre = false;
g->num_faces++;
}
/* Assumes dot list has enough space */
static grid_dot *grid_dot_add_new(grid *g, int x, int y)
{
grid_dot *new_dot = g->dots + g->num_dots;
new_dot->order = 0;
new_dot->edges = NULL;
new_dot->faces = NULL;
new_dot->x = x;
new_dot->y = y;
g->num_dots++;
return new_dot;
}
/* Retrieve a dot with these (x,y) coordinates. Either return an existing dot
* in the dot_list, or add a new dot to the grid (and the dot_list) and
* return that.
* Assumes g->dots has enough capacity allocated */
static grid_dot *grid_get_dot(grid *g, tree234 *dot_list, int x, int y)
{
grid_dot test, *ret;
test.order = 0;
test.edges = NULL;
test.faces = NULL;
test.x = x;
test.y = y;
ret = find234(dot_list, &test, NULL);
if (ret)
return ret;
ret = grid_dot_add_new(g, x, y);
add234(dot_list, ret);
return ret;
}
/* Sets the last face of the grid to include this dot, at this position
* around the face. Assumes num_faces is at least 1 (a new face has
* previously been added, with the required number of dots allocated) */
static void grid_face_set_dot(grid *g, grid_dot *d, int position)
{
grid_face *last_face = g->faces + g->num_faces - 1;
last_face->dots[position] = d;
}
/*
* Helper routines for grid_find_incentre.
*/
static bool solve_2x2_matrix(double mx[4], double vin[2], double vout[2])
{
double inv[4];
double det;
det = (mx[0]*mx[3] - mx[1]*mx[2]);
if (det == 0)
return false;
inv[0] = mx[3] / det;
inv[1] = -mx[1] / det;
inv[2] = -mx[2] / det;
inv[3] = mx[0] / det;
vout[0] = inv[0]*vin[0] + inv[1]*vin[1];
vout[1] = inv[2]*vin[0] + inv[3]*vin[1];
return true;
}
static bool solve_3x3_matrix(double mx[9], double vin[3], double vout[3])
{
double inv[9];
double det;
det = (mx[0]*mx[4]*mx[8] + mx[1]*mx[5]*mx[6] + mx[2]*mx[3]*mx[7] -
mx[0]*mx[5]*mx[7] - mx[1]*mx[3]*mx[8] - mx[2]*mx[4]*mx[6]);
if (det == 0)
return false;
inv[0] = (mx[4]*mx[8] - mx[5]*mx[7]) / det;
inv[1] = (mx[2]*mx[7] - mx[1]*mx[8]) / det;
inv[2] = (mx[1]*mx[5] - mx[2]*mx[4]) / det;
inv[3] = (mx[5]*mx[6] - mx[3]*mx[8]) / det;
inv[4] = (mx[0]*mx[8] - mx[2]*mx[6]) / det;
inv[5] = (mx[2]*mx[3] - mx[0]*mx[5]) / det;
inv[6] = (mx[3]*mx[7] - mx[4]*mx[6]) / det;
inv[7] = (mx[1]*mx[6] - mx[0]*mx[7]) / det;
inv[8] = (mx[0]*mx[4] - mx[1]*mx[3]) / det;
vout[0] = inv[0]*vin[0] + inv[1]*vin[1] + inv[2]*vin[2];
vout[1] = inv[3]*vin[0] + inv[4]*vin[1] + inv[5]*vin[2];
vout[2] = inv[6]*vin[0] + inv[7]*vin[1] + inv[8]*vin[2];
return true;
}
void grid_find_incentre(grid_face *f)
{
double xbest, ybest, bestdist;
int i, j, k, m;
grid_dot *edgedot1[3], *edgedot2[3];
grid_dot *dots[3];
int nedges, ndots;
if (f->has_incentre)
return;
/*
* Find the point in the polygon with the maximum distance to any
* edge or corner.
*
* Such a point must exist which is in contact with at least three
* edges and/or vertices. (Proof: if it's only in contact with two
* edges and/or vertices, it can't even be at a _local_ maximum -
* any such circle can always be expanded in some direction.) So
* we iterate through all 3-subsets of the combined set of edges
* and vertices; for each subset we generate one or two candidate
* points that might be the incentre, and then we vet each one to
* see if it's inside the polygon and what its maximum radius is.
*
* (There's one case which this algorithm will get noticeably
* wrong, and that's when a continuum of equally good answers
* exists due to parallel edges. Consider a long thin rectangle,
* for instance, or a parallelogram. This algorithm will pick a
* point near one end, and choose the end arbitrarily; obviously a
* nicer point to choose would be in the centre. To fix this I
* would have to introduce a special-case system which detected
* parallel edges in advance, set aside all candidate points
* generated using both edges in a parallel pair, and generated
* some additional candidate points half way between them. Also,
* of course, I'd have to cope with rounding error making such a
* point look worse than one of its endpoints. So I haven't done
* this for the moment, and will cross it if necessary when I come
* to it.)
*
* We don't actually iterate literally over _edges_, in the sense
* of grid_edge structures. Instead, we fill in edgedot1[] and
* edgedot2[] with a pair of dots adjacent in the face's list of
* vertices. This ensures that we get the edges in consistent
* orientation, which we could not do from the grid structure
* alone. (A moment's consideration of an order-3 vertex should
* make it clear that if a notional arrow was written on each
* edge, _at least one_ of the three faces bordering that vertex
* would have to have the two arrows tip-to-tip or tail-to-tail
* rather than tip-to-tail.)
*/
nedges = ndots = 0;
bestdist = 0;
xbest = ybest = 0;
for (i = 0; i+2 < 2*f->order; i++) {
if (i < f->order) {
edgedot1[nedges] = f->dots[i];
edgedot2[nedges++] = f->dots[(i+1)%f->order];
} else
dots[ndots++] = f->dots[i - f->order];
for (j = i+1; j+1 < 2*f->order; j++) {
if (j < f->order) {
edgedot1[nedges] = f->dots[j];
edgedot2[nedges++] = f->dots[(j+1)%f->order];
} else
dots[ndots++] = f->dots[j - f->order];
for (k = j+1; k < 2*f->order; k++) {
double cx[2], cy[2]; /* candidate positions */
int cn = 0; /* number of candidates */
if (k < f->order) {
edgedot1[nedges] = f->dots[k];
edgedot2[nedges++] = f->dots[(k+1)%f->order];
} else
dots[ndots++] = f->dots[k - f->order];
/*
* Find a point, or pair of points, equidistant from
* all the specified edges and/or vertices.
*/
if (nedges == 3) {
/*
* Three edges. This is a linear matrix equation:
* each row of the matrix represents the fact that
* the point (x,y) we seek is at distance r from
* that edge, and we solve three of those
* simultaneously to obtain x,y,r. (We ignore r.)
*/
double matrix[9], vector[3], vector2[3];