webgl_nearestneighbour.html 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - nearest neighbour</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. <style>
  8. html, body {
  9. width: 100%;
  10. height: 100%;
  11. }
  12. body {
  13. background-color: #ffffff;
  14. margin: 0;
  15. overflow: hidden;
  16. font-family: arial;
  17. }
  18. #info {
  19. text-align: center;
  20. padding: 5px;
  21. position: absolute;
  22. width: 100%;
  23. color: white;
  24. }
  25. </style>
  26. </head>
  27. <body>
  28. <div id="info"><a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - typed arrays - nearest neighbour for 500,000 sprites</div>
  29. <script src="../build/three.js"></script>
  30. <script src="js/utils/TypedArrayUtils.js"></script>
  31. <script src="js/controls/FirstPersonControls.js"></script>
  32. <script type="x-shader/x-vertex" id="vertexshader">
  33. //uniform float zoom;
  34. attribute float alpha;
  35. varying float vAlpha;
  36. void main() {
  37. vAlpha = 1.0 - alpha;
  38. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  39. gl_PointSize = 4.0 * ( 300.0 / -mvPosition.z );
  40. gl_Position = projectionMatrix * mvPosition;
  41. }
  42. </script>
  43. <script type="x-shader/x-fragment" id="fragmentshader">
  44. uniform sampler2D tex1;
  45. varying float vAlpha;
  46. void main() {
  47. gl_FragColor = texture2D( tex1, gl_PointCoord );
  48. gl_FragColor.r = ( 1.0 - gl_FragColor.r ) * vAlpha + gl_FragColor.r;
  49. }
  50. </script>
  51. <script>
  52. var camera, scene, renderer;
  53. var controls;
  54. var amountOfParticles = 500000, maxDistance = Math.pow( 120, 2 );
  55. var positions, alphas, particles, _particleGeom;
  56. var kdtree;
  57. var clock = new THREE.Clock();
  58. function init() {
  59. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000000 );
  60. scene = new THREE.Scene();
  61. controls = new THREE.FirstPersonControls( camera );
  62. controls.movementSpeed = 100;
  63. controls.lookSpeed = 0.1;
  64. controls.lookAt( 500, 500, 500 );
  65. // add a skybox background
  66. var cubeTextureLoader = new THREE.CubeTextureLoader();
  67. cubeTextureLoader.setPath( 'textures/cube/skybox/' );
  68. var cubeTexture = cubeTextureLoader.load( [
  69. 'px.jpg', 'nx.jpg',
  70. 'py.jpg', 'ny.jpg',
  71. 'pz.jpg', 'nz.jpg',
  72. ] );
  73. scene.background = cubeTexture;
  74. //
  75. renderer = new THREE.WebGLRenderer();
  76. renderer.setPixelRatio( window.devicePixelRatio );
  77. renderer.setSize( window.innerWidth, window.innerHeight );
  78. document.body.appendChild( renderer.domElement );
  79. // create the custom shader
  80. var textureLoader = new THREE.TextureLoader();
  81. var imagePreviewTexture = textureLoader.load( 'textures/crate.gif' );
  82. imagePreviewTexture.minFilter = THREE.LinearMipMapLinearFilter;
  83. imagePreviewTexture.magFilter = THREE.LinearFilter;
  84. var pointShaderMaterial = new THREE.ShaderMaterial( {
  85. uniforms: {
  86. tex1: { value: imagePreviewTexture },
  87. zoom: { value: 9.0 }
  88. },
  89. vertexShader: document.getElementById( 'vertexshader' ).textContent,
  90. fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
  91. transparent: true
  92. } );
  93. //create particles with buffer geometry
  94. var distanceFunction = function ( a, b ) {
  95. return Math.pow( a[ 0 ] - b[ 0 ], 2 ) + Math.pow( a[ 1 ] - b[ 1 ], 2 ) + Math.pow( a[ 2 ] - b[ 2 ], 2 );
  96. };
  97. positions = new Float32Array( amountOfParticles * 3 );
  98. alphas = new Float32Array( amountOfParticles );
  99. _particleGeom = new THREE.BufferGeometry();
  100. _particleGeom.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  101. _particleGeom.addAttribute( 'alpha', new THREE.BufferAttribute( alphas, 1 ) );
  102. particles = new THREE.Points( _particleGeom, pointShaderMaterial );
  103. for ( var x = 0; x < amountOfParticles; x ++ ) {
  104. positions[ x * 3 + 0 ] = Math.random() * 1000;
  105. positions[ x * 3 + 1 ] = Math.random() * 1000;
  106. positions[ x * 3 + 2 ] = Math.random() * 1000;
  107. alphas[ x ] = 1.0;
  108. }
  109. var measureStart = new Date().getTime();
  110. // creating the kdtree takes a lot of time to execute, in turn the nearest neighbour search will be much faster
  111. kdtree = new THREE.TypedArrayUtils.Kdtree( positions, distanceFunction, 3 );
  112. console.log( 'TIME building kdtree', new Date().getTime() - measureStart );
  113. // display particles after the kd-tree was generated and the sorting of the positions-array is done
  114. scene.add( particles );
  115. window.addEventListener( 'resize', onWindowResize, false );
  116. }
  117. function onWindowResize() {
  118. camera.aspect = window.innerWidth / window.innerHeight;
  119. camera.updateProjectionMatrix();
  120. renderer.setSize( window.innerWidth, window.innerHeight );
  121. controls.handleResize();
  122. }
  123. function animate() {
  124. requestAnimationFrame( animate );
  125. //
  126. displayNearest( camera.position );
  127. controls.update( clock.getDelta() );
  128. renderer.render( scene, camera );
  129. }
  130. function displayNearest( position ) {
  131. // take the nearest 200 around him. distance^2 'cause we use the manhattan distance and no square is applied in the distance function
  132. var imagePositionsInRange = kdtree.nearest( [ position.x, position.y, position.z ], 100, maxDistance );
  133. // We combine the nearest neighbour with a view frustum. Doesn't make sense if we change the sprites not in our view... well maybe it does. Whatever you want.
  134. var _frustum = new THREE.Frustum();
  135. var _projScreenMatrix = new THREE.Matrix4();
  136. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  137. _frustum.setFromMatrix( _projScreenMatrix );
  138. for ( var i = 0, il = imagePositionsInRange.length; i < il; i ++ ) {
  139. var object = imagePositionsInRange[ i ];
  140. var objectPoint = new THREE.Vector3().fromArray( object[ 0 ].obj );
  141. if ( _frustum.containsPoint( objectPoint ) ) {
  142. var objectIndex = object[ 0 ].pos;
  143. // set the alpha according to distance
  144. alphas[ objectIndex ] = 1.0 / maxDistance * object[ 1 ];
  145. // update the attribute
  146. _particleGeom.attributes.alpha.needsUpdate = true;
  147. }
  148. }
  149. }
  150. init();
  151. animate();
  152. </script>
  153. </body>
  154. </html>