webgl_nearestneighbour.html 7.0 KB

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