webxr-point-to-select.html 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - WebXR - Point to Select</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <script type="module">
  24. import * as THREE from '../../build/three.module.js';
  25. import {VRButton} from '../../examples/jsm/webxr/VRButton.js';
  26. function main() {
  27. const canvas = document.querySelector('#c');
  28. const renderer = new THREE.WebGLRenderer({canvas});
  29. renderer.xr.enabled = true;
  30. document.body.appendChild(VRButton.createButton(renderer));
  31. const fov = 75;
  32. const aspect = 2; // the canvas default
  33. const near = 0.1;
  34. const far = 50;
  35. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  36. camera.position.set(0, 1.6, 0);
  37. const scene = new THREE.Scene();
  38. // object to put pickable objects on so we can easily
  39. // separate them from non-pickable objects
  40. const pickRoot = new THREE.Object3D();
  41. scene.add(pickRoot);
  42. {
  43. const loader = new THREE.CubeTextureLoader();
  44. const texture = loader.load([
  45. 'resources/images/grid-1024.png',
  46. 'resources/images/grid-1024.png',
  47. 'resources/images/grid-1024.png',
  48. 'resources/images/grid-1024.png',
  49. 'resources/images/grid-1024.png',
  50. 'resources/images/grid-1024.png',
  51. ]);
  52. scene.background = texture;
  53. }
  54. {
  55. const color = 0xFFFFFF;
  56. const intensity = 1;
  57. const light = new THREE.DirectionalLight(color, intensity);
  58. light.position.set(-1, 2, 4);
  59. scene.add(light);
  60. }
  61. const boxWidth = 1;
  62. const boxHeight = 1;
  63. const boxDepth = 1;
  64. const boxGeometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  65. const sphereRadius = 0.5;
  66. const sphereGeometry = new THREE.SphereGeometry(sphereRadius);
  67. function makeInstance(geometry, color, x) {
  68. const material = new THREE.MeshPhongMaterial({color});
  69. const cube = new THREE.Mesh(geometry, material);
  70. pickRoot.add(cube);
  71. cube.position.x = x;
  72. cube.position.y = 1.6;
  73. cube.position.z = -2;
  74. return cube;
  75. }
  76. const meshToMeshMap = new Map();
  77. [
  78. { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, },
  79. { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, },
  80. { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, },
  81. ].forEach((info) => {
  82. const {x, boxColor, sphereColor} = info;
  83. const sphere = makeInstance(sphereGeometry, sphereColor, x);
  84. const box = makeInstance(boxGeometry, boxColor, x);
  85. // hide the sphere
  86. sphere.visible = false;
  87. // map the sphere to the box
  88. meshToMeshMap.set(box, sphere);
  89. // map the box to the sphere
  90. meshToMeshMap.set(sphere, box);
  91. });
  92. class ControllerPickHelper extends THREE.EventDispatcher {
  93. constructor(scene) {
  94. super();
  95. this.raycaster = new THREE.Raycaster();
  96. this.objectToColorMap = new Map();
  97. this.controllerToObjectMap = new Map();
  98. this.tempMatrix = new THREE.Matrix4();
  99. const pointerGeometry = new THREE.BufferGeometry().setFromPoints([
  100. new THREE.Vector3(0, 0, 0),
  101. new THREE.Vector3(0, 0, -1),
  102. ]);
  103. this.controllers = [];
  104. for (let i = 0; i < 2; ++i) {
  105. const controller = renderer.xr.getController(i);
  106. controller.addEventListener('select', (event) => {
  107. const controller = event.target;
  108. const selectedObject = this.controllerToObjectMap.get(controller);
  109. if (selectedObject) {
  110. this.dispatchEvent({type: 'select', controller, selectedObject});
  111. }
  112. });
  113. scene.add(controller);
  114. const line = new THREE.Line(pointerGeometry);
  115. line.scale.z = 5;
  116. controller.add(line);
  117. this.controllers.push({controller, line});
  118. }
  119. }
  120. reset() {
  121. // restore the colors
  122. this.objectToColorMap.forEach((color, object) => {
  123. object.material.emissive.setHex(color);
  124. });
  125. this.objectToColorMap.clear();
  126. this.controllerToObjectMap.clear();
  127. }
  128. update(pickablesParent, time) {
  129. this.reset();
  130. for (const {controller, line} of this.controllers) {
  131. // cast a ray through the from the controller
  132. this.tempMatrix.identity().extractRotation(controller.matrixWorld);
  133. this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);
  134. this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix);
  135. // get the list of objects the ray intersected
  136. const intersections = this.raycaster.intersectObjects(pickablesParent.children);
  137. if (intersections.length) {
  138. const intersection = intersections[0];
  139. // make the line touch the object
  140. line.scale.z = intersection.distance;
  141. // pick the first object. It's the closest one
  142. const pickedObject = intersection.object;
  143. // save which object this controller picked
  144. this.controllerToObjectMap.set(controller, pickedObject);
  145. // highlight the object if we haven't already
  146. if (this.objectToColorMap.get(pickedObject) === undefined) {
  147. // save its color
  148. this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex());
  149. // set its emissive color to flashing red/yellow
  150. pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000);
  151. }
  152. } else {
  153. line.scale.z = 5;
  154. }
  155. }
  156. }
  157. }
  158. const pickHelper = new ControllerPickHelper(scene);
  159. pickHelper.addEventListener('select', (event) => {
  160. event.selectedObject.visible = false;
  161. const partnerObject = meshToMeshMap.get(event.selectedObject);
  162. partnerObject.visible = true;
  163. });
  164. function resizeRendererToDisplaySize(renderer) {
  165. const canvas = renderer.domElement;
  166. const width = canvas.clientWidth;
  167. const height = canvas.clientHeight;
  168. const needResize = canvas.width !== width || canvas.height !== height;
  169. if (needResize) {
  170. renderer.setSize(width, height, false);
  171. }
  172. return needResize;
  173. }
  174. function render(time) {
  175. time *= 0.001;
  176. if (resizeRendererToDisplaySize(renderer)) {
  177. const canvas = renderer.domElement;
  178. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  179. camera.updateProjectionMatrix();
  180. }
  181. let ndx = 0;
  182. for (const mesh of meshToMeshMap.keys()) {
  183. const speed = 1 + ndx * .1;
  184. const rot = time * speed;
  185. mesh.rotation.x = rot;
  186. mesh.rotation.y = rot;
  187. ++ndx;
  188. }
  189. pickHelper.update(pickRoot, time);
  190. renderer.render(scene, camera);
  191. }
  192. renderer.setAnimationLoop(render);
  193. }
  194. main();
  195. </script>
  196. </html>