indexed-textures-picking-debounced.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Indexed Textures - Picking and Highlighting - Debounced</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. height: 100%;
  12. margin: 0;
  13. font-family: sans-serif;
  14. }
  15. #c {
  16. width: 100%; /* let our container decide our size */
  17. height: 100%;
  18. display: block;
  19. }
  20. #container {
  21. position: relative; /* makes this the origin of its children */
  22. width: 100%;
  23. height: 100%;
  24. overflow: hidden;
  25. }
  26. #labels {
  27. position: absolute; /* let us position ourself inside the container */
  28. z-index: 0; /* make a new stacking context so children don't sort with rest of page */
  29. left: 0; /* make our position the top left of the container */
  30. top: 0;
  31. color: white;
  32. }
  33. #labels>div {
  34. position: absolute; /* let us position them inside the container */
  35. left: 0; /* make their default position the top left of the container */
  36. top: 0;
  37. cursor: pointer; /* change the cursor to a hand when over us */
  38. font-size: small;
  39. user-select: none; /* don't let the text get selected */
  40. pointer-events: none; /* make us invisible to the pointer */
  41. text-shadow: /* create a black outline */
  42. -1px -1px 0 #000,
  43. 0 -1px 0 #000,
  44. 1px -1px 0 #000,
  45. 1px 0 0 #000,
  46. 1px 1px 0 #000,
  47. 0 1px 0 #000,
  48. -1px 1px 0 #000,
  49. -1px 0 0 #000;
  50. }
  51. #labels>div:hover {
  52. color: red;
  53. }
  54. </style>
  55. </head>
  56. <body>
  57. <div id="container">
  58. <canvas id="c"></canvas>
  59. <div id="labels"></div>
  60. </div>
  61. </body>
  62. <!-- Import maps polyfill -->
  63. <!-- Remove this when import maps will be widely supported -->
  64. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  65. <script type="importmap">
  66. {
  67. "imports": {
  68. "three": "../../build/three.module.js",
  69. "three/addons/": "../../examples/jsm/"
  70. }
  71. }
  72. </script>
  73. <script type="module">
  74. import * as THREE from 'three';
  75. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  76. function main() {
  77. const canvas = document.querySelector( '#c' );
  78. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  79. renderer.useLegacyLights = false;
  80. const fov = 60;
  81. const aspect = 2; // the canvas default
  82. const near = 0.1;
  83. const far = 10;
  84. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  85. camera.position.z = 2.5;
  86. const controls = new OrbitControls( camera, canvas );
  87. controls.enableDamping = true;
  88. controls.enablePan = false;
  89. controls.minDistance = 1.2;
  90. controls.maxDistance = 4;
  91. controls.update();
  92. const scene = new THREE.Scene();
  93. scene.background = new THREE.Color( '#246' );
  94. const pickingScene = new THREE.Scene();
  95. pickingScene.background = new THREE.Color( 0 );
  96. const tempColor = new THREE.Color();
  97. function get255BasedColor( color ) {
  98. tempColor.set( color );
  99. const base = tempColor.toArray().map( v => v * 255 );
  100. base.push( 255 ); // alpha
  101. return base;
  102. }
  103. const maxNumCountries = 512;
  104. const paletteTextureWidth = maxNumCountries;
  105. const paletteTextureHeight = 1;
  106. const palette = new Uint8Array( paletteTextureWidth * 4 );
  107. const paletteTexture = new THREE.DataTexture( palette, paletteTextureWidth, paletteTextureHeight );
  108. paletteTexture.minFilter = THREE.NearestFilter;
  109. paletteTexture.magFilter = THREE.NearestFilter;
  110. paletteTexture.colorSpace = THREE.SRGBColorSpace;
  111. const selectedColor = get255BasedColor( 'red' );
  112. const unselectedColor = get255BasedColor( '#444' );
  113. const oceanColor = get255BasedColor( 'rgb(100,200,255)' );
  114. resetPalette();
  115. function setPaletteColor( index, color ) {
  116. palette.set( color, index * 4 );
  117. }
  118. function resetPalette() {
  119. // make all colors the unselected color
  120. for ( let i = 1; i < maxNumCountries; ++ i ) {
  121. setPaletteColor( i, unselectedColor );
  122. }
  123. // set the ocean color (index #0)
  124. setPaletteColor( 0, oceanColor );
  125. paletteTexture.needsUpdate = true;
  126. }
  127. {
  128. const loader = new THREE.TextureLoader();
  129. const geometry = new THREE.SphereGeometry( 1, 64, 32 );
  130. const indexTexture = loader.load( 'resources/data/world/country-index-texture.png', render );
  131. indexTexture.minFilter = THREE.NearestFilter;
  132. indexTexture.magFilter = THREE.NearestFilter;
  133. const pickingMaterial = new THREE.MeshBasicMaterial( { map: indexTexture } );
  134. pickingScene.add( new THREE.Mesh( geometry, pickingMaterial ) );
  135. const fragmentShaderReplacements = [
  136. {
  137. from: '#include <common>',
  138. to: `
  139. #include <common>
  140. uniform sampler2D indexTexture;
  141. uniform sampler2D paletteTexture;
  142. uniform float paletteTextureWidth;
  143. `,
  144. },
  145. {
  146. from: '#include <color_fragment>',
  147. to: `
  148. #include <color_fragment>
  149. {
  150. vec4 indexColor = texture2D(indexTexture, vMapUv);
  151. float index = indexColor.r * 255.0 + indexColor.g * 255.0 * 256.0;
  152. vec2 paletteUV = vec2((index + 0.5) / paletteTextureWidth, 0.5);
  153. vec4 paletteColor = texture2D(paletteTexture, paletteUV);
  154. // diffuseColor.rgb += paletteColor.rgb; // white outlines
  155. diffuseColor.rgb = paletteColor.rgb - diffuseColor.rgb; // black outlines
  156. }
  157. `,
  158. },
  159. ];
  160. const texture = loader.load( 'resources/data/world/country-outlines-4k.png', render );
  161. const material = new THREE.MeshBasicMaterial( { map: texture } );
  162. material.onBeforeCompile = function ( shader ) {
  163. fragmentShaderReplacements.forEach( ( rep ) => {
  164. shader.fragmentShader = shader.fragmentShader.replace( rep.from, rep.to );
  165. } );
  166. shader.uniforms.paletteTexture = { value: paletteTexture };
  167. shader.uniforms.indexTexture = { value: indexTexture };
  168. shader.uniforms.paletteTextureWidth = { value: paletteTextureWidth };
  169. };
  170. scene.add( new THREE.Mesh( geometry, material ) );
  171. }
  172. async function loadJSON( url ) {
  173. const req = await fetch( url );
  174. return req.json();
  175. }
  176. let numCountriesSelected = 0;
  177. let countryInfos;
  178. async function loadCountryData() {
  179. countryInfos = await loadJSON( 'resources/data/world/country-info.json' ); /* threejs.org: url */
  180. const lonFudge = Math.PI * 1.5;
  181. const latFudge = Math.PI;
  182. // these helpers will make it easy to position the boxes
  183. // We can rotate the lon helper on its Y axis to the longitude
  184. const lonHelper = new THREE.Object3D();
  185. // We rotate the latHelper on its X axis to the latitude
  186. const latHelper = new THREE.Object3D();
  187. lonHelper.add( latHelper );
  188. // The position helper moves the object to the edge of the sphere
  189. const positionHelper = new THREE.Object3D();
  190. positionHelper.position.z = 1;
  191. latHelper.add( positionHelper );
  192. const labelParentElem = document.querySelector( '#labels' );
  193. for ( const countryInfo of countryInfos ) {
  194. const { lat, lon, min, max, name } = countryInfo;
  195. // adjust the helpers to point to the latitude and longitude
  196. lonHelper.rotation.y = THREE.MathUtils.degToRad( lon ) + lonFudge;
  197. latHelper.rotation.x = THREE.MathUtils.degToRad( lat ) + latFudge;
  198. // get the position of the lat/lon
  199. positionHelper.updateWorldMatrix( true, false );
  200. const position = new THREE.Vector3();
  201. positionHelper.getWorldPosition( position );
  202. countryInfo.position = position;
  203. // compute the area for each country
  204. const width = max[ 0 ] - min[ 0 ];
  205. const height = max[ 1 ] - min[ 1 ];
  206. const area = width * height;
  207. countryInfo.area = area;
  208. // add an element for each country
  209. const elem = document.createElement( 'div' );
  210. elem.textContent = name;
  211. labelParentElem.appendChild( elem );
  212. countryInfo.elem = elem;
  213. }
  214. requestRenderIfNotRequested();
  215. }
  216. loadCountryData();
  217. const tempV = new THREE.Vector3();
  218. const cameraToPoint = new THREE.Vector3();
  219. const cameraPosition = new THREE.Vector3();
  220. const normalMatrix = new THREE.Matrix3();
  221. const settings = {
  222. minArea: 20,
  223. maxVisibleDot: - 0.2,
  224. };
  225. function updateLabels() {
  226. // exit if we have not loaded the data yet
  227. if ( ! countryInfos ) {
  228. return;
  229. }
  230. const large = settings.minArea * settings.minArea;
  231. // get a matrix that represents a relative orientation of the camera
  232. normalMatrix.getNormalMatrix( camera.matrixWorldInverse );
  233. // get the camera's position
  234. camera.getWorldPosition( cameraPosition );
  235. for ( const countryInfo of countryInfos ) {
  236. const { position, elem, area, selected } = countryInfo;
  237. const largeEnough = area >= large;
  238. const show = selected || ( numCountriesSelected === 0 && largeEnough );
  239. if ( ! show ) {
  240. elem.style.display = 'none';
  241. continue;
  242. }
  243. // Orient the position based on the camera's orientation.
  244. // Since the sphere is at the origin and the sphere is a unit sphere
  245. // this gives us a camera relative direction vector for the position.
  246. tempV.copy( position );
  247. tempV.applyMatrix3( normalMatrix );
  248. // compute the direction to this position from the camera
  249. cameraToPoint.copy( position );
  250. cameraToPoint.applyMatrix4( camera.matrixWorldInverse ).normalize();
  251. // get the dot product of camera relative direction to this position
  252. // on the globe with the direction from the camera to that point.
  253. // -1 = facing directly towards the camera
  254. // 0 = exactly on tangent of the sphere from the camera
  255. // > 0 = facing away
  256. const dot = tempV.dot( cameraToPoint );
  257. // if the orientation is not facing us hide it.
  258. if ( dot > settings.maxVisibleDot ) {
  259. elem.style.display = 'none';
  260. continue;
  261. }
  262. // restore the element to its default display style
  263. elem.style.display = '';
  264. // get the normalized screen coordinate of that position
  265. // x and y will be in the -1 to +1 range with x = -1 being
  266. // on the left and y = -1 being on the bottom
  267. tempV.copy( position );
  268. tempV.project( camera );
  269. // convert the normalized position to CSS coordinates
  270. const x = ( tempV.x * .5 + .5 ) * canvas.clientWidth;
  271. const y = ( tempV.y * - .5 + .5 ) * canvas.clientHeight;
  272. // move the elem to that position
  273. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  274. // set the zIndex for sorting
  275. elem.style.zIndex = ( - tempV.z * .5 + .5 ) * 100000 | 0;
  276. }
  277. }
  278. class GPUPickHelper {
  279. constructor() {
  280. // create a 1x1 pixel render target
  281. this.pickingTexture = new THREE.WebGLRenderTarget( 1, 1 );
  282. this.pixelBuffer = new Uint8Array( 4 );
  283. }
  284. pick( cssPosition, scene, camera ) {
  285. const { pickingTexture, pixelBuffer } = this;
  286. // set the view offset to represent just a single pixel under the mouse
  287. const pixelRatio = renderer.getPixelRatio();
  288. camera.setViewOffset(
  289. renderer.getContext().drawingBufferWidth, // full width
  290. renderer.getContext().drawingBufferHeight, // full top
  291. cssPosition.x * pixelRatio | 0, // rect x
  292. cssPosition.y * pixelRatio | 0, // rect y
  293. 1, // rect width
  294. 1, // rect height
  295. );
  296. // render the scene
  297. renderer.setRenderTarget( pickingTexture );
  298. renderer.render( scene, camera );
  299. renderer.setRenderTarget( null );
  300. // clear the view offset so rendering returns to normal
  301. camera.clearViewOffset();
  302. //read the pixel
  303. renderer.readRenderTargetPixels(
  304. pickingTexture,
  305. 0, // x
  306. 0, // y
  307. 1, // width
  308. 1, // height
  309. pixelBuffer );
  310. const id =
  311. ( pixelBuffer[ 0 ] << 0 ) |
  312. ( pixelBuffer[ 1 ] << 8 ) |
  313. ( pixelBuffer[ 2 ] << 16 );
  314. return id;
  315. }
  316. }
  317. const pickHelper = new GPUPickHelper();
  318. const maxClickTimeMs = 200;
  319. const maxMoveDeltaSq = 5 * 5;
  320. const startPosition = {};
  321. let startTimeMs;
  322. function getCanvasRelativePosition( event ) {
  323. const rect = canvas.getBoundingClientRect();
  324. return {
  325. x: ( event.clientX - rect.left ) * canvas.width / rect.width,
  326. y: ( event.clientY - rect.top ) * canvas.height / rect.height,
  327. };
  328. }
  329. function recordStartTimeAndPosition( event ) {
  330. startTimeMs = performance.now();
  331. const pos = getCanvasRelativePosition( event );
  332. startPosition.x = pos.x;
  333. startPosition.y = pos.y;
  334. }
  335. function pickCountry( event ) {
  336. // exit if we have not loaded the data yet
  337. if ( ! countryInfos ) {
  338. return;
  339. }
  340. // if it's been a moment since the user started
  341. // then assume it was a drag action, not a select action
  342. const clickTimeMs = performance.now() - startTimeMs;
  343. if ( clickTimeMs > maxClickTimeMs ) {
  344. return;
  345. }
  346. // if they moved assume it was a drag action
  347. const position = getCanvasRelativePosition( event );
  348. const moveDeltaSq = ( startPosition.x - position.x ) ** 2 +
  349. ( startPosition.y - position.y ) ** 2;
  350. if ( moveDeltaSq > maxMoveDeltaSq ) {
  351. return;
  352. }
  353. const id = pickHelper.pick( position, pickingScene, camera );
  354. if ( id > 0 ) {
  355. const countryInfo = countryInfos[ id - 1 ];
  356. const selected = ! countryInfo.selected;
  357. if ( selected && ! event.shiftKey && ! event.ctrlKey && ! event.metaKey ) {
  358. unselectAllCountries();
  359. }
  360. numCountriesSelected += selected ? 1 : - 1;
  361. countryInfo.selected = selected;
  362. setPaletteColor( id, selected ? selectedColor : unselectedColor );
  363. paletteTexture.needsUpdate = true;
  364. } else if ( numCountriesSelected ) {
  365. unselectAllCountries();
  366. }
  367. requestRenderIfNotRequested();
  368. }
  369. function unselectAllCountries() {
  370. numCountriesSelected = 0;
  371. countryInfos.forEach( ( countryInfo ) => {
  372. countryInfo.selected = false;
  373. } );
  374. resetPalette();
  375. }
  376. canvas.addEventListener( 'pointerdown', recordStartTimeAndPosition );
  377. canvas.addEventListener( 'pointerup', pickCountry );
  378. function resizeRendererToDisplaySize( renderer ) {
  379. const canvas = renderer.domElement;
  380. const width = canvas.clientWidth;
  381. const height = canvas.clientHeight;
  382. const needResize = canvas.width !== width || canvas.height !== height;
  383. if ( needResize ) {
  384. renderer.setSize( width, height, false );
  385. }
  386. return needResize;
  387. }
  388. let renderRequested = false;
  389. function render() {
  390. renderRequested = undefined;
  391. if ( resizeRendererToDisplaySize( renderer ) ) {
  392. const canvas = renderer.domElement;
  393. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  394. camera.updateProjectionMatrix();
  395. }
  396. controls.update();
  397. updateLabels();
  398. renderer.render( scene, camera );
  399. }
  400. render();
  401. function requestRenderIfNotRequested() {
  402. if ( ! renderRequested ) {
  403. renderRequested = true;
  404. requestAnimationFrame( render );
  405. }
  406. }
  407. controls.addEventListener( 'change', requestRenderIfNotRequested );
  408. window.addEventListener( 'resize', requestRenderIfNotRequested );
  409. }
  410. main();
  411. </script>
  412. </html>