webgl_interactive_cubes_gpu.html 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - interactive cubes (gpu)</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #fff;
  11. color: #444;
  12. }
  13. a {
  14. color: #08f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - gpu picking
  21. </div>
  22. <div id="container"></div>
  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/": "./jsm/"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three';
  36. import Stats from 'three/addons/libs/stats.module.js';
  37. import { TrackballControls } from 'three/addons/controls/TrackballControls.js';
  38. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  39. let container, stats;
  40. let camera, controls, scene, renderer;
  41. let pickingTexture, pickingScene;
  42. let highlightBox;
  43. const pickingData = [];
  44. const pointer = new THREE.Vector2();
  45. const offset = new THREE.Vector3( 10, 10, 10 );
  46. const clearColor = new THREE.Color();
  47. init();
  48. animate();
  49. function init() {
  50. container = document.getElementById( 'container' );
  51. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
  52. camera.position.z = 1000;
  53. scene = new THREE.Scene();
  54. scene.background = new THREE.Color( 0xffffff );
  55. scene.add( new THREE.AmbientLight( 0xcccccc ) );
  56. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  57. light.position.set( 0, 500, 2000 );
  58. scene.add( light );
  59. const defaultMaterial = new THREE.MeshPhongMaterial( {
  60. color: 0xffffff,
  61. flatShading: true,
  62. vertexColors: true,
  63. shininess: 0
  64. } );
  65. // set up the picking texture to use a 32 bit integer so we can write and read integer ids from it
  66. pickingScene = new THREE.Scene();
  67. pickingTexture = new THREE.WebGLRenderTarget( 1, 1, {
  68. type: THREE.IntType,
  69. format: THREE.RGBAIntegerFormat,
  70. internalFormat: 'RGBA32I',
  71. } );
  72. const pickingMaterial = new THREE.ShaderMaterial( {
  73. glslVersion: THREE.GLSL3,
  74. vertexShader: /* glsl */`
  75. attribute int id;
  76. flat varying int vid;
  77. void main() {
  78. vid = id;
  79. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  80. }
  81. `,
  82. fragmentShader: /* glsl */`
  83. layout(location = 0) out int out_id;
  84. flat varying int vid;
  85. void main() {
  86. out_id = vid;
  87. }
  88. `,
  89. } );
  90. function applyId( geometry, id ) {
  91. const position = geometry.attributes.position;
  92. const array = new Int16Array( position.count );
  93. array.fill( id );
  94. const bufferAttribute = new THREE.Int16BufferAttribute( array, 1, false );
  95. bufferAttribute.gpuType = THREE.IntType;
  96. geometry.setAttribute( 'id', bufferAttribute );
  97. }
  98. function applyVertexColors( geometry, color ) {
  99. const position = geometry.attributes.position;
  100. const colors = [];
  101. for ( let i = 0; i < position.count; i ++ ) {
  102. colors.push( color.r, color.g, color.b );
  103. }
  104. geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );
  105. }
  106. const geometries = [];
  107. const matrix = new THREE.Matrix4();
  108. const quaternion = new THREE.Quaternion();
  109. const color = new THREE.Color();
  110. for ( let i = 0; i < 5000; i ++ ) {
  111. const geometry = new THREE.BoxGeometry();
  112. const position = new THREE.Vector3();
  113. position.x = Math.random() * 10000 - 5000;
  114. position.y = Math.random() * 6000 - 3000;
  115. position.z = Math.random() * 8000 - 4000;
  116. const rotation = new THREE.Euler();
  117. rotation.x = Math.random() * 2 * Math.PI;
  118. rotation.y = Math.random() * 2 * Math.PI;
  119. rotation.z = Math.random() * 2 * Math.PI;
  120. const scale = new THREE.Vector3();
  121. scale.x = Math.random() * 200 + 100;
  122. scale.y = Math.random() * 200 + 100;
  123. scale.z = Math.random() * 200 + 100;
  124. quaternion.setFromEuler( rotation );
  125. matrix.compose( position, quaternion, scale );
  126. geometry.applyMatrix4( matrix );
  127. // give the geometry's vertices a random color to be displayed and an integer
  128. // identifier as a vertex attribute so boxes can be identified after being merged.
  129. applyVertexColors( geometry, color.setHex( Math.random() * 0xffffff ) );
  130. applyId( geometry, i );
  131. geometries.push( geometry );
  132. pickingData[ i ] = {
  133. position: position,
  134. rotation: rotation,
  135. scale: scale
  136. };
  137. }
  138. const mergedGeometry = BufferGeometryUtils.mergeGeometries( geometries );
  139. scene.add( new THREE.Mesh( mergedGeometry, defaultMaterial ) );
  140. pickingScene.add( new THREE.Mesh( mergedGeometry, pickingMaterial ) );
  141. highlightBox = new THREE.Mesh(
  142. new THREE.BoxGeometry(),
  143. new THREE.MeshLambertMaterial( { color: 0xffff00 } )
  144. );
  145. scene.add( highlightBox );
  146. renderer = new THREE.WebGLRenderer( { antialias: true } );
  147. renderer.setPixelRatio( window.devicePixelRatio );
  148. renderer.setSize( window.innerWidth, window.innerHeight );
  149. renderer.useLegacyLights = false;
  150. container.appendChild( renderer.domElement );
  151. controls = new TrackballControls( camera, renderer.domElement );
  152. controls.rotateSpeed = 1.0;
  153. controls.zoomSpeed = 1.2;
  154. controls.panSpeed = 0.8;
  155. controls.noZoom = false;
  156. controls.noPan = false;
  157. controls.staticMoving = true;
  158. controls.dynamicDampingFactor = 0.3;
  159. stats = new Stats();
  160. container.appendChild( stats.dom );
  161. renderer.domElement.addEventListener( 'pointermove', onPointerMove );
  162. }
  163. //
  164. function onPointerMove( e ) {
  165. pointer.x = e.clientX;
  166. pointer.y = e.clientY;
  167. }
  168. function animate() {
  169. requestAnimationFrame( animate );
  170. render();
  171. stats.update();
  172. }
  173. function pick() {
  174. // render the picking scene off-screen
  175. // set the view offset to represent just a single pixel under the mouse
  176. const dpr = window.devicePixelRatio;
  177. camera.setViewOffset(
  178. renderer.domElement.width, renderer.domElement.height,
  179. Math.floor( pointer.x * dpr ), Math.floor( pointer.y * dpr ),
  180. 1, 1
  181. );
  182. // render the scene
  183. renderer.setRenderTarget( pickingTexture );
  184. // clear the background to - 1 meaning no item was hit
  185. clearColor.setRGB( - 1, - 1, - 1 );
  186. renderer.setClearColor( clearColor );
  187. renderer.render( pickingScene, camera );
  188. // clear the view offset so rendering returns to normal
  189. camera.clearViewOffset();
  190. // create buffer for reading single pixel
  191. const pixelBuffer = new Int32Array( 4 );
  192. // read the pixel
  193. renderer.readRenderTargetPixels( pickingTexture, 0, 0, 1, 1, pixelBuffer );
  194. const id = pixelBuffer[ 0 ];
  195. if ( id !== - 1 ) {
  196. // move our highlightBox so that it surrounds the picked object
  197. const data = pickingData[ id ];
  198. highlightBox.position.copy( data.position );
  199. highlightBox.rotation.copy( data.rotation );
  200. highlightBox.scale.copy( data.scale ).add( offset );
  201. highlightBox.visible = true;
  202. } else {
  203. highlightBox.visible = false;
  204. }
  205. }
  206. function render() {
  207. controls.update();
  208. pick();
  209. renderer.setRenderTarget( null );
  210. renderer.render( scene, camera );
  211. }
  212. </script>
  213. </body>
  214. </html>