2
0

webgl_nearestneighbour.html 6.0 KB

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