webgl_interactive_cubes_gpu.html 7.4 KB

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