webxr_vr_handinput_pressbutton.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js vr - handinput - press button</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> vr - handinput - press button<br />
  12. (Oculus Browser 15.1+)
  13. </div>
  14. <!-- Import maps polyfill -->
  15. <!-- Remove this when import maps will be widely supported -->
  16. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.module.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import { VRButton } from 'three/addons/webxr/VRButton.js';
  28. import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
  29. import { OculusHandModel } from 'three/addons/webxr/OculusHandModel.js';
  30. import { createText } from 'three/addons/webxr/Text2D.js';
  31. import { World, System, Component, TagComponent, Types } from 'three/addons/libs/ecsy.module.js';
  32. THREE.ColorManagement.enabled = false; // TODO: Consider enabling color management.
  33. class Object3D extends Component { }
  34. Object3D.schema = {
  35. object: { type: Types.Ref }
  36. };
  37. class Button extends Component { }
  38. Button.schema = {
  39. // button states: [resting, pressed, fully_pressed, recovering]
  40. currState: { type: Types.String, default: 'resting' },
  41. prevState: { type: Types.String, default: 'resting' },
  42. pressSound: { type: Types.Ref, default: null },
  43. releaseSound: { type: Types.Ref, default: null },
  44. restingY: { type: Types.Number, default: null },
  45. surfaceY: { type: Types.Number, default: null },
  46. recoverySpeed: { type: Types.Number, default: 0.4 },
  47. fullPressDistance: { type: Types.Number, default: null },
  48. action: { type: Types.Ref, default: () => { } }
  49. };
  50. class ButtonSystem extends System {
  51. init( attributes ) {
  52. this.renderer = attributes.renderer;
  53. this.soundAdded = false;
  54. }
  55. execute( /*delta, time*/ ) {
  56. let buttonPressSound, buttonReleaseSound;
  57. if ( this.renderer.xr.getSession() && ! this.soundAdded ) {
  58. const xrCamera = this.renderer.xr.getCamera();
  59. const listener = new THREE.AudioListener();
  60. xrCamera.add( listener );
  61. // create a global audio source
  62. buttonPressSound = new THREE.Audio( listener );
  63. buttonReleaseSound = new THREE.Audio( listener );
  64. // load a sound and set it as the Audio object's buffer
  65. const audioLoader = new THREE.AudioLoader();
  66. audioLoader.load( 'sounds/button-press.ogg', function ( buffer ) {
  67. buttonPressSound.setBuffer( buffer );
  68. } );
  69. audioLoader.load( 'sounds/button-release.ogg', function ( buffer ) {
  70. buttonReleaseSound.setBuffer( buffer );
  71. } );
  72. this.soundAdded = true;
  73. }
  74. this.queries.buttons.results.forEach( entity => {
  75. const button = entity.getMutableComponent( Button );
  76. const buttonMesh = entity.getComponent( Object3D ).object;
  77. // populate restingY
  78. if ( button.restingY == null ) {
  79. button.restingY = buttonMesh.position.y;
  80. }
  81. if ( buttonPressSound ) {
  82. button.pressSound = buttonPressSound;
  83. }
  84. if ( buttonReleaseSound ) {
  85. button.releaseSound = buttonReleaseSound;
  86. }
  87. if ( button.currState == 'fully_pressed' && button.prevState != 'fully_pressed' ) {
  88. if ( button.pressSound ) button.pressSound.play();
  89. button.action();
  90. }
  91. if ( button.currState == 'recovering' && button.prevState != 'recovering' ) {
  92. if ( button.releaseSound ) button.releaseSound.play();
  93. }
  94. // preserve prevState, clear currState
  95. // FingerInputSystem will update currState
  96. button.prevState = button.currState;
  97. button.currState = 'resting';
  98. } );
  99. }
  100. }
  101. ButtonSystem.queries = {
  102. buttons: {
  103. components: [ Button ]
  104. }
  105. };
  106. class Pressable extends TagComponent { }
  107. class FingerInputSystem extends System {
  108. init( attributes ) {
  109. this.hands = attributes.hands;
  110. }
  111. execute( delta/*, time*/ ) {
  112. this.queries.pressable.results.forEach( entity => {
  113. const button = entity.getMutableComponent( Button );
  114. const object = entity.getComponent( Object3D ).object;
  115. const pressingDistances = [];
  116. this.hands.forEach( hand => {
  117. if ( hand && hand.intersectBoxObject( object ) ) {
  118. const pressingPosition = hand.getPointerPosition();
  119. pressingDistances.push( button.surfaceY - object.worldToLocal( pressingPosition ).y );
  120. }
  121. } );
  122. if ( pressingDistances.length == 0 ) { // not pressed this frame
  123. if ( object.position.y < button.restingY ) {
  124. object.position.y += button.recoverySpeed * delta;
  125. button.currState = 'recovering';
  126. } else {
  127. object.position.y = button.restingY;
  128. button.currState = 'resting';
  129. }
  130. } else {
  131. button.currState = 'pressed';
  132. const pressingDistance = Math.max( pressingDistances );
  133. if ( pressingDistance > 0 ) {
  134. object.position.y -= pressingDistance;
  135. }
  136. if ( object.position.y <= button.restingY - button.fullPressDistance ) {
  137. button.currState = 'fully_pressed';
  138. object.position.y = button.restingY - button.fullPressDistance;
  139. }
  140. }
  141. } );
  142. }
  143. }
  144. FingerInputSystem.queries = {
  145. pressable: {
  146. components: [ Pressable ]
  147. }
  148. };
  149. class Rotating extends TagComponent { }
  150. class RotatingSystem extends System {
  151. execute( delta/*, time*/ ) {
  152. this.queries.rotatingObjects.results.forEach( entity => {
  153. const object = entity.getComponent( Object3D ).object;
  154. object.rotation.x += 0.4 * delta;
  155. object.rotation.y += 0.4 * delta;
  156. } );
  157. }
  158. }
  159. RotatingSystem.queries = {
  160. rotatingObjects: {
  161. components: [ Rotating ]
  162. }
  163. };
  164. class HandsInstructionText extends TagComponent { }
  165. class InstructionSystem extends System {
  166. init( attributes ) {
  167. this.controllers = attributes.controllers;
  168. }
  169. execute( /*delta, time*/ ) {
  170. let visible = false;
  171. this.controllers.forEach( controller => {
  172. if ( controller.visible ) {
  173. visible = true;
  174. }
  175. } );
  176. this.queries.instructionTexts.results.forEach( entity => {
  177. const object = entity.getComponent( Object3D ).object;
  178. object.visible = visible;
  179. } );
  180. }
  181. }
  182. InstructionSystem.queries = {
  183. instructionTexts: {
  184. components: [ HandsInstructionText ]
  185. }
  186. };
  187. class OffsetFromCamera extends Component { }
  188. OffsetFromCamera.schema = {
  189. x: { type: Types.Number, default: 0 },
  190. y: { type: Types.Number, default: 0 },
  191. z: { type: Types.Number, default: 0 },
  192. };
  193. class NeedCalibration extends TagComponent { }
  194. class CalibrationSystem extends System {
  195. init( attributes ) {
  196. this.camera = attributes.camera;
  197. this.renderer = attributes.renderer;
  198. }
  199. execute( /*delta, time*/ ) {
  200. this.queries.needCalibration.results.forEach( entity => {
  201. if ( this.renderer.xr.getSession() ) {
  202. const offset = entity.getComponent( OffsetFromCamera );
  203. const object = entity.getComponent( Object3D ).object;
  204. const xrCamera = this.renderer.xr.getCamera();
  205. object.position.x = xrCamera.position.x + offset.x;
  206. object.position.y = xrCamera.position.y + offset.y;
  207. object.position.z = xrCamera.position.z + offset.z;
  208. entity.removeComponent( NeedCalibration );
  209. }
  210. } );
  211. }
  212. }
  213. CalibrationSystem.queries = {
  214. needCalibration: {
  215. components: [ NeedCalibration ]
  216. }
  217. };
  218. const world = new World();
  219. const clock = new THREE.Clock();
  220. let camera, scene, renderer;
  221. init();
  222. animate();
  223. function makeButtonMesh( x, y, z, color ) {
  224. const geometry = new THREE.BoxGeometry( x, y, z );
  225. const material = new THREE.MeshPhongMaterial( { color: color } );
  226. const buttonMesh = new THREE.Mesh( geometry, material );
  227. buttonMesh.castShadow = true;
  228. buttonMesh.receiveShadow = true;
  229. return buttonMesh;
  230. }
  231. function init() {
  232. const container = document.createElement( 'div' );
  233. document.body.appendChild( container );
  234. scene = new THREE.Scene();
  235. scene.background = new THREE.Color( 0x444444 );
  236. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 10 );
  237. camera.position.set( 0, 1.2, 0.3 );
  238. scene.add( new THREE.HemisphereLight( 0x808080, 0x606060 ) );
  239. const light = new THREE.DirectionalLight( 0xffffff );
  240. light.position.set( 0, 6, 0 );
  241. light.castShadow = true;
  242. light.shadow.camera.top = 2;
  243. light.shadow.camera.bottom = - 2;
  244. light.shadow.camera.right = 2;
  245. light.shadow.camera.left = - 2;
  246. light.shadow.mapSize.set( 4096, 4096 );
  247. scene.add( light );
  248. renderer = new THREE.WebGLRenderer( { antialias: true } );
  249. renderer.setPixelRatio( window.devicePixelRatio );
  250. renderer.setSize( window.innerWidth, window.innerHeight );
  251. renderer.shadowMap.enabled = true;
  252. renderer.xr.enabled = true;
  253. renderer.xr.cameraAutoUpdate = false;
  254. container.appendChild( renderer.domElement );
  255. document.body.appendChild( VRButton.createButton( renderer ) );
  256. // controllers
  257. const controller1 = renderer.xr.getController( 0 );
  258. scene.add( controller1 );
  259. const controller2 = renderer.xr.getController( 1 );
  260. scene.add( controller2 );
  261. const controllerModelFactory = new XRControllerModelFactory();
  262. // Hand 1
  263. const controllerGrip1 = renderer.xr.getControllerGrip( 0 );
  264. controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
  265. scene.add( controllerGrip1 );
  266. const hand1 = renderer.xr.getHand( 0 );
  267. const handModel1 = new OculusHandModel( hand1 );
  268. hand1.add( handModel1 );
  269. scene.add( hand1 );
  270. // Hand 2
  271. const controllerGrip2 = renderer.xr.getControllerGrip( 1 );
  272. controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
  273. scene.add( controllerGrip2 );
  274. const hand2 = renderer.xr.getHand( 1 );
  275. const handModel2 = new OculusHandModel( hand2 );
  276. hand2.add( handModel2 );
  277. scene.add( hand2 );
  278. // buttons
  279. const floorGeometry = new THREE.PlaneGeometry( 4, 4 );
  280. const floorMaterial = new THREE.MeshPhongMaterial( { color: 0x222222 } );
  281. const floor = new THREE.Mesh( floorGeometry, floorMaterial );
  282. floor.rotation.x = - Math.PI / 2;
  283. floor.receiveShadow = true;
  284. scene.add( floor );
  285. const consoleGeometry = new THREE.BoxGeometry( 0.5, 0.12, 0.15 );
  286. const consoleMaterial = new THREE.MeshPhongMaterial( { color: 0x595959 } );
  287. const consoleMesh = new THREE.Mesh( consoleGeometry, consoleMaterial );
  288. consoleMesh.position.set( 0, 1, - 0.3 );
  289. consoleMesh.castShadow = true;
  290. consoleMesh.receiveShadow = true;
  291. scene.add( consoleMesh );
  292. const orangeButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xffd3b5 );
  293. orangeButton.position.set( - 0.15, 0.04, 0 );
  294. consoleMesh.add( orangeButton );
  295. const pinkButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xe84a5f );
  296. pinkButton.position.set( - 0.05, 0.04, 0 );
  297. consoleMesh.add( pinkButton );
  298. const resetButton = makeButtonMesh( 0.08, 0.1, 0.08, 0x355c7d );
  299. const resetButtonText = createText( 'reset', 0.03 );
  300. resetButton.add( resetButtonText );
  301. resetButtonText.rotation.x = - Math.PI / 2;
  302. resetButtonText.position.set( 0, 0.051, 0 );
  303. resetButton.position.set( 0.05, 0.04, 0 );
  304. consoleMesh.add( resetButton );
  305. const exitButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xff0000 );
  306. const exitButtonText = createText( 'exit', 0.03 );
  307. exitButton.add( exitButtonText );
  308. exitButtonText.rotation.x = - Math.PI / 2;
  309. exitButtonText.position.set( 0, 0.051, 0 );
  310. exitButton.position.set( 0.15, 0.04, 0 );
  311. consoleMesh.add( exitButton );
  312. const tkGeometry = new THREE.TorusKnotGeometry( 0.5, 0.2, 200, 32 );
  313. const tkMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff } );
  314. tkMaterial.metalness = 0.8;
  315. const torusKnot = new THREE.Mesh( tkGeometry, tkMaterial );
  316. torusKnot.position.set( 0, 1, - 5 );
  317. scene.add( torusKnot );
  318. const instructionText = createText( 'This is a WebXR Hands demo, please explore with hands.', 0.04 );
  319. instructionText.position.set( 0, 1.6, - 0.6 );
  320. scene.add( instructionText );
  321. const exitText = createText( 'Exiting session...', 0.04 );
  322. exitText.position.set( 0, 1.5, - 0.6 );
  323. exitText.visible = false;
  324. scene.add( exitText );
  325. world
  326. .registerComponent( Object3D )
  327. .registerComponent( Button )
  328. .registerComponent( Pressable )
  329. .registerComponent( Rotating )
  330. .registerComponent( HandsInstructionText )
  331. .registerComponent( OffsetFromCamera )
  332. .registerComponent( NeedCalibration );
  333. world
  334. .registerSystem( RotatingSystem )
  335. .registerSystem( InstructionSystem, { controllers: [ controllerGrip1, controllerGrip2 ] } )
  336. .registerSystem( CalibrationSystem, { renderer: renderer, camera: camera } )
  337. .registerSystem( ButtonSystem, { renderer: renderer, camera: camera } )
  338. .registerSystem( FingerInputSystem, { hands: [ handModel1, handModel2 ] } );
  339. const csEntity = world.createEntity();
  340. csEntity.addComponent( OffsetFromCamera, { x: 0, y: - 0.4, z: - 0.3 } );
  341. csEntity.addComponent( NeedCalibration );
  342. csEntity.addComponent( Object3D, { object: consoleMesh } );
  343. const obEntity = world.createEntity();
  344. obEntity.addComponent( Pressable );
  345. obEntity.addComponent( Object3D, { object: orangeButton } );
  346. const obAction = function () {
  347. torusKnot.material.color.setHex( 0xffd3b5 );
  348. };
  349. obEntity.addComponent( Button, { action: obAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  350. const pbEntity = world.createEntity();
  351. pbEntity.addComponent( Pressable );
  352. pbEntity.addComponent( Object3D, { object: pinkButton } );
  353. const pbAction = function () {
  354. torusKnot.material.color.setHex( 0xe84a5f );
  355. };
  356. pbEntity.addComponent( Button, { action: pbAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  357. const rbEntity = world.createEntity();
  358. rbEntity.addComponent( Pressable );
  359. rbEntity.addComponent( Object3D, { object: resetButton } );
  360. const rbAction = function () {
  361. torusKnot.material.color.setHex( 0xffffff );
  362. };
  363. rbEntity.addComponent( Button, { action: rbAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  364. const ebEntity = world.createEntity();
  365. ebEntity.addComponent( Pressable );
  366. ebEntity.addComponent( Object3D, { object: exitButton } );
  367. const ebAction = function () {
  368. exitText.visible = true;
  369. setTimeout( function () {
  370. exitText.visible = false; renderer.xr.getSession().end();
  371. }, 2000 );
  372. };
  373. ebEntity.addComponent( Button, { action: ebAction, surfaceY: 0.05, recoverySpeed: 0.2, fullPressDistance: 0.03 } );
  374. const tkEntity = world.createEntity();
  375. tkEntity.addComponent( Rotating );
  376. tkEntity.addComponent( Object3D, { object: torusKnot } );
  377. const itEntity = world.createEntity();
  378. itEntity.addComponent( HandsInstructionText );
  379. itEntity.addComponent( Object3D, { object: instructionText } );
  380. window.addEventListener( 'resize', onWindowResize );
  381. }
  382. function onWindowResize() {
  383. camera.aspect = window.innerWidth / window.innerHeight;
  384. camera.updateProjectionMatrix();
  385. renderer.setSize( window.innerWidth, window.innerHeight );
  386. }
  387. function animate() {
  388. renderer.setAnimationLoop( render );
  389. }
  390. function render() {
  391. const delta = clock.getDelta();
  392. const elapsedTime = clock.elapsedTime;
  393. renderer.xr.updateCamera( camera );
  394. world.execute( delta, elapsedTime );
  395. renderer.render( scene, camera );
  396. }
  397. </script>
  398. </body>
  399. </html>