-
Notifications
You must be signed in to change notification settings - Fork 0
/
poisson.js
77 lines (63 loc) · 1.61 KB
/
poisson.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
importScripts('quadtree.js');
const PI2 = Math.PI * 2;
var RADIUS = 20;
var CANDIDATES = 10;
var WIDTH = 100;
var HEIGHT = 100;
var polygons = [];
var points = [];
var active = [];
var quadtree;
function poisson() {
quadtree = quadtreeNew(0, 0, WIDTH, HEIGHT);
// create one random point
var point = {
x: Math.random() * WIDTH,
y: Math.random() * HEIGHT,
};
points.push(point);
active.push(point);
quadtreeAdd(quadtree, point);
while (active.length) {
// get a random active sample
var randomIndex = Math.floor(Math.random() * active.length);
var current = active[randomIndex];
var acceptable = null;
// generate candidates
for (var i = 0; i < CANDIDATES; i++) {
var far = Math.random() * RADIUS + RADIUS;
var angle = Math.random() * PI2;
var candidate = {
x: current.x + Math.cos(angle) * far,
y: current.y - Math.sin(angle) * far,
};
var good = true;
// check candidate
if (candidate.x > WIDTH || candidate.y > HEIGHT
|| candidate.x < 0 || candidate.y < 0) {
good = false;
} else {
good = quadtreeFits(quadtree, candidate);
}
if (good) {
acceptable = candidate;
break;
}
}
if (acceptable) {
points.push(acceptable);
active.push(acceptable);
quadtreeAdd(quadtree, acceptable);
} else {
active.splice(randomIndex, 1);
}
}
}
self.onmessage = function (event) {
RADIUS = event.data[0];
CANDIDATES = event.data[1];
WIDTH = event.data[2];
HEIGHT = event.data[3];
poisson();
postMessage([points, quadtree]);
};