threejs-picking-gpu.html 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 - Picking - RayCaster w/Transparency</title>
  8. <style>
  9. body {
  10. margin: 0;
  11. }
  12. #c {
  13. width: 100vw;
  14. height: 100vh;
  15. display: block;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <canvas id="c"></canvas>
  21. </body>
  22. <script src="resources/threejs/r102/three.min.js"></script>
  23. <script>
  24. 'use strict';
  25. /* global THREE */
  26. function main() {
  27. const canvas = document.querySelector('#c');
  28. const renderer = new THREE.WebGLRenderer({canvas: canvas});
  29. const fov = 60;
  30. const aspect = 2; // the canvas default
  31. const near = 0.1;
  32. const far = 200;
  33. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  34. camera.position.z = 30;
  35. const scene = new THREE.Scene();
  36. scene.background = new THREE.Color('white');
  37. const pickingScene = new THREE.Scene();
  38. pickingScene.background = new THREE.Color(0);
  39. // put the camera on a pole (parent it to an object)
  40. // so we can spin the pole to move the camera around the scene
  41. const cameraPole = new THREE.Object3D();
  42. scene.add(cameraPole);
  43. cameraPole.add(camera);
  44. {
  45. const color = 0xFFFFFF;
  46. const intensity = 1;
  47. const light = new THREE.DirectionalLight(color, intensity);
  48. light.position.set(-1, 2, 4);
  49. camera.add(light);
  50. }
  51. const boxWidth = 1;
  52. const boxHeight = 1;
  53. const boxDepth = 1;
  54. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  55. function rand(min, max) {
  56. if (max === undefined) {
  57. max = min;
  58. min = 0;
  59. }
  60. return min + (max - min) * Math.random();
  61. }
  62. function randomColor() {
  63. return `hsl(${rand(360) | 0}, ${rand(50, 100) | 0}%, 50%)`;
  64. }
  65. const loader = new THREE.TextureLoader();
  66. const texture = loader.load('resources/images/frame.png');
  67. const idToObject = {};
  68. const numObjects = 100;
  69. for (let i = 0; i < numObjects; ++i) {
  70. const id = i + 1;
  71. const material = new THREE.MeshPhongMaterial({
  72. color: randomColor(),
  73. map: texture,
  74. transparent: true,
  75. side: THREE.DoubleSide,
  76. alphaTest: 0.5,
  77. });
  78. const cube = new THREE.Mesh(geometry, material);
  79. scene.add(cube);
  80. idToObject[id] = cube;
  81. cube.position.set(rand(-20, 20), rand(-20, 20), rand(-20, 20));
  82. cube.rotation.set(rand(Math.PI), rand(Math.PI), 0);
  83. cube.scale.set(rand(3, 6), rand(3, 6), rand(3, 6));
  84. const pickingMaterial = new THREE.MeshPhongMaterial({
  85. emissive: new THREE.Color(id),
  86. color: new THREE.Color(0, 0, 0),
  87. specular: new THREE.Color(0, 0, 0),
  88. map: texture,
  89. transparent: true,
  90. side: THREE.DoubleSide,
  91. alphaTest: 0.5,
  92. blending: THREE.NoBlending,
  93. });
  94. const pickingCube = new THREE.Mesh(geometry, pickingMaterial);
  95. pickingScene.add(pickingCube);
  96. pickingCube.position.copy(cube.position);
  97. pickingCube.rotation.copy(cube.rotation);
  98. pickingCube.scale.copy(cube.scale);
  99. }
  100. function resizeRendererToDisplaySize(renderer) {
  101. const canvas = renderer.domElement;
  102. const width = canvas.clientWidth;
  103. const height = canvas.clientHeight;
  104. const needResize = canvas.width !== width || canvas.height !== height;
  105. if (needResize) {
  106. renderer.setSize(width, height, false);
  107. }
  108. return needResize;
  109. }
  110. class GPUPickHelper {
  111. constructor() {
  112. // create a 1x1 pixel render target
  113. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  114. this.pixelBuffer = new Uint8Array(4);
  115. this.pickedObject = null;
  116. this.pickedObjectSavedColor = 0;
  117. }
  118. pick(cssPosition, scene, camera, time) {
  119. const {pickingTexture, pixelBuffer} = this;
  120. // restore the color if there is a picked object
  121. if (this.pickedObject) {
  122. this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
  123. this.pickedObject = undefined;
  124. }
  125. // set the view offset to represent just a single pixel under the mouse
  126. const pixelRatio = renderer.getPixelRatio();
  127. camera.setViewOffset(
  128. renderer.context.drawingBufferWidth, // full width
  129. renderer.context.drawingBufferHeight, // full top
  130. cssPosition.x * pixelRatio | 0, // rect x
  131. cssPosition.y * pixelRatio | 0, // rect y
  132. 1, // rect width
  133. 1, // rect height
  134. );
  135. // render the scene
  136. renderer.setRenderTarget(pickingTexture);
  137. renderer.render(scene, camera);
  138. renderer.setRenderTarget(null);
  139. // clear the view offset so rendering returns to normal
  140. camera.clearViewOffset();
  141. //read the pixel
  142. renderer.readRenderTargetPixels(
  143. pickingTexture,
  144. 0, // x
  145. 0, // y
  146. 1, // width
  147. 1, // height
  148. pixelBuffer);
  149. const id =
  150. (pixelBuffer[0] << 16) |
  151. (pixelBuffer[1] << 8) |
  152. (pixelBuffer[2] );
  153. const intersectedObject = idToObject[id];
  154. if (intersectedObject) {
  155. // pick the first object. It's the closest one
  156. this.pickedObject = intersectedObject;
  157. // save its color
  158. this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
  159. // set its emissive color to flashing red/yellow
  160. this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
  161. }
  162. }
  163. }
  164. const pickPosition = {x: 0, y: 0};
  165. const pickHelper = new GPUPickHelper();
  166. clearPickPosition();
  167. function render(time) {
  168. time *= 0.001; // convert to seconds;
  169. if (resizeRendererToDisplaySize(renderer)) {
  170. const canvas = renderer.domElement;
  171. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  172. camera.updateProjectionMatrix();
  173. }
  174. cameraPole.rotation.y = time * .1;
  175. pickHelper.pick(pickPosition, pickingScene, camera, time);
  176. renderer.render(scene, camera);
  177. requestAnimationFrame(render);
  178. }
  179. requestAnimationFrame(render);
  180. function setPickPosition(event) {
  181. pickPosition.x = event.clientX;
  182. pickPosition.y = event.clientY;
  183. }
  184. function clearPickPosition() {
  185. // unlike the mouse which always has a position
  186. // if the user stops touching the screen we want
  187. // to stop picking. For now we just pick a value
  188. // unlikely to pick something
  189. pickPosition.x = -100000;
  190. pickPosition.y = -100000;
  191. }
  192. window.addEventListener('mousemove', setPickPosition);
  193. window.addEventListener('mouseout', clearPickPosition);
  194. window.addEventListener('mouseleave', clearPickPosition);
  195. window.addEventListener('touchstart', (event) => {
  196. // prevent the window from scrolling
  197. event.preventDefault();
  198. setPickPosition(event.touches[0]);
  199. }, {passive: false});
  200. window.addEventListener('touchmove', (event) => {
  201. setPickPosition(event.touches[0]);
  202. });
  203. window.addEventListener('touchend', clearPickPosition);
  204. }
  205. main();
  206. </script>
  207. </html>