-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTile.js
110 lines (96 loc) · 2.97 KB
/
Tile.js
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
import { EPSILON } from './draw.js';
import { get_wrap, wrap_index } from './util.js';
import Vector from './Vector.js';
export class Tile {
static id_counter = 0;
constructor(node, points, neighbours) {
this.id = Tile.id_counter++;
this.node = node;
this.points = points;
this.neighbours = neighbours;
this.original_points = this.deduplicate();
this.direction = this.get_direction();
this.parity = this.get_parity();
this.node.dataset.id = this.id;
this.node.classList.add(this.parity == 0 ? 'even' : 'odd');
}
get center() {
return this.points.reduce((a, b) => a.add(b), new Vector(0, 0)).mul(1 / this.points.length);
}
point(i) {
return get_wrap(this.points, i);
}
edge(i) {
return this.point(i + 1).sub(this.point(i));
}
corner(i) {
let v1 = this.edge(i - 1).normalize();
let v2 = this.edge(i).normalize();
return {
dot: v1.dot(v2),
sign: Math.sign(v1.cross(v2))
};
}
get_direction() {
let p = this.point(0);
let e = this.edge(0);
let t = p.add(e.mul(.5)).add(new Vector(-e.y, e.x).mul(.1));
for (let n of document.elementsFromPoint(t.x, t.y)) {
if (n == this.node) {
return 1;
}
}
return -1;
}
deduplicate() {
candidate_loop: for (let i in this.points) {
i = Number(i);
if (i == 0 || this.points.length % i != 0) {
continue;
}
for (let j in this.points) {
j = Number(j);
if (j < i) {
continue;
}
let c1 = this.corner(j);
let c2 = this.corner(j % i);
if (Math.abs(this.edge(j).length() - this.edge(j % i).length()) > EPSILON
|| Math.abs(c1.dot - c2.dot) > EPSILON
|| c1.sign != c2.sign) {
continue candidate_loop;
}
}
return this.points.slice(0, i);
}
return this.points;
}
get_parity() {
if (!this.neighbours) {
return 0;
}
let result = null;
for (let i in this.neighbours) {
if (result == null) {
result = (this.neighbours[i].tile.parity + 1) % 2;
}
if (result != (this.neighbours[i].tile.parity + 1) % 2) {
console.log("Parity mismatch: ", this, i, this.neighbours[i]);
}
}
return result ?? 0;
}
neighbour(i) {
return get_wrap(this.neighbours, i) ?? null;
}
set_neighbour(i, tile, edge) {
if (tile == null) {
delete this.neighbours[wrap_index(i, this.points.length)];
} else {
this.neighbours[wrap_index(i, this.points.length)] = {
tile,
edge
};
}
}
}