indexed-textures-picking.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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</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="module">
  62. import * as THREE from '../../build/three.module.js';
  63. import {OrbitControls} from '../../examples/jsm/controls/OrbitControls.js';
  64. function main() {
  65. const canvas = document.querySelector('#c');
  66. const renderer = new THREE.WebGLRenderer({canvas});
  67. const fov = 60;
  68. const aspect = 2; // the canvas default
  69. const near = 0.1;
  70. const far = 10;
  71. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  72. camera.position.z = 2.5;
  73. const controls = new OrbitControls(camera, canvas);
  74. controls.enableDamping = true;
  75. controls.enablePan = false;
  76. controls.minDistance = 1.2;
  77. controls.maxDistance = 4;
  78. controls.update();
  79. const scene = new THREE.Scene();
  80. scene.background = new THREE.Color('#246');
  81. const pickingScene = new THREE.Scene();
  82. pickingScene.background = new THREE.Color(0);
  83. {
  84. const loader = new THREE.TextureLoader();
  85. const geometry = new THREE.SphereGeometry(1, 64, 32);
  86. const indexTexture = loader.load('resources/data/world/country-index-texture.png', render);
  87. indexTexture.minFilter = THREE.NearestFilter;
  88. indexTexture.magFilter = THREE.NearestFilter;
  89. const pickingMaterial = new THREE.MeshBasicMaterial({map: indexTexture});
  90. pickingScene.add(new THREE.Mesh(geometry, pickingMaterial));
  91. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  92. const material = new THREE.MeshBasicMaterial({map: texture});
  93. scene.add(new THREE.Mesh(geometry, material));
  94. }
  95. async function loadJSON(url) {
  96. const req = await fetch(url);
  97. return req.json();
  98. }
  99. let numCountriesSelected = 0;
  100. let countryInfos;
  101. async function loadCountryData() {
  102. countryInfos = await loadJSON('resources/data/world/country-info.json'); /* threejs.org: url */
  103. const lonFudge = Math.PI * 1.5;
  104. const latFudge = Math.PI;
  105. // these helpers will make it easy to position the boxes
  106. // We can rotate the lon helper on its Y axis to the longitude
  107. const lonHelper = new THREE.Object3D();
  108. // We rotate the latHelper on its X axis to the latitude
  109. const latHelper = new THREE.Object3D();
  110. lonHelper.add(latHelper);
  111. // The position helper moves the object to the edge of the sphere
  112. const positionHelper = new THREE.Object3D();
  113. positionHelper.position.z = 1;
  114. latHelper.add(positionHelper);
  115. const labelParentElem = document.querySelector('#labels');
  116. for (const countryInfo of countryInfos) {
  117. const {lat, lon, min, max, name} = countryInfo;
  118. // adjust the helpers to point to the latitude and longitude
  119. lonHelper.rotation.y = THREE.MathUtils.degToRad(lon) + lonFudge;
  120. latHelper.rotation.x = THREE.MathUtils.degToRad(lat) + latFudge;
  121. // get the position of the lat/lon
  122. positionHelper.updateWorldMatrix(true, false);
  123. const position = new THREE.Vector3();
  124. positionHelper.getWorldPosition(position);
  125. countryInfo.position = position;
  126. // compute the area for each country
  127. const width = max[0] - min[0];
  128. const height = max[1] - min[1];
  129. const area = width * height;
  130. countryInfo.area = area;
  131. // add an element for each country
  132. const elem = document.createElement('div');
  133. elem.textContent = name;
  134. labelParentElem.appendChild(elem);
  135. countryInfo.elem = elem;
  136. }
  137. requestRenderIfNotRequested();
  138. }
  139. loadCountryData();
  140. const tempV = new THREE.Vector3();
  141. const cameraToPoint = new THREE.Vector3();
  142. const cameraPosition = new THREE.Vector3();
  143. const normalMatrix = new THREE.Matrix3();
  144. const settings = {
  145. minArea: 20,
  146. maxVisibleDot: -0.2,
  147. };
  148. function updateLabels() {
  149. // exit if we have not loaded the data yet
  150. if (!countryInfos) {
  151. return;
  152. }
  153. const large = settings.minArea * settings.minArea;
  154. // get a matrix that represents a relative orientation of the camera
  155. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  156. // get the camera's position
  157. camera.getWorldPosition(cameraPosition);
  158. for (const countryInfo of countryInfos) {
  159. const {position, elem, area, selected} = countryInfo;
  160. const largeEnough = area >= large;
  161. const show = selected || (numCountriesSelected === 0 && largeEnough);
  162. if (!show) {
  163. elem.style.display = 'none';
  164. continue;
  165. }
  166. // Orient the position based on the camera's orientation.
  167. // Since the sphere is at the origin and the sphere is a unit sphere
  168. // this gives us a camera relative direction vector for the position.
  169. tempV.copy(position);
  170. tempV.applyMatrix3(normalMatrix);
  171. // compute the direction to this position from the camera
  172. cameraToPoint.copy(position);
  173. cameraToPoint.applyMatrix4(camera.matrixWorldInverse).normalize();
  174. // get the dot product of camera relative direction to this position
  175. // on the globe with the direction from the camera to that point.
  176. // 1 = facing directly towards the camera
  177. // 0 = exactly on tangent of the sphere from the camera
  178. // < 0 = facing away
  179. const dot = tempV.dot(cameraToPoint);
  180. // if the orientation is not facing us hide it.
  181. if (dot > settings.maxVisibleDot) {
  182. elem.style.display = 'none';
  183. continue;
  184. }
  185. // restore the element to its default display style
  186. elem.style.display = '';
  187. // get the normalized screen coordinate of that position
  188. // x and y will be in the -1 to +1 range with x = -1 being
  189. // on the left and y = -1 being on the bottom
  190. tempV.copy(position);
  191. tempV.project(camera);
  192. // convert the normalized position to CSS coordinates
  193. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  194. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  195. // move the elem to that position
  196. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  197. // set the zIndex for sorting
  198. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  199. }
  200. }
  201. class GPUPickHelper {
  202. constructor() {
  203. // create a 1x1 pixel render target
  204. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  205. this.pixelBuffer = new Uint8Array(4);
  206. }
  207. pick(cssPosition, scene, camera) {
  208. const {pickingTexture, pixelBuffer} = this;
  209. // set the view offset to represent just a single pixel under the mouse
  210. const pixelRatio = renderer.getPixelRatio();
  211. camera.setViewOffset(
  212. renderer.getContext().drawingBufferWidth, // full width
  213. renderer.getContext().drawingBufferHeight, // full top
  214. cssPosition.x * pixelRatio | 0, // rect x
  215. cssPosition.y * pixelRatio | 0, // rect y
  216. 1, // rect width
  217. 1, // rect height
  218. );
  219. // render the scene
  220. renderer.setRenderTarget(pickingTexture);
  221. renderer.render(scene, camera);
  222. renderer.setRenderTarget(null);
  223. // clear the view offset so rendering returns to normal
  224. camera.clearViewOffset();
  225. //read the pixel
  226. renderer.readRenderTargetPixels(
  227. pickingTexture,
  228. 0, // x
  229. 0, // y
  230. 1, // width
  231. 1, // height
  232. pixelBuffer);
  233. const id =
  234. (pixelBuffer[0] << 0) |
  235. (pixelBuffer[1] << 8) |
  236. (pixelBuffer[2] << 16);
  237. return id;
  238. }
  239. }
  240. const pickHelper = new GPUPickHelper();
  241. function getCanvasRelativePosition(event) {
  242. const rect = canvas.getBoundingClientRect();
  243. return {
  244. x: (event.clientX - rect.left) * canvas.width / rect.width,
  245. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  246. };
  247. }
  248. function pickCountry(event) {
  249. // exit if we have not loaded the data yet
  250. if (!countryInfos) {
  251. return;
  252. }
  253. const position = getCanvasRelativePosition(event);
  254. const id = pickHelper.pick(position, pickingScene, camera);
  255. if (id > 0) {
  256. // we clicked a country. Toggle its 'selected' property
  257. const countryInfo = countryInfos[id - 1];
  258. const selected = !countryInfo.selected;
  259. // if we're selecting this country and modifiers are not
  260. // pressed unselect everything else.
  261. if (selected && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  262. unselectAllCountries();
  263. }
  264. numCountriesSelected += selected ? 1 : -1;
  265. countryInfo.selected = selected;
  266. } else if (numCountriesSelected) {
  267. unselectAllCountries();
  268. }
  269. requestRenderIfNotRequested();
  270. }
  271. function unselectAllCountries() {
  272. numCountriesSelected = 0;
  273. countryInfos.forEach((countryInfo) => {
  274. countryInfo.selected = false;
  275. });
  276. }
  277. canvas.addEventListener('pointerup', pickCountry);
  278. function resizeRendererToDisplaySize(renderer) {
  279. const canvas = renderer.domElement;
  280. const width = canvas.clientWidth;
  281. const height = canvas.clientHeight;
  282. const needResize = canvas.width !== width || canvas.height !== height;
  283. if (needResize) {
  284. renderer.setSize(width, height, false);
  285. }
  286. return needResize;
  287. }
  288. let renderRequested = false;
  289. function render() {
  290. renderRequested = undefined;
  291. if (resizeRendererToDisplaySize(renderer)) {
  292. const canvas = renderer.domElement;
  293. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  294. camera.updateProjectionMatrix();
  295. }
  296. controls.update();
  297. updateLabels();
  298. renderer.render(scene, camera);
  299. }
  300. render();
  301. function requestRenderIfNotRequested() {
  302. if (!renderRequested) {
  303. renderRequested = true;
  304. requestAnimationFrame(render);
  305. }
  306. }
  307. controls.addEventListener('change', requestRenderIfNotRequested);
  308. window.addEventListener('resize', requestRenderIfNotRequested);
  309. }
  310. main();
  311. </script>
  312. </html>