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

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