webgl_interactive_cubes_gpu.html 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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( 0x555555 ) );
  56. const light = new THREE.SpotLight( 0xffffff, 1.5 );
  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.RedIntegerFormat,
  70. internalFormat: 'R32I',
  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 Int32Array( position.count );
  93. array.fill( id );
  94. const bufferAttribute = new THREE.BufferAttribute( array, 1, false );
  95. geometry.setAttribute( 'id', bufferAttribute );
  96. }
  97. function applyVertexColors( geometry, color ) {
  98. const position = geometry.attributes.position;
  99. const colors = [];
  100. for ( let i = 0; i < position.count; i ++ ) {
  101. colors.push( color.r, color.g, color.b );
  102. }
  103. geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );
  104. }
  105. const geometries = [];
  106. const matrix = new THREE.Matrix4();
  107. const quaternion = new THREE.Quaternion();
  108. const color = new THREE.Color();
  109. for ( let i = 0; i < 5000; i ++ ) {
  110. const geometry = new THREE.BoxGeometry();
  111. const position = new THREE.Vector3();
  112. position.x = Math.random() * 10000 - 5000;
  113. position.y = Math.random() * 6000 - 3000;
  114. position.z = Math.random() * 8000 - 4000;
  115. const rotation = new THREE.Euler();
  116. rotation.x = Math.random() * 2 * Math.PI;
  117. rotation.y = Math.random() * 2 * Math.PI;
  118. rotation.z = Math.random() * 2 * Math.PI;
  119. const scale = new THREE.Vector3();
  120. scale.x = Math.random() * 200 + 100;
  121. scale.y = Math.random() * 200 + 100;
  122. scale.z = Math.random() * 200 + 100;
  123. quaternion.setFromEuler( rotation );
  124. matrix.compose( position, quaternion, scale );
  125. geometry.applyMatrix4( matrix );
  126. // give the geometry's vertices a random color to be displayed and an integer
  127. // identifier as a vertex attribute so boxes can be identified after being merged.
  128. applyVertexColors( geometry, color.setHex( Math.random() * 0xffffff ) );
  129. applyId( geometry, i );
  130. geometries.push( geometry );
  131. pickingData[ i ] = {
  132. position: position,
  133. rotation: rotation,
  134. scale: scale
  135. };
  136. }
  137. const mergedGeometry = BufferGeometryUtils.mergeGeometries( geometries );
  138. scene.add( new THREE.Mesh( mergedGeometry, defaultMaterial ) );
  139. pickingScene.add( new THREE.Mesh( mergedGeometry, pickingMaterial ) );
  140. highlightBox = new THREE.Mesh(
  141. new THREE.BoxGeometry(),
  142. new THREE.MeshLambertMaterial( { color: 0xffff00 } )
  143. );
  144. scene.add( highlightBox );
  145. renderer = new THREE.WebGLRenderer( { antialias: true } );
  146. renderer.setPixelRatio( window.devicePixelRatio );
  147. renderer.setSize( window.innerWidth, window.innerHeight );
  148. container.appendChild( renderer.domElement );
  149. controls = new TrackballControls( camera, renderer.domElement );
  150. controls.rotateSpeed = 1.0;
  151. controls.zoomSpeed = 1.2;
  152. controls.panSpeed = 0.8;
  153. controls.noZoom = false;
  154. controls.noPan = false;
  155. controls.staticMoving = true;
  156. controls.dynamicDampingFactor = 0.3;
  157. stats = new Stats();
  158. container.appendChild( stats.dom );
  159. renderer.domElement.addEventListener( 'pointermove', onPointerMove );
  160. }
  161. //
  162. function onPointerMove( e ) {
  163. pointer.x = e.clientX;
  164. pointer.y = e.clientY;
  165. }
  166. function animate() {
  167. requestAnimationFrame( animate );
  168. render();
  169. stats.update();
  170. }
  171. function pick() {
  172. // render the picking scene off-screen
  173. // set the view offset to represent just a single pixel under the mouse
  174. const dpr = window.devicePixelRatio;
  175. camera.setViewOffset(
  176. renderer.domElement.width, renderer.domElement.height,
  177. Math.floor( pointer.x * dpr ), Math.floor( pointer.y * dpr ),
  178. 1, 1
  179. );
  180. // render the scene
  181. renderer.setRenderTarget( pickingTexture );
  182. // clear the background to - 1 meaning no item was hit
  183. clearColor.setRGB( - 1, - 1, - 1 );
  184. renderer.setClearColor( clearColor );
  185. renderer.render( pickingScene, camera );
  186. // clear the view offset so rendering returns to normal
  187. camera.clearViewOffset();
  188. // create buffer for reading single pixel
  189. const pixelBuffer = new Int32Array( 1 );
  190. // read the pixel
  191. renderer.readRenderTargetPixels( pickingTexture, 0, 0, 1, 1, pixelBuffer );
  192. const id = pixelBuffer[ 0 ];
  193. if ( id !== - 1 ) {
  194. // move our highlightBox so that it surrounds the picked object
  195. const data = pickingData[ id ];
  196. highlightBox.position.copy( data.position );
  197. highlightBox.rotation.copy( data.rotation );
  198. highlightBox.scale.copy( data.scale ).add( offset );
  199. highlightBox.visible = true;
  200. } else {
  201. highlightBox.visible = false;
  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>