Repository navigation
Expand file tree
/
Copy path11-hashing.html
More file actions
511 lines (397 loc) · 14.7 KB
/
Copy path11-hashing.html
File metadata and controls
511 lines (397 loc) · 14.7 KB
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
<!--
Copyright 2022 Matthias Müller - Ten Minute Physics
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<html lang="en">
<head>
<title>Spatial Hashing</title>
<style>
body {
font-family: verdana;
font-size: 15px;
}
.button {
background-color: #606060;
border: none;
color: white;
padding: 10px 32px;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Spatial Hashing</h1>
<button id = "buttonRun" onclick="run()" class="button">Run</button>
<button onclick="restart()" class="button">Restart</button>
<input type = "checkbox" onclick = "onShowColl()"> Show collisions</p>
<span id = "particleCount">0</span> particles,
<span id = "ms">0.000</span> ms per frame
<br><br>
<div id="container"></div>
<script src="https://unpkg.com/three@0.139.2/build/three.min.js"></script>
<script src="https://unpkg.com/three@0.139.2/examples/js/controls/OrbitControls.js"></script>
<script>
var threeScene;
var renderer;
var camera;
var cameraControl;
// ------------------------------------------------------------------
class Hash {
constructor(spacing, maxNumObjects)
{
this.spacing = spacing;
this.tableSize = 2 * maxNumObjects;
this.cellStart = new Int32Array(this.tableSize + 1);
this.cellEntries = new Int32Array(maxNumObjects);
this.queryIds = new Int32Array(maxNumObjects);
this.querySize = 0;
}
hashCoords(xi, yi, zi) {
var h = (xi * 92837111) ^ (yi * 689287499) ^ (zi * 283923481); // fantasy function
return Math.abs(h) % this.tableSize;
}
intCoord(coord) {
return Math.floor(coord / this.spacing);
}
hashPos(pos, nr) {
return this.hashCoords(
this.intCoord(pos[3 * nr]),
this.intCoord(pos[3 * nr + 1]),
this.intCoord(pos[3 * nr + 2]));
}
create(pos) {
var numObjects = Math.min(pos.length / 3, this.cellEntries.length);
// determine cell sizes
this.cellStart.fill(0);
this.cellEntries.fill(0);
for (var i = 0; i < numObjects; i++) {
var h = this.hashPos(pos, i);
this.cellStart[h]++;
}
// determine cells starts
var start = 0;
for (var i = 0; i < this.tableSize; i++) {
start += this.cellStart[i];
this.cellStart[i] = start;
}
this.cellStart[this.tableSize] = start; // guard
// fill in objects ids
for (var i = 0; i < numObjects; i++) {
var h = this.hashPos(pos, i);
this.cellStart[h]--;
this.cellEntries[this.cellStart[h]] = i;
}
}
query(pos, nr, maxDist) {
var x0 = this.intCoord(pos[3 * nr] - maxDist);
var y0 = this.intCoord(pos[3 * nr + 1] - maxDist);
var z0 = this.intCoord(pos[3 * nr + 2] - maxDist);
var x1 = this.intCoord(pos[3 * nr] + maxDist);
var y1 = this.intCoord(pos[3 * nr + 1] + maxDist);
var z1 = this.intCoord(pos[3 * nr + 2] + maxDist);
this.querySize = 0;
for (var xi = x0; xi <= x1; xi++) {
for (var yi = y0; yi <= y1; yi++) {
for (var zi = z0; zi <= z1; zi++) {
var h = this.hashCoords(xi, yi, zi);
var start = this.cellStart[h];
var end = this.cellStart[h + 1];
for (var i = start; i < end; i++) {
this.queryIds[this.querySize] = this.cellEntries[i];
this.querySize++;
}
}
}
}
}
};
// ----- math on vector arrays -------------------------------------------------------------
function vecScale(a,anr, scale) {
anr *= 3;
a[anr++] *= scale;
a[anr++] *= scale;
a[anr] *= scale;
}
function vecCopy(a,anr, b,bnr) {
anr *= 3; bnr *= 3;
a[anr++] = b[bnr++];
a[anr++] = b[bnr++];
a[anr] = b[bnr];
}
function vecAdd(a,anr, b,bnr, scale = 1.0) {
anr *= 3; bnr *= 3;
a[anr++] += b[bnr++] * scale;
a[anr++] += b[bnr++] * scale;
a[anr] += b[bnr] * scale;
}
function vecSetDiff(dst,dnr, a,anr, b,bnr, scale = 1.0) {
dnr *= 3; anr *= 3; bnr *= 3;
dst[dnr++] = (a[anr++] - b[bnr++]) * scale;
dst[dnr++] = (a[anr++] - b[bnr++]) * scale;
dst[dnr] = (a[anr] - b[bnr]) * scale;
}
function vecLengthSquared(a,anr) {
anr *= 3;
let a0 = a[anr], a1 = a[anr + 1], a2 = a[anr + 2];
return a0 * a0 + a1 * a1 + a2 * a2;
}
function vecDistSquared(a,anr, b,bnr) {
anr *= 3; bnr *= 3;
let a0 = a[anr] - b[bnr], a1 = a[anr + 1] - b[bnr + 1], a2 = a[anr + 2] - b[bnr + 2];
return a0 * a0 + a1 * a1 + a2 * a2;
}
function vecDot(a,anr, b,bnr) {
anr *= 3; bnr *= 3;
return a[anr] * b[bnr] + a[anr + 1] * b[bnr + 1] + a[anr + 2] * b[bnr + 2];
}
// ------------------------------------------------------------------
var physicsScene =
{
gravity : [0.0, 0.0, 0.0],
dt : 1.0 / 60.0,
worldBounds : [-1.0, 0.0, -1.0, 1.0, 2.0, 1.0],
paused: true,
balls: null,
};
function onShowColl() {
if (physicsScene.balls)
physicsScene.balls.showCollisions = !physicsScene.balls.showCollisions;
}
// ------------------------------------------------------------------
class Balls {
constructor(radius, pos, vel, scene)
{
// physics data
this.radius = radius;
this.pos = pos;
this.prevPos = pos;
this.vel = vel;
this.matrix = new THREE.Matrix4();
this.numBalls = Math.floor(pos.length / 3);
this.hash = new Hash(2.0 * radius, this.numBalls);
this.showCollisions = false;
this.normal = new Float32Array(3);
// visual mesh
var geometry = new THREE.SphereGeometry( radius, 8, 8 );
var material = new THREE.MeshPhongMaterial();
this.visMesh = new THREE.InstancedMesh( geometry, material, this.numBalls );
this.visMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
this.ballColor = new THREE.Color(0xFF0000);
this.ballCollisionColor = new THREE.Color(0xFF8000);
var colors = new Float32Array(3 * this.numBalls);
this.visMesh.instanceColor = new THREE.InstancedBufferAttribute(colors, 3, false, 1);
for (var i = 0; i < this.numBalls; i++)
this.visMesh.setColorAt(i, this.ballColor);
threeScene.add(this.visMesh);
this.updateMesh();
}
updateMesh()
{
for (var i = 0; i < this.numBalls; i++) {
this.matrix.makeTranslation(this.pos[3 * i], this.pos[3 * i + 1], this.pos[3 * i + 2]);
this.visMesh.setMatrixAt(i, this.matrix);
}
this.visMesh.instanceMatrix.needsUpdate = true;
this.visMesh.instanceColor.needsUpdate = true;
}
simulate(dt, gravity, worldBounds)
{
var minDist = 2.0 * this.radius;
// integrate
for (var i = 0; i < this.numBalls; i++) {
vecAdd(this.vel, i, gravity, 0, dt);
vecCopy(this.prevPos, i, this.pos, i);
vecAdd(this.pos, i, this.vel, i, dt);
}
this.hash.create(this.pos);
// handle collisions
for (var i = 0; i < this.numBalls; i++) {
this.visMesh.setColorAt(i, this.ballColor);
// world collision
for (var dim = 0; dim < 3; dim++) {
var nr = 3 * i + dim;
if (this.pos[nr] < worldBounds[dim] + this.radius) {
this.pos[nr] = worldBounds[dim] + this.radius;
this.vel[nr] = - this.vel[nr];
if (this.showCollisions)
this.visMesh.setColorAt(i, this.ballCollisionColor);
}
else if (this.pos[nr] > worldBounds[dim + 3] - this.radius) {
this.pos[nr] = worldBounds[dim + 3] - this.radius;
this.vel[nr] = - this.vel[nr];
if (this.showCollisions)
this.visMesh.setColorAt(i, this.ballCollisionColor);
}
}
// interball collision
this.hash.query(this.pos, i, 2.0 * this.radius);
for (var nr = 0; nr < this.hash.querySize; nr++) {
var j = this.hash.queryIds[nr];
vecSetDiff(this.normal, 0, this.pos, i, this.pos, j);
var d2 = vecLengthSquared(this.normal, 0);
// are the balls overlapping?
if (d2 > 0.0 && d2 < minDist * minDist) {
var d = Math.sqrt(d2);
vecScale(this.normal, 0, 1.0 / d);
// separate the balls
var corr = (minDist - d) * 0.5;
vecAdd(this.pos, i, this.normal, 0, corr);
vecAdd(this.pos, j, this.normal, 0, -corr);
// reflect velocities along normal
var vi = vecDot(this.vel, i, this.normal, 0);
var vj = vecDot(this.vel, j, this.normal, 0);
vecAdd(this.vel, i, this.normal, 0, vj - vi);
vecAdd(this.vel, j, this.normal, 0, vi - vj);
if (this.showCollisions)
this.visMesh.setColorAt(i, this.ballCollisionColor);
}
}
}
this.updateMesh();
}
}
// ------------------------------------------------------------------
function initPhysics(scene)
{
var radius = 0.025;
var spacing = 3.0 * radius;
var velRand = 0.2;
var s = physicsScene.worldBounds;
var numX = Math.floor((s[3] - s[0] - 2.0 * spacing) / spacing);
var numY = Math.floor((s[4] - s[1] - 2.0 * spacing) / spacing);
var numZ = Math.floor((s[5] - s[2] - 2.0 * spacing) / spacing);
var pos = new Float32Array(3 * numX * numY * numZ);
var vel = new Float32Array(3 * numX * numY * numZ);
vel.fill(0.0);
for (var xi = 0; xi < numX; xi++) {
for (var yi = 0; yi < numY; yi++) {
for (var zi = 0; zi < numZ; zi++) {
var x = 3 * ((xi * numY + yi) * numZ + zi);
var y = x + 1;
var z = x + 2;
pos[x] = s[0] + spacing + xi * spacing;
pos[y] = s[1] + spacing + yi * spacing;
pos[z] = s[2] + spacing + zi * spacing;
vel[x] = -velRand + 2.0 * velRand * Math.random();
vel[y] = -velRand + 2.0 * velRand * Math.random();
vel[z] = -velRand + 2.0 * velRand * Math.random();
}
}
}
physicsScene.balls = new Balls(radius, pos, vel, threeScene);
document.getElementById("particleCount").innerHTML = pos.length / 3;
}
var timeFrames = 0;
var timeSum = 0;
// ------------------------------------------------------------------
function simulate()
{
if (physicsScene.paused)
return;
var startTime = performance.now();
physicsScene.balls.simulate(physicsScene.dt,
physicsScene.gravity, physicsScene.worldBounds);
var endTime = performance.now();
timeSum += endTime - startTime;
timeFrames++;
if (timeFrames > 10) {
timeSum /= timeFrames;
document.getElementById("ms").innerHTML = timeSum.toFixed(3);
timeFrames = 0;
timeSum = 0;
}
}
// ------------------------------------------
function initThreeScene()
{
threeScene = new THREE.Scene();
// Lights
threeScene.add( new THREE.AmbientLight( 0x505050 ) );
threeScene.fog = new THREE.Fog( 0x000000, 0, 15 );
var spotLight = new THREE.SpotLight( 0xffffff );
spotLight.angle = Math.PI / 5;
spotLight.penumbra = 0.2;
spotLight.position.set( 2, 3, 3 );
spotLight.castShadow = true;
spotLight.shadow.camera.near = 3;
spotLight.shadow.camera.far = 10;
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;
threeScene.add( spotLight );
var dirLight = new THREE.DirectionalLight( 0x55505a, 1 );
dirLight.position.set( 0, 3, 0 );
dirLight.castShadow = true;
dirLight.shadow.camera.near = 1;
dirLight.shadow.camera.far = 10;
dirLight.shadow.camera.right = 1;
dirLight.shadow.camera.left = - 1;
dirLight.shadow.camera.top = 1;
dirLight.shadow.camera.bottom = - 1;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
threeScene.add( dirLight );
// Geometry
var ground = new THREE.Mesh(
new THREE.PlaneBufferGeometry( 20, 20, 1, 1 ),
new THREE.MeshPhongMaterial( { color: 0xa0adaf, shininess: 150 } )
);
ground.rotation.x = - Math.PI / 2; // rotates X/Y to X/Z
ground.receiveShadow = true;
threeScene.add( ground );
var helper = new THREE.GridHelper( 20, 20 );
helper.material.opacity = 1.0;
helper.material.transparent = true;
helper.position.set(0, 0.002, 0);
threeScene.add( helper );
// Renderer
renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( 0.8 * window.innerWidth, 0.8 * window.innerHeight );
window.addEventListener( 'resize', onWindowResize, false );
container.appendChild( renderer.domElement );
// Camera
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 100);
camera.position.set(0, 2, 4);
camera.updateMatrixWorld();
threeScene.add( camera );
cameraControl = new THREE.OrbitControls(camera, renderer.domElement);
cameraControl.zoomSpeed = 2.0;
cameraControl.panSpeed = 0.4;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function run() {
var button = document.getElementById('buttonRun');
if (physicsScene.paused)
button.innerHTML = "Stop";
else
button.innerHTML = "Run";
physicsScene.paused = !physicsScene.paused;
}
function restart() {
location.reload();
}
// make browser to call us repeatedly -----------------------------------
function update() {
simulate();
renderer.render(threeScene, camera);
cameraControl.update();
requestAnimationFrame(update);
}
initThreeScene();
onWindowResize();
initPhysics();
update();
</script>
</body>
</html>