webgl_interactive_cubes_gpu.html 7.4 KB

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