forked from lo-th/Oimo.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_worker.html
333 lines (267 loc) · 10.2 KB
/
test_worker.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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Oimo.js worker example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
* { margin: 0; padding: 0; border: 0;}
body { background-color: #585858; overflow: hidden; color: #eeeeee; font-family: monospace; font-size: 12px; }
input{ margin:0; padding:4px; }
#interface{ position: absolute; left:10px; top:10px; width:456px; height:20px; }
#info{ pointer-events:none; position: absolute; left:10px; top:50px; width: 400px; height: 400px; }
</style>
</head>
<body>
<div id='container'></div>
<div id="info">
<a href="https://github.com/lo-th/Oimo.js">Oimo.js</a> web worker example
</div>
<script src="js/three.min.js"></script>
<script src="js/BufferGeometryUtils.js"></script>
<script src="js/Detector.js"></script>
<!-- Worker script, will be run in separate thread -->
<script id="worker1" type="javascript/worker">
var world;
var body = [];
self.onmessage = function(e) {
if (e.data.oimoUrl && !world) {
// Load cannon.js
importScripts(e.data.oimoUrl);
// Init physics
OIMO.WORLD_SCALE = 1;
OIMO.INV_SCALE = 1;
world = new OIMO.World(e.data.dt, 2, 8);
world.gravity.init(0,-10,0);
// Ground plane
var ground = new OIMO.Body({size:[400, 40, 400], pos:[0,-20,0], world:world});
var N = e.data.N;
for(var i=0; i!==N; i++){
if(N < N*0.5) body[i] = new OIMO.Body({type:'sphere', size:[0.25], pos:[Math.random()-0.5,(0.5*i)+0.5,Math.random()-0.5], move:true, world:world});
else body[i] = new OIMO.Body({type:'box', size:[0.5,0.5,0.5], pos:[1+Math.random()-0.5,((0.5*i)+0.5),Math.random()-0.5], move:true, world:world});
}
}
// Step the world
world.step();
// Copy over the data to the buffers
var matrixs = e.data.matrixs;
var b=world.rigidBodies;
var m, j, i=0;
while(b!==null){
if(b.type === 0x1){
m = b.getMatrix();
j = 16;
while(j--) matrixs[(16*i) + j] = m[j];
i++;
}
b=b.next;
}
/* var matrixs = e.data.matrixs;
var i = body.length;
var m, j;
while(i--){
m = body[i].getMatrix();
j = 16;
while(j--) matrixs[(16*i) + j] = m[j];
}*/
// Send data back to the main thread
self.postMessage({ perf:world.performance.fpsint, matrixs:matrixs }, [matrixs.buffer]);
};
</script>
<script>
// Parameters
var dt = 1/60, N=500;
var ToRad = Math.PI / 180;
var info = document.getElementById("info");
// navigation var
var camPos = { horizontal: 90, vertical: 30, distance: 100, automove: false };
var mouse = { ox:0, oy:0, h:0, v:0, mx:0, my:0, down:false, over:false, moving:true };
var fps=0, time, time_prev=0, fpsint = 0;
// Data arrays. Contains all our kinematic data we need for rendering.
var matrixs = new Float32Array(N*16);
var oimoInfo = 0;
// Create a blob for the inline worker code
var blob = new Blob([document.querySelector('#worker1').textContent]);
// Create worker
var worker = new Worker(window.URL.createObjectURL(blob));
worker.postMessage = worker.webkitPostMessage || worker.postMessage;
var sendTime; // Time when we sent last message
worker.onmessage = function(e) {
oimoInfo = e.data.perf;
// Get fresh data from the worker
matrixs = e.data.matrixs;
// Update rendering meshes
i = meshes.length;
while(i--){
var m = [];
var mtx = new THREE.Matrix4();
j = 16;
while(j--) m[j] = matrixs[16*i + j];
mtx.fromArray( m );
meshes[i].position.setFromMatrixPosition( mtx )
meshes[i].rotation.setFromRotationMatrix( mtx );
}
// If the worker was faster than the time step (dt seconds), we want to delay the next timestep
var delay = dt * 1000 - (Date.now()-sendTime);
if(delay < 0){
delay = 0;
}
setTimeout(sendDataToWorker,delay);
}
function sendDataToWorker(){
sendTime = Date.now();
worker.postMessage({
N : N,
dt : dt,
oimoUrl : document.location.href.replace(/\/[^/]*$/,"/") + "build/Oimo.js",
matrixs : matrixs,
},[matrixs.buffer]);
}
// Initialize Three.js
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, camera, scene, renderer;
var meshes=[];
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer( {precision: "mediump", antialias: false } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xbcbcbc, 1 );
container = document.getElementById("container");
container.appendChild( renderer.domElement );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMapEnabled = true;
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 0.5, 10000 );
camera.position.set( 0, 30, 100 );
center = new THREE.Vector3();
moveCamera();
scene.add( camera );
// lights
var light, materials;
scene.add( new THREE.AmbientLight( 0x666666 ) );
light = new THREE.DirectionalLight( 0xffffff, 1.75 );
var d = 40;
light.position.set( d, d, d );
light.castShadow = true;
//light.shadowCameraVisible = true;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowCameraFar = 3*d;
light.shadowCameraNear = d;
light.shadowDarkness = 0.5;
scene.add( light );
var material = new THREE.MeshLambertMaterial( { color: 0x777777 } );
var cubeMaterial = new THREE.MeshPhongMaterial( { color: 0xCC8888 } );
var sphereMaterial = new THREE.MeshPhongMaterial( { color: 0x8888CC } );
geometry = THREE.BufferGeometryUtils.fromGeometry( new THREE.PlaneGeometry( 400, 400, 1, 1 ) );
var mesh = new THREE.Mesh( geometry, material );
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.rotation.x = -90 * ToRad;
scene.add( mesh );
// cubes
var cubeGeo = THREE.BufferGeometryUtils.fromGeometry(new THREE.CubeGeometry( 0.5, 0.5, 0.5, 1, 1, 1));
for(var i=0; i<N*0.5; i++){
mesh = new THREE.Mesh( cubeGeo, cubeMaterial );
mesh.castShadow = true;
meshes.push(mesh);
scene.add( mesh );
}
// cubes
var sphereGeo = THREE.BufferGeometryUtils.fromGeometry(new THREE.SphereGeometry( 0.25, 16, 8));
for(var i=0; i<N*0.5; i++){
mesh = new THREE.Mesh( sphereGeo, sphereMaterial );
mesh.castShadow = true;
meshes.push(mesh);
scene.add( mesh );
}
window.addEventListener( 'resize', onWindowResize, false );
container.addEventListener( 'mousemove', onMouseMove, false );
container.addEventListener( 'mousedown', onMouseDown, false );
container.addEventListener( 'mouseout', onMouseUp, false );
container.addEventListener( 'mouseup', onMouseUp, false );
container.addEventListener( 'mousewheel', onMouseWheel, false );
container.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
displayInfo();
}
function displayInfo(){
time = Date.now();
if (time - 1000 > time_prev) {
time_prev = time; fpsint = fps; fps = 0;
} fps++;
var info =[
"Oimo.js DEV.1.1.0a<br><br>",
"Physics: " + oimoInfo +" fps<br>",
"Render: " + fpsint +" fps<br>"
].join("\n");
document.getElementById("info").innerHTML = info;
}
function render() {
renderer.render( scene, camera );
}
// MATH
function Orbit(origine, horizontal, vertical, distance) {
var p = new THREE.Vector3();
var phi = vertical*ToRad;
var theta = horizontal*ToRad;
p.x = (distance * Math.sin(phi) * Math.cos(theta)) + origine.x;
p.z = (distance * Math.sin(phi) * Math.sin(theta)) + origine.z;
p.y = (distance * Math.cos(phi)) + origine.y;
return p;
}
// MOUSE & NAVIGATION
function moveCamera() {
camera.position.copy(Orbit(center, camPos.horizontal, camPos.vertical, camPos.distance));
camera.lookAt(center);
}
function onMouseDown(e) {
e.preventDefault();
mouse.ox = e.clientX;
mouse.oy = e.clientY;
mouse.h = camPos.horizontal;
mouse.v = camPos.vertical;
mouse.down = true;
}
function onMouseUp(e) {
mouse.down = false;
document.body.style.cursor = 'auto';
}
function onMouseMove(e) {
e.preventDefault();
if (mouse.down ) {
document.body.style.cursor = 'move';
camPos.horizontal = ((e.clientX - mouse.ox) * 0.3) + mouse.h;
camPos.vertical = (-(e.clientY - mouse.oy) * 0.3) + mouse.v;
moveCamera();
}
}
function onMouseWheel(e) {
var delta = 0;
if(e.wheelDeltaY){delta=e.wheelDeltaY*0.01;}
else if(e.wheelDelta){delta=e.wheelDelta*0.05;}
else if(e.detail){delta=-e.detail*1.0;}
camPos.distance-=(delta*10);
moveCamera();
}
// Start the worker!
sendDataToWorker();
</script>
</body>
</html>