webxr-look-to-select-w-cursor.html 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 - Look to Select w/cursor</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. <!-- Import maps polyfill -->
  24. <!-- Remove this when import maps will be widely supported -->
  25. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../../build/three.module.js",
  30. "three/addons/": "../../examples/jsm/"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three';
  36. import {VRButton} from 'three/addons/webxr/VRButton.js';
  37. function main() {
  38. const canvas = document.querySelector('#c');
  39. const renderer = new THREE.WebGLRenderer({antialias: true, canvas});
  40. renderer.xr.enabled = true;
  41. document.body.appendChild(VRButton.createButton(renderer));
  42. const fov = 75;
  43. const aspect = 2; // the canvas default
  44. const near = 0.1;
  45. const far = 50;
  46. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  47. camera.position.set(0, 1.6, 0);
  48. const scene = new THREE.Scene();
  49. {
  50. const loader = new THREE.CubeTextureLoader();
  51. const texture = loader.load([
  52. 'resources/images/grid-1024.png',
  53. 'resources/images/grid-1024.png',
  54. 'resources/images/grid-1024.png',
  55. 'resources/images/grid-1024.png',
  56. 'resources/images/grid-1024.png',
  57. 'resources/images/grid-1024.png',
  58. ]);
  59. scene.background = texture;
  60. }
  61. {
  62. const color = 0xFFFFFF;
  63. const intensity = 1;
  64. const light = new THREE.DirectionalLight(color, intensity);
  65. light.position.set(-1, 2, 4);
  66. scene.add(light);
  67. }
  68. function makeDataTexture(data, width, height) {
  69. const texture = new THREE.DataTexture(data, width, height, THREE.RGBAFormat);
  70. texture.minFilter = THREE.NearestFilter;
  71. texture.magFilter = THREE.NearestFilter;
  72. texture.needsUpdate = true;
  73. return texture;
  74. }
  75. const boxWidth = 1;
  76. const boxHeight = 1;
  77. const boxDepth = 1;
  78. const boxGeometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  79. const sphereRadius = 0.5;
  80. const sphereGeometry = new THREE.SphereGeometry(sphereRadius);
  81. function makeInstance(geometry, color, x) {
  82. const material = new THREE.MeshPhongMaterial({color});
  83. const cube = new THREE.Mesh(geometry, material);
  84. scene.add(cube);
  85. cube.position.x = x;
  86. cube.position.y = 1.6;
  87. cube.position.z = -2;
  88. return cube;
  89. }
  90. const meshToMeshMap = new Map();
  91. [
  92. { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, },
  93. { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, },
  94. { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, },
  95. ].forEach((info) => {
  96. const {x, boxColor, sphereColor} = info;
  97. const sphere = makeInstance(sphereGeometry, sphereColor, x);
  98. const box = makeInstance(boxGeometry, boxColor, x);
  99. // hide the sphere
  100. sphere.visible = false;
  101. // map the sphere to the box
  102. meshToMeshMap.set(box, sphere);
  103. // map the box to the sphere
  104. meshToMeshMap.set(sphere, box);
  105. });
  106. class PickHelper {
  107. constructor(camera) {
  108. this.raycaster = new THREE.Raycaster();
  109. this.pickedObject = null;
  110. this.pickedObjectSavedColor = 0;
  111. const cursorColors = new Uint8Array([
  112. 64, 64, 64, 64, // dark gray
  113. 255, 255, 255, 255, // white
  114. ]);
  115. this.cursorTexture = makeDataTexture(cursorColors, 2, 1);
  116. const ringRadius = 0.4;
  117. const tubeRadius = 0.1;
  118. const tubeSegments = 4;
  119. const ringSegments = 64;
  120. const cursorGeometry = new THREE.TorusGeometry(
  121. ringRadius, tubeRadius, tubeSegments, ringSegments);
  122. const cursorMaterial = new THREE.MeshBasicMaterial({
  123. color: 'white',
  124. map: this.cursorTexture,
  125. transparent: true,
  126. blending: THREE.CustomBlending,
  127. blendSrc: THREE.OneMinusDstColorFactor,
  128. blendDst: THREE.OneMinusSrcColorFactor,
  129. });
  130. const cursor = new THREE.Mesh(cursorGeometry, cursorMaterial);
  131. camera.add(cursor);
  132. cursor.position.z = -1;
  133. const scale = 0.05;
  134. cursor.scale.set(scale, scale, scale);
  135. this.cursor = cursor;
  136. this.selectTimer = 0;
  137. this.selectDuration = 2;
  138. this.lastTime = 0;
  139. }
  140. pick(normalizedPosition, scene, camera, time) {
  141. const elapsedTime = time - this.lastTime;
  142. this.lastTime = time;
  143. const lastPickedObject = this.pickedObject;
  144. // restore the color if there is a picked object
  145. if (this.pickedObject) {
  146. this.pickedObject = undefined;
  147. }
  148. // cast a ray through the frustum
  149. this.raycaster.setFromCamera(normalizedPosition, camera);
  150. // get the list of objects the ray intersected
  151. const intersectedObjects = this.raycaster.intersectObjects(scene.children);
  152. if (intersectedObjects.length) {
  153. // pick the first object. It's the closest one
  154. this.pickedObject = intersectedObjects[0].object;
  155. }
  156. // show or hide cursor
  157. this.cursor.visible = this.pickedObject ? true : false;
  158. let selected = false;
  159. // if we're looking at the same object as before
  160. // increment time select timer
  161. if (this.pickedObject && lastPickedObject === this.pickedObject) {
  162. this.selectTimer += elapsedTime;
  163. if (this.selectTimer >= this.selectDuration) {
  164. this.selectTimer = 0;
  165. selected = true;
  166. }
  167. } else {
  168. this.selectTimer = 0;
  169. }
  170. // set cursor material to show the timer state
  171. const fromStart = 0;
  172. const fromEnd = this.selectDuration;
  173. const toStart = -0.5;
  174. const toEnd = 0.5;
  175. this.cursorTexture.offset.x = THREE.MathUtils.mapLinear(
  176. this.selectTimer,
  177. fromStart, fromEnd,
  178. toStart, toEnd);
  179. return selected ? this.pickedObject : undefined;
  180. }
  181. }
  182. const pickHelper = new PickHelper(camera);
  183. scene.add(camera);
  184. function resizeRendererToDisplaySize(renderer) {
  185. const canvas = renderer.domElement;
  186. const width = canvas.clientWidth;
  187. const height = canvas.clientHeight;
  188. const needResize = canvas.width !== width || canvas.height !== height;
  189. if (needResize) {
  190. renderer.setSize(width, height, false);
  191. }
  192. return needResize;
  193. }
  194. function render(time) {
  195. time *= 0.001;
  196. if (resizeRendererToDisplaySize(renderer)) {
  197. const canvas = renderer.domElement;
  198. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  199. camera.updateProjectionMatrix();
  200. }
  201. let ndx = 0;
  202. for (const mesh of meshToMeshMap.keys()) {
  203. const speed = 1 + ndx * .1;
  204. const rot = time * speed;
  205. mesh.rotation.x = rot;
  206. mesh.rotation.y = rot;
  207. ++ndx;
  208. }
  209. // 0, 0 is the center of the view in normalized coordinates.
  210. const selectedObject = pickHelper.pick({x: 0, y: 0}, scene, camera, time);
  211. if (selectedObject) {
  212. selectedObject.visible = false;
  213. const partnerObject = meshToMeshMap.get(selectedObject);
  214. partnerObject.visible = true;
  215. }
  216. renderer.render(scene, camera);
  217. }
  218. renderer.setAnimationLoop(render);
  219. }
  220. main();
  221. </script>
  222. </html>