This repository has been archived by the owner on Jan 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
hands_ml.html
403 lines (343 loc) · 14.8 KB
/
hands_ml.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
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#008000"/>
<title>hands_ml</title>
<link rel="manifest" href="hands_ml_manifest.json">
<script>
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('/hands_ml_sw.js')
.then(function() {
console.log('Service Worker Registered');
});
}
</script>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<h1>hands_ml.html example</h1>
<script src="three.js"></script>
<script>
let container, scene, camera, session;
// let handTracker;
function init() {
container = document.createElement('div');
document.body.appendChild(container);
scene = new THREE.Scene();
scene.matrixAutoUpdate = false;
// scene.background = new THREE.Color(0x3B3961);
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
// camera.position.set(0, 1, 0);
scene.add(camera);
const ambientLight = new THREE.AmbientLight(0x808080);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
const localVector = new THREE.Vector3();
const localVector2 = new THREE.Vector3();
const localQuaternion = new THREE.Quaternion();
const localMatrix = new THREE.Matrix4();
const pointerGeometry = (() => {
const geometries = [
new THREE.CylinderBufferGeometry(0.001, 0.001, 1, 32, 1)
.applyMatrix(localMatrix.makeTranslation(0, 1/2, 0))
.applyMatrix(localMatrix.makeRotationFromQuaternion(
localQuaternion.setFromUnitVectors(
localVector.set(0, 1, 0),
localVector2.set(0, 0, -1)
)
)),
new THREE.BoxBufferGeometry(0.001, 0.1, 0.001)
.applyMatrix(localMatrix.makeTranslation(0, 0.1/2, 0)),
];
const positions = (() => {
let numPositions = 0;
for (let i = 0; i < geometries.length; i++) {
numPositions += geometries[i].attributes.position.array.length;
}
const positions = new Float32Array(numPositions);
let positionIndex = 0;
for (let i = 0; i < geometries.length; i++) {
const geometry = geometries[i];
positions.set(geometry.attributes.position.array, positionIndex);
positionIndex += geometry.attributes.position.array.length;
}
return positions;
})();
const normals = (() => {
let numNormals = 0;
for (let i = 0; i < geometries.length; i++) {
numNormals += geometries[i].attributes.normal.array.length;
}
const normals = new Float32Array(numNormals);
let normalIndex = 0;
for (let i = 0; i < geometries.length; i++) {
const geometry = geometries[i];
normals.set(geometry.attributes.normal.array, normalIndex);
normalIndex += geometry.attributes.normal.array.length;
}
return normals;
})();
const indices = (() => {
let numIndices = 0;
for (let i = 0; i < geometries.length; i++) {
numIndices += geometries[i].index.array.length;
}
const indices = new Uint16Array(numIndices);
let indexIndex = 0;
let positionIndex = 0;
for (let i = 0; i < geometries.length; i++) {
const geometry = geometries[i];
indices.set(geometry.index.array, indexIndex);
const positionOffset = positionIndex / 3;
for (let j = 0; j < geometry.index.array.length; j++) {
indices[indexIndex + j] += positionOffset;
}
indexIndex += geometry.index.array.length;
positionIndex += geometry.attributes.position.array.length;
}
return indices;
})();
const geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('normal', new THREE.BufferAttribute(normals, 3));
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
return geometry;
})();
const boneGeometry = new THREE.BoxBufferGeometry(0.01, 0.01, 0.01);
const handMaterial = new THREE.MeshPhongMaterial({
color: 0xFF0000,
});
const _makeHandMesh = i => {
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(boneGeometry.attributes.position.array.length * 2 * 6 * 4 + pointerGeometry.attributes.position.array.length * 2);
const positionAttribute = new THREE.BufferAttribute(positions, 3);
geometry.addAttribute('position', positionAttribute);
const normals = new Float32Array(boneGeometry.attributes.normal.array.length * 2 * 6 * 4 + pointerGeometry.attributes.normal.array.length * 2);
const normalAttribute = new THREE.BufferAttribute(normals, 3);
geometry.addAttribute('normal', normalAttribute);
const indices = new Uint16Array(boneGeometry.index.array.length * 2 * 6 * 4 + pointerGeometry.index.array.length * 2);
const indexAttribute = new THREE.BufferAttribute(indices, 1);
geometry.setIndex(indexAttribute);
const mesh = new THREE.Mesh(geometry, handMaterial);
mesh.update = frame => {
if (session && frame) {
const handInputSources = session.getInputSources().filter(inputSource => inputSource.targetRayMode === 'hand');
// console.log('got hand input sources', handInputSources.length);
if (handInputSources.length > 0) {
const inputSource = handInputSources[i];
if (inputSource.connected) {
let positionIndex = 0;
let normalIndex = 0;
let indexIndex = 0;
const _shiftIndex = array => {
for (let l = 0; l < array.length; l++) {
array[l] += positionIndex / 3;
}
};
const pose = frame.getPose(inputSource.targetRaySpace);
const {wrist, fingers} = inputSource;
const allFingers = [wrist].concat(fingers);
for (let j = 0; j < allFingers.length; j++) {
const bones = allFingers[j];
for (let k = 0; k < bones.length; k++) {
const positionFloat32Array = bones[k];
if (positionFloat32Array && isFinite(positionFloat32Array[0])) {
const newGeometry = boneGeometry.clone()
.applyMatrix(
localMatrix.makeTranslation(positionFloat32Array[0], positionFloat32Array[1], positionFloat32Array[2])
);
_shiftIndex(newGeometry.index.array);
positions.set(newGeometry.attributes.position.array, positionIndex);
positionIndex += newGeometry.attributes.position.array.length;
normals.set(newGeometry.attributes.normal.array, normalIndex);
normalIndex += newGeometry.attributes.normal.array.length;
indices.set(newGeometry.index.array, indexIndex);
indexIndex += newGeometry.index.array.length;
}
}
}
/* if (pointer) {
const newGeometry = pointerGeometry.clone()
.applyMatrix(
localMatrix
.compose(
localVector.fromArray(pointer.position),
localQuaternion.fromArray(pointer.rotation),
localVector2.set(1, 1, 1),
)
);
_shiftIndex(newGeometry.index.array);
positions.set(newGeometry.attributes.position.array, positionIndex);
positionIndex += newGeometry.attributes.position.array.length;
normals.set(newGeometry.attributes.normal.array, normalIndex);
normalIndex += newGeometry.attributes.normal.array.length;
indices.set(newGeometry.index.array, indexIndex);
indexIndex += newGeometry.index.array.length;
}
if (grip) {
const newGeometry = pointerGeometry.clone()
.applyMatrix(
localMatrix
.compose(
localVector.fromArray(grip.position),
localQuaternion.fromArray(grip.rotation),
localVector2.set(1, 1, 1),
)
);
_shiftIndex(newGeometry.index.array);
positions.set(newGeometry.attributes.position.array, positionIndex);
positionIndex += newGeometry.attributes.position.array.length;
normals.set(newGeometry.attributes.normal.array, normalIndex);
normalIndex += newGeometry.attributes.normal.array.length;
indices.set(newGeometry.index.array, indexIndex);
indexIndex += newGeometry.index.array.length;
} */
positionAttribute.needsUpdate = true;
indexAttribute.needsUpdate = true;
geometry.setDrawRange(0, indexIndex);
mesh.matrix.fromArray(pose.transform.inverse.matrix);
mesh.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);
mesh.updateMatrixWorld(true);
mesh.visible = true;
} else {
mesh.visible = false;
}
} else {
mesh.visible = false;
}
} else {
mesh.visible = false;
}
};
mesh.visible = false;
mesh.frustumCulled = false;
return mesh;
};
handMeshes = [
_makeHandMesh(0),
_makeHandMesh(1),
];
for (let i = 0; i < handMeshes.length; i++) {
scene.add(handMeshes[i]);
}
/* const _onHands = hands => {
handMesh.update(hands);
for (let i = 0; i < hands.length; i++) {
const hand = hands[i];
const handIndex = hand.hand === 'left' ? 0 : 1;
if (lastPincheds[handIndex]) {
const handSpec = hand.pointer || hand.grip || null;
if (handSpec) {
const pinchedObject = pinchedObjects[handIndex];
const pinchedObjectStart = pinchedObjectStarts[handIndex];
pinchedObject.position.fromArray(handSpec.position);
pinchedObject.quaternion
.copy(pinchedObjectStart.rotation)
.inverse()
.premultiply(localQuaternion.fromArray(handSpec.rotation));
pinchedObject.matrix.compose(pinchedObject.position, pinchedObject.quaternion, pinchedObject.scale)
pinchedObject.updateMatrixWorld(true);
}
}
}
}; */
const objectGeometry = new THREE.BoxBufferGeometry(0.1, 0.2, 0.001);
const objectMaterial = new THREE.MeshPhongMaterial({
color: 0x0000FF,
});
const lastPincheds = [false, false];
const _makePinchedObject = () => {
const mesh = new THREE.Mesh(objectGeometry, objectMaterial);
mesh.frustumCulled = false;
mesh.matrixAutoUpdate = false;
mesh.visible = false;
return mesh;
};
const pinchedObjects = [
_makePinchedObject(),
_makePinchedObject(),
];
const pinchedObjectStarts = [
{position: new THREE.Vector3(), rotation: new THREE.Quaternion()},
{position: new THREE.Vector3(), rotation: new THREE.Quaternion()},
];
const _onGesture = e => {
const {hand, gesture, lastGesture, position, rotation} = e;
console.log('got gesture', {hand, gesture, lastGesture});
const pinched = gesture === 'pinch';
const handIndex = hand === 'left' ? 0 : 1;
const lastPinched = lastPincheds[handIndex];
if (pinched && !lastPinched) {
const pinchedObject = pinchedObjects[handIndex];
pinchedObject.position.fromArray(position);
pinchedObject.quaternion.fromArray(rotation);
pinchedObject.matrix.compose(pinchedObject.position, pinchedObject.quaternion, pinchedObject.scale);
pinchedObject.updateMatrixWorld(true);
pinchedObject.visible = true;
scene.add(pinchedObject);
const pinchedObjectStart = pinchedObjectStarts[handIndex];
pinchedObjectStart.position.fromArray(position);
pinchedObjectStart.rotation.fromArray(rotation);
}
lastPincheds[handIndex] = pinched;
};
/* handTracker.onhands = _onHands;
handTracker.ongesture = _onGesture; */
// handMesh.visible = true;
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// window.browser.magicleap.RequestDepthPopulation(true);
// renderer.autoClear = false;
container.appendChild(renderer.domElement);
renderer.setAnimationLoop(animate);
}
function animate(time, frame) {
for (let i = 0; i < handMeshes.length; i++) {
handMeshes[i].update(frame);
}
renderer.render(scene, renderer.vr.enabled ? renderer.vr.getCamera(camera) : camera);
}
init();
(async () => {
console.log('request session');
session = await navigator.xr.requestSession({
exclusive: true,
extensions: {
handTracking: true,
},
}).catch(err => Promise.resolve(null));
if (session) {
// console.log('request first frame');
session.requestAnimationFrame((timestamp, frame) => {
renderer.vr.setSession(session, {
frameOfReferenceType: 'stage',
});
const {views} = frame.getViewerPose();
const viewport = session.baseLayer.getViewport(views[0]);
const width = viewport.width;
const height = viewport.height;
renderer.setSize(width * 2, height);
renderer.setAnimationLoop(null);
renderer.vr.enabled = true;
renderer.vr.setAnimationLoop(animate);
console.log('running!');
});
} else {
console.log('no xr devices');
}
})();
</script>
</body>
</html>