123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>three.js webgl - nearest neighbour</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
- <link type="text/css" rel="stylesheet" href="main.css">
- </head>
- <body>
- <div id="info">
- <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - typed arrays<br/>
- nearest neighbour for 500,000 sprites
- </div>
- <script type="x-shader/x-vertex" id="vertexshader">
- //uniform float zoom;
- attribute float alpha;
- varying float vAlpha;
- void main() {
- vAlpha = 1.0 - alpha;
- vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
- gl_PointSize = 4.0 * ( 300.0 / -mvPosition.z );
- gl_Position = projectionMatrix * mvPosition;
- }
- </script>
- <script type="x-shader/x-fragment" id="fragmentshader">
- uniform sampler2D tex1;
- varying float vAlpha;
- void main() {
- gl_FragColor = texture2D( tex1, gl_PointCoord );
- gl_FragColor.r = ( 1.0 - gl_FragColor.r ) * vAlpha + gl_FragColor.r;
- }
- </script>
- <script type="module">
- import * as THREE from '../build/three.module.js';
- import { FirstPersonControls } from './jsm/controls/FirstPersonControls.js';
- import { TypedArrayUtils } from './jsm/utils/TypedArrayUtils.js';
- var camera, scene, renderer;
- var controls;
- var amountOfParticles = 500000, maxDistance = Math.pow( 120, 2 );
- var positions, alphas, particles, _particleGeom;
- var kdtree;
- var clock = new THREE.Clock();
- function init() {
- camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000000 );
- scene = new THREE.Scene();
- // add a skybox background
- var cubeTextureLoader = new THREE.CubeTextureLoader();
- cubeTextureLoader.setPath( 'textures/cube/skyboxsun25deg/' );
- var cubeTexture = cubeTextureLoader.load( [
- 'px.jpg', 'nx.jpg',
- 'py.jpg', 'ny.jpg',
- 'pz.jpg', 'nz.jpg',
- ] );
- scene.background = cubeTexture;
- //
- renderer = new THREE.WebGLRenderer();
- renderer.setPixelRatio( window.devicePixelRatio );
- renderer.setSize( window.innerWidth, window.innerHeight );
- document.body.appendChild( renderer.domElement );
- controls = new FirstPersonControls( camera, renderer.domElement );
- controls.movementSpeed = 100;
- controls.lookSpeed = 0.1;
- controls.lookAt( 500, 500, 500 );
- // create the custom shader
- var textureLoader = new THREE.TextureLoader();
- var imagePreviewTexture = textureLoader.load( 'textures/crate.gif' );
- imagePreviewTexture.minFilter = THREE.LinearMipmapLinearFilter;
- imagePreviewTexture.magFilter = THREE.LinearFilter;
- var pointShaderMaterial = new THREE.ShaderMaterial( {
- uniforms: {
- tex1: { value: imagePreviewTexture },
- zoom: { value: 9.0 }
- },
- vertexShader: document.getElementById( 'vertexshader' ).textContent,
- fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
- transparent: true
- } );
- //create particles with buffer geometry
- var distanceFunction = function ( a, b ) {
- return Math.pow( a[ 0 ] - b[ 0 ], 2 ) + Math.pow( a[ 1 ] - b[ 1 ], 2 ) + Math.pow( a[ 2 ] - b[ 2 ], 2 );
- };
- positions = new Float32Array( amountOfParticles * 3 );
- alphas = new Float32Array( amountOfParticles );
- _particleGeom = new THREE.BufferGeometry();
- _particleGeom.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
- _particleGeom.setAttribute( 'alpha', new THREE.BufferAttribute( alphas, 1 ) );
- particles = new THREE.Points( _particleGeom, pointShaderMaterial );
- for ( var x = 0; x < amountOfParticles; x ++ ) {
- positions[ x * 3 + 0 ] = Math.random() * 1000;
- positions[ x * 3 + 1 ] = Math.random() * 1000;
- positions[ x * 3 + 2 ] = Math.random() * 1000;
- alphas[ x ] = 1.0;
- }
- var measureStart = new Date().getTime();
- // creating the kdtree takes a lot of time to execute, in turn the nearest neighbour search will be much faster
- kdtree = new TypedArrayUtils.Kdtree( positions, distanceFunction, 3 );
- console.log( 'TIME building kdtree', new Date().getTime() - measureStart );
- // display particles after the kd-tree was generated and the sorting of the positions-array is done
- scene.add( particles );
- window.addEventListener( 'resize', onWindowResize, false );
- }
- function onWindowResize() {
- camera.aspect = window.innerWidth / window.innerHeight;
- camera.updateProjectionMatrix();
- renderer.setSize( window.innerWidth, window.innerHeight );
- controls.handleResize();
- }
- function animate() {
- requestAnimationFrame( animate );
- //
- displayNearest( camera.position );
- controls.update( clock.getDelta() );
- renderer.render( scene, camera );
- }
- function displayNearest( position ) {
- // take the nearest 200 around him. distance^2 'cause we use the manhattan distance and no square is applied in the distance function
- var imagePositionsInRange = kdtree.nearest( [ position.x, position.y, position.z ], 100, maxDistance );
- // 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.
- var _frustum = new THREE.Frustum();
- var _projScreenMatrix = new THREE.Matrix4();
- _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
- _frustum.setFromProjectionMatrix( _projScreenMatrix );
- for ( var i = 0, il = imagePositionsInRange.length; i < il; i ++ ) {
- var object = imagePositionsInRange[ i ];
- var objectPoint = new THREE.Vector3().fromArray( object[ 0 ].obj );
- if ( _frustum.containsPoint( objectPoint ) ) {
- var objectIndex = object[ 0 ].pos;
- // set the alpha according to distance
- alphas[ objectIndex ] = 1.0 / maxDistance * object[ 1 ];
- // update the attribute
- _particleGeom.attributes.alpha.needsUpdate = true;
- }
- }
- }
- init();
- animate();
- </script>
- </body>
- </html>
|