threejs-indexed-textures-random-colors.html 13 KB

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