-
Notifications
You must be signed in to change notification settings - Fork 1
/
index2.html
654 lines (575 loc) · 18.5 KB
/
index2.html
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
<html lang="en">
<meta charset="utf-8"/>
<head><title>Test Voronoï</title></head>
<body>
<h1>Constrained Delaunay triangulation algorithm implemented with Quad-Edges</h1>
<p>This example uses a refinement algorithm where we compute a giant triangle
surrounding all the sites, then insert them one by one while keeping the
triangulation.</p>
<p>The geometric predicates (inCircle and isRightOf) have not been made robust. The envelope has been left gray. </p>
<p>Clicking on a triangle displays its circumscribed
circle, it should be respect the "Modified circle criterion".</p>
<div id="draw"></div>
<script src="svg.js"></script>
<script>
// http://www.cs.cmu.edu/afs/andrew/scs/cs/15-463/2001/pub/src/a2/cell/
// https://github.com/hastebrot/jsts-dist/blob/master/src/jsts
// https://github.com/savithru-j/cdt-js
// https://doc.cgal.org/latest/Triangulation_2/index.html
// GRAPH STUFF
class QuadEdge {
constructor () {
this.rot = null
this.vertex = null
this.next = null
}
get sym () {
return this.rot.rot
}
get org () {
return this.vertex
}
set org (o) {
this.vertex = o
}
get dest () {
return this.sym.org
}
set dest (d) {
this.sym.org = d
}
get invRot () {
return this.rot.sym
}
get left () {
return this.rot.vertex
}
get right () {
return this.invRot.vertex
}
get lNext () {
return this.invRot.oNext.rot
}
get lPrev () {
return this.next.sym
}
get rNext () {
return this.rot.oNext.invRot
}
get oNext () {
return this.next
}
get oPrev () {
return this.rot.next.rot
}
get dPrev () {
return this.invRot.oNext.invRot
}
get rPrev () {
return this.sym.oNext
}
}
const allEdges = []
function makeEdge (v1, v2) {
const q0 = new QuadEdge()
allEdges.push(q0)
const q1 = new QuadEdge()
const q2 = new QuadEdge()
const q3 = new QuadEdge()
q0.rot = q1
q1.rot = q2
q2.rot = q3
q3.rot = q0
q0.next = q0
q1.next = q3
q2.next = q2
q3.next = q1
q0.org = v1
q0.dest = v2
console.assert(q0.dest === v2)
console.assert(q0.org !== q0.dest, q0.org, q0.dest)
console.assert(q0.left === q0.right)
console.assert(q0.lNext === q0.rNext)
console.assert(q0.lNext === q0.sym)
console.assert(q0.oPrev === q0.oNext)
console.assert(q0.oPrev === q0)
q1.org = generateColor()
q3.org = generateColor()
return q0
}
function splice (a, b) {
const alpha = a.oNext.rot
const beta = b.oNext.rot
const t1 = b.oNext
const t2 = a.oNext
const t3 = beta.oNext
const t4 = alpha.oNext
a.next = t1
b.next = t2
alpha.next = t3
beta.next = t4
}
function connect (a, b) {
const e = makeEdge(a.dest, b.org)
splice(e, a.lNext)
splice(e.sym, b)
return e
}
function swap (e) {
const a = e.oPrev
const b = e.sym.oPrev
splice(e, a)
splice(e.sym, b)
splice(e, a.lNext)
splice(e.sym, b.lNext)
e.org = a.dest
e.dest = b.dest
}
</script>
<script>
// GEOMETRIC STUFF
function triArea (a, b, c) {
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)
}
function ccw (a, b, c) {
return triArea(a, b, c) > 0
}
function inCircle (a, b, c, p) {
const det = (a.x * a.x + a.y * a.y) * triArea(b, c, p) -
(b.x * b.x + b.y * b.y) * triArea(a, c, p) +
(c.x * c.x + c.y * c.y) * triArea(a, b, p) -
(p.x * p.x + p.y * p.y) * triArea(a, b, c)
return det > 0
}
// check the circle of the triangle this edge is in vs the point of the symmetric triangle
function inCircleEdge (edge) {
return inCircle(edge.org, edge.rPrev.dest, edge.dest, edge.sym.rPrev.dest)
}
function circumCenter (p0, p1, p2) {
const d = 2 * (p0.x * (p1.y - p2.y) + p1.x * (p2.y - p0.y) + p2.x * (p0.y - p1.y))
const p0_mag = p0.x * p0.x + p0.y * p0.y
const p1_mag = p1.x * p1.x + p1.y * p1.y
const p2_mag = p2.x * p2.x + p2.y * p2.y
const x = (p0_mag * (p1.y - p2.y) + p1_mag * (p2.y - p0.y) + p2_mag * (p0.y - p1.y)) / d
const y = (p0_mag * (p2.x - p1.x) + p1_mag * (p0.x - p2.x) + p2_mag * (p1.x - p0.x)) / d
return {x, y}
}
function circumCircleForEdge (edge) {
return circumCircle(edge.org, edge.dest, edge.rPrev.dest)
}
function circumCircle (a, b, c) {
const {x, y} = circumCenter(a, b, c)
const sq = v => v * v
return {x, y, r: Math.sqrt(sq(a.x - x) + sq(a.y - y))}
}
console.assert(inCircle({x: 1, y: 2}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 1.5, y: 1.5}))
console.assert(!inCircle({x: 1, y: 2}, {x: 1, y: 1}, {x: 2, y: 1}, {x: 15, y: 15}))
function edgeVector (e) {
const dx = e.dest.x - e.org.x
const dy = e.dest.y - e.org.y
return {x: dx, y: dy}
}
function edgeLength (e) {
const v = edgeVector(e)
return Math.sqrt(v.x * v.x + v.y * v.y)
}
function edgeOriginBisector (e) {
const prevVector = edgeVector(e.oNext)
const prevLength = edgeLength(e.oNext)
const vector = edgeVector(e)
const length = edgeLength(e)
return {
x: 20 * (vector.x / length + prevVector.x / prevLength),
y: 20 * (vector.y / length + prevVector.y / prevLength)
}
}
function edgeNormal (e, factor = 1) {
const vector = edgeVector(e)
const length = edgeLength(e)
// noinspection JSSuspiciousNameCombination
return {x: factor * -vector.y / length, y: factor * vector.x / length}
}
function edgeDirection (e, factor = 1) {
const vector = edgeVector(e)
const length = edgeLength(e)
return {x: factor * vector.x / length, y: factor * vector.y / length}
}
function isRightOf (point, edge) {
return ccw(point, edge.dest, edge.org)
}
// one edge and 2 points
function doesIntersect (edge, p1, p2) {
//https://stackoverflow.com/a/1968345/72637
const s1X = edge.dest.x - edge.org.x
const s1Y = edge.dest.y - edge.org.y
const s2X = p2.x - p1.x
const s2Y = p2.y - p1.y
let denominator = (-s2X * s1Y + s1X * s2Y)
let s = (-s1Y * (edge.org.x - p1.x) + s1X * (edge.org.y - p1.y)) / denominator
let t = (s2X * (edge.org.y - p1.y) - s2Y * (edge.org.x - p1.x)) / denominator
return (s >= 0 && s <= 1 && t >= 0 && t <= 1)
}
function edgeEndsAtPoint (edge, point) {
return edge.org === point || edge.dest === point
}
function isConvex (p1, p2, p3, p4) {
const arr = [p1, p2, p3, p4]
const nextPoint = index => arr[(index + 1) % arr.length]
const edgeVector = (fromP, toP) => ({x: toP.x - fromP.x, y: toP.y - fromP.y})
const crossProductZ = (v1, v2) => v1.x * v2.y - v1.y * v2.x
const edgesCrossProducts = arr.map((p, i) => crossProductZ(edgeVector(p, nextPoint(i)), edgeVector(nextPoint(i), nextPoint(i + 1))))
edgesCrossProducts.sort((a, b) => a - b)
return Math.sign(edgesCrossProducts.shift()) * Math.sign(edgesCrossProducts.pop()) === 1
}
function isQuadAroundEdgeConvex (edge) {
return isConvex(edge.rNext.org, edge.org, edge.oNext.dest, edge.dest)
}
function locateFromEdge (vertex, edge) {
let iter = 0
let e = edge
while (true) {
iter++
if (iter > 1000) {
throw new Error('lol')
}
if (vertex === e.org || vertex === e.dest) {
break
}
if (isRightOf(vertex, e)) {
e = e.sym
} else if (!isRightOf(vertex, e.oNext)) {
e = e.oNext
} else if (!isRightOf(vertex, e.dPrev)) {
e = e.dPrev
} else {
break
}
}
return e
}
function insertSite (edge, vertex) {
let e = locateFromEdge(vertex, edge)
if (e.org === vertex || e.dest === vertex) {
return e
}
//TODO: is on edge
let base = makeEdge(e.org, vertex)
splice(base, e)
const startEdge = base
let i = 10
const newEdgeGroup = svg.group().attr({stroke: 'green', 'stroke-width': 3})
const flippedEdges = newEdgeGroup.group().attr({stroke: 'red'})
newEdgeGroup.circle(10).move(vertex.x - 5, vertex.y - 5).attr({'stroke-width': 1, fill: 'none'})
displayEdge(base, newEdgeGroup)
do {
base = connect(e, base.sym)
displayEdge(base, newEdgeGroup)
e = base.oPrev
i--
if (i <= 0)
throw Error('error')
} while (e.lNext !== startEdge && i > 0)
i = 100
const suspectGroup = newEdgeGroup.group().attr({stroke: 'orange', 'stroke-width': 4, 'stroke-opacity': 4})
do {
const t = e.oPrev
const circleDef = circumCircle(e.org, t.dest, e.dest)
const localGroup = newEdgeGroup.group().attr({stroke: 'red', 'stroke-width': 1, fill: 'none'})
localGroup.circle(circleDef.r * 2).move(circleDef.x - circleDef.r, circleDef.y - circleDef.r)
displayEdge(e, localGroup)
//debugger
if (isRightOf(t.dest, e) && inCircle(e.org, t.dest, e.dest, vertex)) {
swap(e)
displayEdge(e, flippedEdges)
// go back and re-test the same edge with the new triangle
e = e.oPrev
} else {
if (e.oNext === startEdge) {
newEdgeGroup.remove()
return base
}
displayEdge(e, suspectGroup)
e = e.oNext.lPrev
}
localGroup.remove()
i--
if (i <= 0)
throw Error('error')
} while (true)
}
// https://stackoverflow.com/a/328110/72637
// http://bit-player.org/wp-content/extras/bph-publications/BeautifulCode-2007-Hayes.pdf
function pointIsOnSegment (p1, p2, testPoint) {
function within (a, b, candidate) {
const arr = [a, b, candidate]
arr.sort((a, b) => a - b)
return arr[1] === candidate
}
const collinear = (p2.x - p1.x) * (testPoint.y - p1.y) === (testPoint.x - p1.x) * (p2.y - p1.y)
return collinear && (p1.x !== p2.x ? within(p1.x, p2.x, testPoint.x) : within(p1.y, p2.y, testPoint.y))
}
function getNeighbors (edge, neighborOperator = e => e.oPrev) {
const res = []
let e = edge
do {
e = neighborOperator(e)
res.push(e)
} while (e !== edge)
return res
}
class PointOnSegmentError extends Error {
constructor (message, point) {
super(message)
this.point = point
}
}
/**
*
* http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.61.3862&rep=rep1&type=pdf
* https://infoscience.epfl.ch/record/100269/files/Kallmann_and_al_Geometric_Modeling_03.pdf
* @throws PointOnSegmentError
*/
function insertConstraint (edge, p1, p2) {
const newEdgeGroup = svg.group().attr({stroke: 'green', 'stroke-width': 3})
try {
newEdgeGroup.line(p1.x, p1.y, p2.x, p2.y)
let e = locateFromEdge(p1, edge)
if (e.org !== p1)
e = e.sym
// check if there is an existing edge from P1 to P2
for (let n of getNeighbors(e)) {
if (edgeEndsAtPoint(n, p2)) {
n.constrained = true
n.sym.constrained = true
return n
}
}
while (!doesIntersect(e.rPrev, p1, p2))
e = e.oNext
const findNextCrossingEdge = (e) => doesIntersect(e.rPrev, p1, p2) && !edgeEndsAtPoint(e.rPrev, p1) && !edgeEndsAtPoint(e.rPrev, p2) ? e.rPrev : e.rPrev.rPrev
let e1 = e.rPrev.sym
const intersectingEdges = []
while (!edgeEndsAtPoint(e1, p2)) {
if (pointIsOnSegment(p1, p2, e1.org))
throw new PointOnSegmentError('point on Segment', e1.org)
if (pointIsOnSegment(p1, p2, e1.dest))
throw new PointOnSegmentError('point on Segment', e1.dest)
intersectingEdges.push(e1)
e1 = findNextCrossingEdge(e1).sym
}
let currentEdge
const newEdgesSet = new Set()
while ((currentEdge = intersectingEdges.shift())) {
const svgE = displayEdge(currentEdge, root)
if (isQuadAroundEdgeConvex(currentEdge)) {
swap(currentEdge)
newEdgesSet.add(currentEdge)
if (!edgeEndsAtPoint(currentEdge, p1) && !edgeEndsAtPoint(currentEdge, p2) && doesIntersect(currentEdge, p1, p2))
intersectingEdges.push(currentEdge)
} else
intersectingEdges.push(currentEdge)
svgE.remove()
}
const newEdges = [...newEdgesSet]
let constrainedEdge = null
let hasSwapped
do {
hasSwapped = false
for (currentEdge of newEdges) {
let svgEdge = displayEdge(currentEdge, root)
if (!(edgeEndsAtPoint(currentEdge, p1) && edgeEndsAtPoint(currentEdge, p2))) {
if (isQuadAroundEdgeConvex(currentEdge) && inCircleEdge(currentEdge)) {
swap(currentEdge)
hasSwapped = true
}
} else {
currentEdge.constrained = true
currentEdge.sym.constrained = true
constrainedEdge = currentEdge
}
svgEdge.remove()
}
} while (hasSwapped)
return constrainedEdge
} finally {
newEdgeGroup.remove()
}
}
function makeTriangle (v1, v2, v3) {
const ea = makeEdge(v1, v2)
const eb = makeEdge(v2, v3)
splice(ea.sym, eb)
const ec = makeEdge(v3, v1)
splice(eb.sym, ec)
splice(ec.sym, ea)
return ea
}
const TAN_60 = Math.sqrt(3)
/***
* This is a triangle with an horizontal base and 2 60° sides.
* minX and maxX are the abscissa at y == 0
*/
class Envelope {
constructor () {
this.minY = NaN
this.minX = NaN
this.maxX = NaN
}
addPoint (x, y) {
this.minY = isNaN(this.minY) || y < this.minY ? y : this.minY
const limits = [x - y / TAN_60, x + y / TAN_60, this.minX, this.maxX].filter(e => !isNaN(e))
limits.sort((a, b) => a - b)
this.minX = limits[0]
this.maxX = limits[limits.length - 1]
}
get apex () {
const x = (this.minX + this.maxX) / 2
return {x: x, y: Math.abs(this.minX - x) * TAN_60 + 20}
}
get botLeft () {
const y = this.minY - 20
return {x: this.minX - 20 + (y / TAN_60), y}
}
get botRight () {
const y = this.minY - 20
return {x: this.maxX + 20 - (y / TAN_60), y}
}
}
</script>
<script>
// google: octilinear metric
function generatePoints (count, xMin, xSize, yMin, ySize) {
const getNumber = (size) => Math.floor(Math.random() * size / 25) * 25
const points = {}
while (Object.keys(points).length < count) {
const point = {x: xMin + getNumber(xSize), y: yMin + getNumber(ySize)}
points[`${point.x}|${point.y}`] = point
}
return Object.values(points)
}
const generateColor = () => '#' + ('000000' + ((1 << 24) * Math.random() | 0).toString(16)).substr(-6)
function displayEdge (e, group) {
const o = e.org
const d = e.dest
return group.line(o.x, o.y, d.x, d.y)
}
function displayPolygon (edges, group) {
group.polygon(edges.map(e => [e.org.x, e.org.y]))
}
function displayEdgeCircumCircle (edge, group) {
const circleDef = circumCircleForEdge(edge)
return group.circle(circleDef.r * 2).move(circleDef.x - circleDef.r, circleDef.y - circleDef.r)
}
function * iteratePolygons (startEdge, skippedVertices = new Set()) {
const markedEdges = new Set()
const edgeStack = [startEdge]
while (edgeStack.length) {
const e = edgeStack.pop()
if (markedEdges.has(e)) {
continue
}
if (e.left) {
let skipFace = false
let points = []
let faceEdge = e
do {
markedEdges.add(faceEdge)
edgeStack.push(faceEdge.sym)
if (skippedVertices.has(faceEdge.org))
skipFace = true
points.push(faceEdge.org)
faceEdge = faceEdge.lNext
} while (faceEdge !== e)
if (!skipFace)
yield points
}
}
}
let svg = SVG(document.querySelector('#draw')[0])
const points = generatePoints(30, 30, 400, 30, 300)
const envelopeGroup = svg.group().attr({
stroke: 'lightgray',
'stroke-width': 10,
'stroke-linejoin': 'arcs',
'fill': 'none'
})
const background = svg.group()
const root = svg.group().attr({stroke: 'red', fill: 'none', class: 'root', 'vector-effect': 'non-scaling-stroke'})
const arrowMarker = svg.marker(10, 10, function (g) {
g.path('M0,0 L10,5 0,10').attr('fill', 'green')
})
const blueGroup = svg.group().attr({stroke: 'blue', fill: 'blue'})
const edgeGroup = svg.group().attr({class: 'edges', 'vector-effect': 'non-scaling-stroke'})
edgeGroup.attr({stroke: 'green', 'stroke-width': 1.5, 'marker-end': arrowMarker})
const envelope = new Envelope()
points.forEach(({x, y}) => envelope.addPoint(x, y))
function displayPoint (p, name) {
root.line(p.x - 10, p.y - 10, p.x + 10, p.y + 10)
root.line(p.x - 10, p.y + 10, p.x + 10, p.y - 10)
root.plain(name).move(p.x, p.y)
}
let botLeft = envelope.botLeft
let botRight = envelope.botRight
let apex = envelope.apex
const ea = makeTriangle(apex, botRight, botLeft)
ea.rot.vertex = generateColor()
displayPolygon([ea, ea.lNext, ea.lNext.lNext], envelopeGroup)
let i = 0
for (let vertex of points) {
displayPoint(vertex, 'V' + i)
const polygons = background.group()
for (let polygon of iteratePolygons(ea)) {
polygons.polygon(polygon.map(point => [point.x, point.y])).attr({
fill: 'blue',
'fill-opacity': 0.2,
stroke: 'white',
'stroke-width': 2,
'stroke-linejoin': 'round'
})
}
insertSite(ea, vertex)
polygons.remove()
i++
}
let splitSegments = [[points[29], points[2]]]
while (splitSegments.length) {
const currentConstraint = splitSegments.shift()
try {
const constrainedEdge = insertConstraint(ea, currentConstraint[0], currentConstraint[1])
displayEdge(constrainedEdge, edgeGroup).attr({stroke: 'green', 'stroke-width': 2})
} catch (e) {
if (e instanceof PointOnSegmentError) {
splitSegments.unshift([e.point, currentConstraint[1]])
splitSegments.unshift([currentConstraint[0], e.point])
} else
throw e
}
}
let currentCircle = null
for (let polygon of iteratePolygons(ea, new Set([apex, botRight, botLeft]))) {
background.polygon(polygon.map(point => [point.x, point.y])).attr({
fill: 'blue',
'fill-opacity': 0.4,
stroke: 'white',
'stroke-width': 4,
'stroke-linejoin': 'round'
}).click(() => {
if (currentCircle)
currentCircle.remove()
const circleDef = circumCircle(...polygon)
currentCircle = root.group()
currentCircle.polygon(polygon.map(point => [point.x, point.y])).attr({
fill: 'red',
stroke: 'white',
'stroke-width': 4,
'stroke-linejoin': 'round'
})
currentCircle.circle(circleDef.r * 2).move(circleDef.x - circleDef.r, circleDef.y - circleDef.r)
})
}
for (let e of allEdges) {
displayEdge(e, blueGroup)
}
</script>
</body>
</html>