indexed-textures-random-colors.html 13 KB

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