webxr_vr_handinput_pressbutton.html 15 KB

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