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

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