-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsweep.js
331 lines (273 loc) · 8.39 KB
/
sweep.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
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
import createEventQueue from './src/createEventQueue';
import createSweepStatus from './src/sweepStatus';
import SweepEvent from './src/SweepEvent';
import {intersectSegments, EPS, angle, samePoint} from './src/geom';
/**
* A point on a line
*
* @typedef {Object} Point
* @property {number} x coordinate
* @property {number} y coordinate
*/
/**
* @typedef {Object} Segment
* @property {Point} from start of the segment
* @property {Point} to end of the segment
*/
/**
* @typedef {function(point : Point, interior : Segment[], lower : Segment[], upper : Segment[])} ReportIntersectionCallback
*/
/**
* @typedef {Object} ISectOptions
* @property {ReportIntersectionCallback} onFound
*/
/**
* @typedef {Object} ISectResult
*/
// We use EMPTY array to avoid pressure on garbage collector. Need to be
// very cautious to not mutate this array.
var EMPTY = [];
/**
* Finds all intersections among given segments.
*
* The algorithm follows "Computation Geometry, Algorithms and Applications" book
* by Mark de Berg, Otfried Cheong, Marc van Kreveld, and Mark Overmars.
*
* Line is swept top-down
*
* @param {Segment[]} segments
* @param {ISectOptions=} options
* @returns {ISectResult}
*/
export default function isect(segments, options) {
var results = [];
var reportIntersection = (options && options.onFound) || defaultIntersectionReporter;
var onError = (options && options.onError) || defaultErrorReporter;
var eventQueue = createEventQueue(byY);
var sweepStatus = createSweepStatus(onError, EPS);
var lower, interior, lastPoint;
segments.forEach(addSegment);
return {
/**
* Find all intersections synchronously.
*
* @returns array of found intersections.
*/
run,
/**
* Performs a single step in the sweep line algorithm
*
* @returns true if there was something to process; False if no more work to do
*/
step,
// Methods below are low level API for fine-grained control.
// Don't use it unless you understand this code thoroughly
/**
* Add segment into the
*/
addSegment,
/**
* Direct access to event queue. Queue contains segment endpoints and
* pending detected intersections.
*/
eventQueue,
/**
* Direct access to sweep line status. "Status" holds information about
* all intersected segments.
*/
sweepStatus,
/**
* Access to results array. Works only when you use default onFound() handler
*/
results
}
function run() {
while (!eventQueue.isEmpty()) {
var eventPoint = eventQueue.pop();
if (handleEventPoint(eventPoint)) {
// they decided to stop.
return;
};
}
return results;
}
function step() {
if (!eventQueue.isEmpty()) {
var eventPoint = eventQueue.pop();
handleEventPoint(eventPoint);
// Note: we don't check results of `handleEventPoint()`
// assumption is that client controls `step()` and thus they
// know better if they want to stop.
return true;
}
return false;
}
function handleEventPoint(p) {
lastPoint = p.point;
var upper = p.from || EMPTY;
lower = interior = undefined;
// TODO: move lower/interior into sweep status method?
sweepStatus.findSegmentsWithPoint(lastPoint, addLowerOrInterior);
// if (segmentsWithPoint) {
// segmentsWithPoint.forEach()
// }
if (!lower) lower = EMPTY;
if (!interior) interior = EMPTY;
var uLength = upper.length;
var iLength = interior.length;
var lLength = lower.length;
var hasIntersection = uLength + iLength + lLength > 1;
var hasPointIntersection = !hasIntersection && (uLength === 0 && lLength === 0 && iLength > 0);
if (hasIntersection || hasPointIntersection) {
p.isReported = true;
if (reportIntersection(lastPoint, union(interior, union(lower, upper)))) {
return true;
}
}
sweepStatus.deleteSegments(lower, interior, lastPoint);
sweepStatus.insertSegments(interior, upper, lastPoint);
var sLeft, sRight;
var hasNoCrossing = (uLength + iLength === 0);
if (hasNoCrossing) {
var leftRight = sweepStatus.getLeftRightPoint(lastPoint);
sLeft = leftRight.left;
if (!sLeft) return;
sRight = leftRight.right;
if (!sRight) return;
findNewEvent(sLeft, sRight, p);
} else {
var boundarySegments = sweepStatus.getBoundarySegments(upper, interior);
findNewEvent(boundarySegments.beforeLeft, boundarySegments.left, p);
findNewEvent(boundarySegments.right, boundarySegments.afterRight, p);
}
return false;
}
function addLowerOrInterior(s) {
if (samePoint(s.to, lastPoint)) {
if (!lower) lower = [s];
else lower.push(s);
} else if (!samePoint(s.from, lastPoint)) {
if (!interior) interior = [s];
else interior.push(s);
}
}
function findNewEvent(left, right, p) {
if (!left || !right) return;
var intersection = intersectSegments(left, right);
if (!intersection) {
return;
}
var dy = p.point.y - intersection.y
// TODO: should I add dy to intersection.y?
if (dy < -EPS) {
// this means intersection happened after the sweep line.
// We already processed it.
return;
}
if (Math.abs(dy) < EPS && intersection.x <= p.point.x) {
return;
}
// Need to adjust floating point for this special case,
// since otherwise it gives rounding errors:
roundNearZero(intersection);
var current = eventQueue.find(intersection);
if (current && current.isReported) {
// We already reported this event. No need to add it one more time
// TODO: Is this case even possible?
onError('We already reported this event.');
return;
}
if (!current) {
var event = new SweepEvent(intersection)
eventQueue.insert(event);
}
}
function defaultIntersectionReporter(p, segments) {
results.push({
point: p,
segments: segments
});
}
function addSegment(segment) {
var from = segment.from;
var to = segment.to;
// Small numbers give more precision errors. Rounding them to 0.
roundNearZero(from);
roundNearZero(to);
var dy = from.y - to.y;
// Note: dy is much smaller then EPS on purpose. I found that higher
// precision here does less good - getting way more rounding errors.
if (Math.abs(dy) < 1e-5) {
from.y = to.y;
segment.dy = 0;
}
if ((from.y < to.y) || (
(from.y === to.y) && (from.x > to.x))
) {
var temp = from;
from = segment.from = to;
to = segment.to = temp;
}
// We pre-compute some immutable properties of the segment
// They are used quite often in the tree traversal, and pre-computation
// gives significant boost:
segment.dy = from.y - to.y;
segment.dx = from.x - to.x;
segment.angle = angle(segment.dy, segment.dx);
var isPoint = segment.dy === segment.dx && segment.dy === 0;
var prev = eventQueue.find(from)
if (prev && !isPoint) {
// this detects identical segments early. Without this check
// the algorithm would break since sweep line has no means to
// detect identical segments.
var prevFrom = prev.data.from;
if (prevFrom) {
for (var i = 0; i < prevFrom.length; ++i) {
var s = prevFrom[i];
if (samePoint(s.to, to)) {
reportIntersection(s.from, [s.from, s.to]);
reportIntersection(s.to, [s.from, s.to]);
return;
}
}
}
}
if (!isPoint) {
if (prev) {
if (prev.data.from) prev.data.from.push(segment);
else prev.data.from = [segment];
} else {
var e = new SweepEvent(from, segment)
eventQueue.insert(e);
}
var event = new SweepEvent(to)
eventQueue.insert(event)
} else {
var event = new SweepEvent(to)
eventQueue.insert(event)
}
}
}
function roundNearZero(point) {
if (Math.abs(point.x) < EPS) point.x = 0;
if (Math.abs(point.y) < EPS) point.y = 0;
}
function defaultErrorReporter(errorMessage) {
throw new Error(errorMessage);
}
function union(a, b) {
if (!a) return b;
if (!b) return a;
return a.concat(b);
}
function byY(a, b) {
// decreasing Y
var res = b.y - a.y;
// TODO: This might mess up the status tree.
if (Math.abs(res) < EPS) {
// increasing x.
res = a.x - b.x;
if (Math.abs(res) < EPS) res = 0;
}
return res;
}