indexed-textures.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Indexed Textures for Picking and Color</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – Indexed Textures for Picking and Color">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="../resources/lesson.css">
  12. <link rel="stylesheet" href="../resources/lang.css">
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../../build/three.module.js"
  17. }
  18. }
  19. </script>
  20. </head>
  21. <body>
  22. <div class="container">
  23. <div class="lesson-title">
  24. <h1>Indexed Textures for Picking and Color</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>This article is a continuation of <a href="align-html-elements-to-3d.html">an article about aligning html elements to 3d</a>.
  29. If you haven't read that yet you should start there before continuing here.</p>
  30. <p>Sometimes using three.js requires coming up with creative solutions.
  31. I'm not sure this is a great solution but I thought I'd share it and
  32. you can see if it suggests any solutions for your needs.</p>
  33. <p>In the <a href="align-html-elements-to-3d.html">previous article</a> we
  34. displayed country names around a 3d globe. How would we go about letting
  35. the user select a country and show their selection?</p>
  36. <p>The first idea that comes to mind is to generate geometry for each country.
  37. We could <a href="picking.html">use a picking solution</a> like we covered before.
  38. We'd build 3D geometry for each country. If the user clicks on the mesh for
  39. that country we'd know what country was clicked.</p>
  40. <p>So, just to check that solution I tried generating 3D meshes of all the countries
  41. using the same data I used to generate the outlines
  42. <a href="align-html-elements-to-3d.html">in the previous article</a>.
  43. The result was a 15.5meg binary GLTF (.glb) file. Making the user download 15.5meg
  44. sounds like too much to me.</p>
  45. <p>There are lots of ways to compress the data. The first would probably be
  46. to apply some algorithm to lower the resolution of the outlines. I didn't spend
  47. any time pursuing that solution. For borders of the USA that's probably a huge
  48. win. For a borders of Canada probably much less. </p>
  49. <p>Another solution would be to use just actual data compression. For example gzipping
  50. the file brought it down to 11meg. That's 30% less but arguably not enough.</p>
  51. <p>We could store all the data as 16bit ranged values instead of 32bit float values.
  52. Or we could use something like <a href="https://google.github.io/draco/">draco compression</a>
  53. and maybe that would be enough. I didn't check and I would encourage you to check
  54. yourself and tell me how it goes as I'd love to know. 😅</p>
  55. <p>In my case I thought about <a href="picking.html">the GPU picking solution</a>
  56. we covered at the end of <a href="picking.html">the article on picking</a>. In
  57. that solution we drew every mesh with a unique color that represented that
  58. mesh's id. We then drew all the meshes and looked at the color that was clicked
  59. on.</p>
  60. <p>Taking inspiration from that we could pre-generate a map of countries where
  61. each country's color is its index number in our array of countries. We could
  62. then use a similar GPU picking technique. We'd draw the globe off screen using
  63. this index texture. Looking at the color of the pixel the user clicks would
  64. tell us the country id.</p>
  65. <p>So, I <a href="https://github.com/mrdoob/three.js/blob/master/manual/resources/tools/geo-picking/">wrote some code</a>
  66. to generate such a texture. Here it is. </p>
  67. <div class="threejs_center"><img src="../examples/resources/data/world/country-index-texture.png" style="width: 700px;"></div>
  68. <p>Note: The data used to generate this texture comes from <a href="http://thematicmapping.org/downloads/world_borders.php">this website</a>
  69. and is therefore licensed as <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>.</p>
  70. <p>It's only 217k, much better than the 14meg for the country meshes. In fact we could probably
  71. even lower the resolution but 217k seems good enough for now.</p>
  72. <p>So let's try using it for picking countries.</p>
  73. <p>Grabbing code from the <a href="picking.html">gpu picking example</a> we need
  74. a scene for picking.</p>
  75. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const pickingScene = new THREE.Scene();
  76. pickingScene.background = new THREE.Color(0);
  77. </pre>
  78. <p>and we need to add the globe with the our index texture to the
  79. picking scene.</p>
  80. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  81. const loader = new THREE.TextureLoader();
  82. const geometry = new THREE.SphereGeometry(1, 64, 32);
  83. + const indexTexture = loader.load('resources/data/world/country-index-texture.png', render);
  84. + indexTexture.minFilter = THREE.NearestFilter;
  85. + indexTexture.magFilter = THREE.NearestFilter;
  86. +
  87. + const pickingMaterial = new THREE.MeshBasicMaterial({map: indexTexture});
  88. + pickingScene.add(new THREE.Mesh(geometry, pickingMaterial));
  89. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  90. const material = new THREE.MeshBasicMaterial({map: texture});
  91. scene.add(new THREE.Mesh(geometry, material));
  92. }
  93. </pre>
  94. <p>Then let's copy over the <code class="notranslate" translate="no">GPUPickingHelper</code> class we used
  95. before with a few minor changes.</p>
  96. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class GPUPickHelper {
  97. constructor() {
  98. // create a 1x1 pixel render target
  99. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  100. this.pixelBuffer = new Uint8Array(4);
  101. - this.pickedObject = null;
  102. - this.pickedObjectSavedColor = 0;
  103. }
  104. pick(cssPosition, scene, camera) {
  105. const {pickingTexture, pixelBuffer} = this;
  106. // set the view offset to represent just a single pixel under the mouse
  107. const pixelRatio = renderer.getPixelRatio();
  108. camera.setViewOffset(
  109. renderer.getContext().drawingBufferWidth, // full width
  110. renderer.getContext().drawingBufferHeight, // full top
  111. cssPosition.x * pixelRatio | 0, // rect x
  112. cssPosition.y * pixelRatio | 0, // rect y
  113. 1, // rect width
  114. 1, // rect height
  115. );
  116. // render the scene
  117. renderer.setRenderTarget(pickingTexture);
  118. renderer.render(scene, camera);
  119. renderer.setRenderTarget(null);
  120. // clear the view offset so rendering returns to normal
  121. camera.clearViewOffset();
  122. //read the pixel
  123. renderer.readRenderTargetPixels(
  124. pickingTexture,
  125. 0, // x
  126. 0, // y
  127. 1, // width
  128. 1, // height
  129. pixelBuffer);
  130. + const id =
  131. + (pixelBuffer[0] &lt;&lt; 16) |
  132. + (pixelBuffer[1] &lt;&lt; 8) |
  133. + (pixelBuffer[2] &lt;&lt; 0);
  134. +
  135. + return id;
  136. - const id =
  137. - (pixelBuffer[0] &lt;&lt; 16) |
  138. - (pixelBuffer[1] &lt;&lt; 8) |
  139. - (pixelBuffer[2] );
  140. - const intersectedObject = idToObject[id];
  141. - if (intersectedObject) {
  142. - // pick the first object. It's the closest one
  143. - this.pickedObject = intersectedObject;
  144. - // save its color
  145. - this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
  146. - // set its emissive color to flashing red/yellow
  147. - this.pickedObject.material.emissive.setHex((time * 8) % 2 &gt; 1 ? 0xFFFF00 : 0xFF0000);
  148. - }
  149. }
  150. }
  151. </pre>
  152. <p>Now we can use that to pick countries.</p>
  153. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const pickHelper = new GPUPickHelper();
  154. function getCanvasRelativePosition(event) {
  155. const rect = canvas.getBoundingClientRect();
  156. return {
  157. x: (event.clientX - rect.left) * canvas.width / rect.width,
  158. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  159. };
  160. }
  161. function pickCountry(event) {
  162. // exit if we have not loaded the data yet
  163. if (!countryInfos) {
  164. return;
  165. }
  166. const position = getCanvasRelativePosition(event);
  167. const id = pickHelper.pick(position, pickingScene, camera);
  168. if (id &gt; 0) {
  169. // we clicked a country. Toggle its 'selected' property
  170. const countryInfo = countryInfos[id - 1];
  171. const selected = !countryInfo.selected;
  172. // if we're selecting this country and modifiers are not
  173. // pressed unselect everything else.
  174. if (selected &amp;&amp; !event.shiftKey &amp;&amp; !event.ctrlKey &amp;&amp; !event.metaKey) {
  175. unselectAllCountries();
  176. }
  177. numCountriesSelected += selected ? 1 : -1;
  178. countryInfo.selected = selected;
  179. } else if (numCountriesSelected) {
  180. // the ocean or sky was clicked
  181. unselectAllCountries();
  182. }
  183. requestRenderIfNotRequested();
  184. }
  185. function unselectAllCountries() {
  186. numCountriesSelected = 0;
  187. countryInfos.forEach((countryInfo) =&gt; {
  188. countryInfo.selected = false;
  189. });
  190. }
  191. canvas.addEventListener('pointerup', pickCountry);
  192. </pre>
  193. <p>The code above sets/unsets the <code class="notranslate" translate="no">selected</code> property on
  194. the array of countries. If <code class="notranslate" translate="no">shift</code> or <code class="notranslate" translate="no">ctrl</code> or <code class="notranslate" translate="no">cmd</code>
  195. is pressed then you can select more than one country.</p>
  196. <p>All that's left is showing the selected countries. For now
  197. let's just update the labels.</p>
  198. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">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} = countryInfo;
  210. - // large enough?
  211. - if (area &lt; large) {
  212. + const {position, elem, area, selected} = countryInfo;
  213. + const largeEnough = area &gt;= large;
  214. + const show = selected || (numCountriesSelected === 0 &amp;&amp; largeEnough);
  215. + if (!show) {
  216. elem.style.display = 'none';
  217. continue;
  218. }
  219. ...
  220. </pre>
  221. <p>and with that we should be able to pick countries</p>
  222. <p></p><div translate="no" class="threejs_example_container notranslate">
  223. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/indexed-textures-picking.html"></iframe></div>
  224. <a class="threejs_center" href="/manual/examples/indexed-textures-picking.html" target="_blank">click here to open in a separate window</a>
  225. </div>
  226. <p></p>
  227. <p>The code stills shows countries based on their area but if you
  228. click one just that one will have a label.</p>
  229. <p>So that seems like a reasonable solution for picking countries
  230. but what about highlighting the selected countries?</p>
  231. <p>For that we can take inspiration from <em>paletted graphics</em>.</p>
  232. <p><a href="https://en.wikipedia.org/wiki/Palette_%28computing%29">Paletted graphics</a>
  233. or <a href="https://en.wikipedia.org/wiki/Indexed_color">Indexed Color</a> is
  234. what older systems like the Atari 800, Amiga, NES,
  235. Super Nintendo, and even older IBM PCs used. Instead of storing bitmaps
  236. as RGBA colors 8bits per color, 32 bytes per pixel or more, they stored
  237. bitmaps as 8bit values or less. The value for each pixel was an index
  238. into a palette. So for example a value
  239. of 3 in the image means "display color 3". What color color#3 is is
  240. defined somewhere else called a "palette".</p>
  241. <p>In JavaScript you can think of it like this</p>
  242. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const face7x7PixelImageData = [
  243. 0, 1, 1, 1, 1, 1, 0,
  244. 1, 0, 0, 0, 0, 0, 1,
  245. 1, 0, 2, 0, 2, 0, 1,
  246. 1, 0, 0, 0, 0, 0, 1,
  247. 1, 0, 3, 3, 3, 0, 1,
  248. 1, 0, 0, 0, 0, 0, 1,
  249. 0, 1, 1, 1, 1, 1, 1,
  250. ];
  251. const palette = [
  252. [255, 255, 255], // white
  253. [ 0, 0, 0], // black
  254. [ 0, 255, 255], // cyan
  255. [255, 0, 0], // red
  256. ];
  257. </pre>
  258. <p>Where each pixel in the image data is an index into palette. If you interpreted
  259. the image data through the palette above you'd get this image</p>
  260. <div class="threejs_center"><img src="../resources/images/7x7-indexed-face.png"></div>
  261. <p>In our case we already have a texture above that has a different id
  262. per country. So, we could use that same texture through a palette
  263. texture to give each country its own color. By changing the palette
  264. texture we can color each individual country. For example by setting
  265. the entire palette texture to black and then for one country's entry
  266. in the palette a different color, we can highlight just that country.</p>
  267. <p>To do paletted index graphics requires some custom shader code.
  268. Let's modify the default shaders in three.js.
  269. That way we can use lighting and other features if we want.</p>
  270. <p>Like we covered in <a href="optimize-lots-of-objects-animated.html">the article on animating lots of objects</a>
  271. we can modify the default shaders by adding a function to a material's
  272. <code class="notranslate" translate="no">onBeforeCompile</code> property.</p>
  273. <p>The default fragment shader looks something like this before compiling.</p>
  274. <pre class="prettyprint showlinemods notranslate lang-glsl" translate="no">#include &lt;common&gt;
  275. #include &lt;color_pars_fragment&gt;
  276. #include &lt;uv_pars_fragment&gt;
  277. #include &lt;map_pars_fragment&gt;
  278. #include &lt;alphamap_pars_fragment&gt;
  279. #include &lt;aomap_pars_fragment&gt;
  280. #include &lt;lightmap_pars_fragment&gt;
  281. #include &lt;envmap_pars_fragment&gt;
  282. #include &lt;fog_pars_fragment&gt;
  283. #include &lt;specularmap_pars_fragment&gt;
  284. #include &lt;logdepthbuf_pars_fragment&gt;
  285. #include &lt;clipping_planes_pars_fragment&gt;
  286. void main() {
  287. #include &lt;clipping_planes_fragment&gt;
  288. vec4 diffuseColor = vec4( diffuse, opacity );
  289. #include &lt;logdepthbuf_fragment&gt;
  290. #include &lt;map_fragment&gt;
  291. #include &lt;color_fragment&gt;
  292. #include &lt;alphamap_fragment&gt;
  293. #include &lt;alphatest_fragment&gt;
  294. #include &lt;specularmap_fragment&gt;
  295. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  296. #ifdef USE_LIGHTMAP
  297. reflectedLight.indirectDiffuse += texture2D( lightMap, vLightMapUv ).xyz * lightMapIntensity;
  298. #else
  299. reflectedLight.indirectDiffuse += vec3( 1.0 );
  300. #endif
  301. #include &lt;aomap_fragment&gt;
  302. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  303. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  304. #include &lt;envmap_fragment&gt;
  305. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  306. #include &lt;premultiplied_alpha_fragment&gt;
  307. #include &lt;tonemapping_fragment&gt;
  308. #include &lt;colorspace_fragment&gt;
  309. #include &lt;fog_fragment&gt;
  310. }
  311. </pre>
  312. <p><a href="https://github.com/mrdoob/three.js/tree/dev/src/renderers/shaders/ShaderChunk">Digging through all those snippets</a>
  313. we find that three.js uses a variable called <code class="notranslate" translate="no">diffuseColor</code> to manage the
  314. base material color. It sets this in the <code class="notranslate" translate="no">&lt;color_fragment&gt;</code> <a href="https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/color_fragment.glsl.js">snippet</a>
  315. so we should be able to modify it after that point.</p>
  316. <p><code class="notranslate" translate="no">diffuseColor</code> at that point in the shader should already be the color from
  317. our outline texture so we can look up the color from a palette texture
  318. and mix them for the final result.</p>
  319. <p>Like we <a href="optimize-lots-of-objects-animated.html">did before</a> we'll make an array
  320. of search and replacement strings and apply them to the shader in
  321. <a href="/docs/#api/en/materials/Material.onBeforeCompile"><code class="notranslate" translate="no">Material.onBeforeCompile</code></a>.</p>
  322. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  323. const loader = new THREE.TextureLoader();
  324. const geometry = new THREE.SphereGeometry(1, 64, 32);
  325. const indexTexture = loader.load('resources/data/world/country-index-texture.png', render);
  326. indexTexture.minFilter = THREE.NearestFilter;
  327. indexTexture.magFilter = THREE.NearestFilter;
  328. const pickingMaterial = new THREE.MeshBasicMaterial({map: indexTexture});
  329. pickingScene.add(new THREE.Mesh(geometry, pickingMaterial));
  330. + const fragmentShaderReplacements = [
  331. + {
  332. + from: '#include &lt;common&gt;',
  333. + to: `
  334. + #include &lt;common&gt;
  335. + uniform sampler2D indexTexture;
  336. + uniform sampler2D paletteTexture;
  337. + uniform float paletteTextureWidth;
  338. + `,
  339. + },
  340. + {
  341. + from: '#include &lt;color_fragment&gt;',
  342. + to: `
  343. + #include &lt;color_fragment&gt;
  344. + {
  345. + vec4 indexColor = texture2D(indexTexture, vUv);
  346. + float index = indexColor.r * 255.0 + indexColor.g * 255.0 * 256.0;
  347. + vec2 paletteUV = vec2((index + 0.5) / paletteTextureWidth, 0.5);
  348. + vec4 paletteColor = texture2D(paletteTexture, paletteUV);
  349. + // diffuseColor.rgb += paletteColor.rgb; // white outlines
  350. + diffuseColor.rgb = paletteColor.rgb - diffuseColor.rgb; // black outlines
  351. + }
  352. + `,
  353. + },
  354. + ];
  355. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  356. const material = new THREE.MeshBasicMaterial({map: texture});
  357. + material.onBeforeCompile = function(shader) {
  358. + fragmentShaderReplacements.forEach((rep) =&gt; {
  359. + shader.fragmentShader = shader.fragmentShader.replace(rep.from, rep.to);
  360. + });
  361. + };
  362. scene.add(new THREE.Mesh(geometry, material));
  363. }
  364. </pre>
  365. <p>Above can see above we add 3 uniforms, <code class="notranslate" translate="no">indexTexture</code>, <code class="notranslate" translate="no">paletteTexture</code>,
  366. and <code class="notranslate" translate="no">paletteTextureWidth</code>. We get a color from the <code class="notranslate" translate="no">indexTexture</code>
  367. and convert it to an index. <code class="notranslate" translate="no">vUv</code> is the texture coordinates provided by
  368. three.js. We then use that index to get a color out of the palette texture.
  369. We then mix the result with the current <code class="notranslate" translate="no">diffuseColor</code>. The <code class="notranslate" translate="no">diffuseColor</code>
  370. at this point is our black and white outline texture so if we add the 2 colors
  371. we'll get white outlines. If we subtract the current diffuse color we'll get
  372. black outlines.</p>
  373. <p>Before we can render we need to setup the palette texture
  374. and these 3 uniforms.</p>
  375. <p>For the palette texture it just needs to be wide enough to
  376. hold one color per country + one for the ocean (id = 0).
  377. There are 240 something countries. We could wait until the
  378. list of countries loads to get an exact number or look it up.
  379. There's not much harm in just picking some larger number so
  380. let's choose 512.</p>
  381. <p>Here's the code to create the palette texture</p>
  382. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const maxNumCountries = 512;
  383. const paletteTextureWidth = maxNumCountries;
  384. const paletteTextureHeight = 1;
  385. const palette = new Uint8Array(paletteTextureWidth * 4);
  386. const paletteTexture = new THREE.DataTexture(
  387. palette, paletteTextureWidth, paletteTextureHeight);
  388. paletteTexture.minFilter = THREE.NearestFilter;
  389. paletteTexture.magFilter = THREE.NearestFilter;
  390. </pre>
  391. <p>A <a href="/docs/#api/en/textures/DataTexture"><code class="notranslate" translate="no">DataTexture</code></a> let's us give a texture raw data. In this case
  392. we're giving it 512 RGBA colors, 4 bytes each where each byte is
  393. red, green, and blue respectively using values that go from 0 to 255.</p>
  394. <p>Let's fill it with random colors just to see it work</p>
  395. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">for (let i = 1; i &lt; palette.length; ++i) {
  396. palette[i] = Math.random() * 256;
  397. }
  398. // set the ocean color (index #0)
  399. palette.set([100, 200, 255, 255], 0);
  400. paletteTexture.needsUpdate = true;
  401. </pre>
  402. <p>Anytime we want three.js to update the palette texture with
  403. the contents of the <code class="notranslate" translate="no">palette</code> array we need to set <code class="notranslate" translate="no">paletteTexture.needsUpdate</code>
  404. to <code class="notranslate" translate="no">true</code>.</p>
  405. <p>And then we still need to set the uniforms on the material.</p>
  406. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const geometry = new THREE.SphereGeometry(1, 64, 32);
  407. const material = new THREE.MeshBasicMaterial({map: texture});
  408. material.onBeforeCompile = function(shader) {
  409. fragmentShaderReplacements.forEach((rep) =&gt; {
  410. shader.fragmentShader = shader.fragmentShader.replace(rep.from, rep.to);
  411. });
  412. + shader.uniforms.paletteTexture = {value: paletteTexture};
  413. + shader.uniforms.indexTexture = {value: indexTexture};
  414. + shader.uniforms.paletteTextureWidth = {value: paletteTextureWidth};
  415. };
  416. scene.add(new THREE.Mesh(geometry, material));
  417. </pre>
  418. <p>and with that we get randomly colored countries.</p>
  419. <p></p><div translate="no" class="threejs_example_container notranslate">
  420. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/indexed-textures-random-colors.html"></iframe></div>
  421. <a class="threejs_center" href="/manual/examples/indexed-textures-random-colors.html" target="_blank">click here to open in a separate window</a>
  422. </div>
  423. <p></p>
  424. <p>Now that we can see the index and palette textures are working
  425. let's manipulate the palette for highlighting.</p>
  426. <p>First let's make function that will let us pass in a three.js
  427. style color and give us values we can put in the palette texture.</p>
  428. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const tempColor = new THREE.Color();
  429. function get255BasedColor(color) {
  430. tempColor.set(color);
  431. const base = tempColor.toArray().map(v =&gt; v * 255);
  432. base.push(255); // alpha
  433. return base;
  434. }
  435. </pre>
  436. <p>Calling it like this <code class="notranslate" translate="no">color = get255BasedColor('red')</code> will
  437. return an array like <code class="notranslate" translate="no">[255, 0, 0, 255]</code>.</p>
  438. <p>Next let's use it to make a few colors and fill out the
  439. palette.</p>
  440. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const selectedColor = get255BasedColor('red');
  441. const unselectedColor = get255BasedColor('#444');
  442. const oceanColor = get255BasedColor('rgb(100,200,255)');
  443. resetPalette();
  444. function setPaletteColor(index, color) {
  445. palette.set(color, index * 4);
  446. }
  447. function resetPalette() {
  448. // make all colors the unselected color
  449. for (let i = 1; i &lt; maxNumCountries; ++i) {
  450. setPaletteColor(i, unselectedColor);
  451. }
  452. // set the ocean color (index #0)
  453. setPaletteColor(0, oceanColor);
  454. paletteTexture.needsUpdate = true;
  455. }
  456. </pre>
  457. <p>Now let's use those functions to update the palette when a country
  458. is selected</p>
  459. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function getCanvasRelativePosition(event) {
  460. const rect = canvas.getBoundingClientRect();
  461. return {
  462. x: (event.clientX - rect.left) * canvas.width / rect.width,
  463. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  464. };
  465. }
  466. function pickCountry(event) {
  467. // exit if we have not loaded the data yet
  468. if (!countryInfos) {
  469. return;
  470. }
  471. const position = getCanvasRelativePosition(event);
  472. const id = pickHelper.pick(position, pickingScene, camera);
  473. if (id &gt; 0) {
  474. const countryInfo = countryInfos[id - 1];
  475. const selected = !countryInfo.selected;
  476. if (selected &amp;&amp; !event.shiftKey &amp;&amp; !event.ctrlKey &amp;&amp; !event.metaKey) {
  477. unselectAllCountries();
  478. }
  479. numCountriesSelected += selected ? 1 : -1;
  480. countryInfo.selected = selected;
  481. + setPaletteColor(id, selected ? selectedColor : unselectedColor);
  482. + paletteTexture.needsUpdate = true;
  483. } else if (numCountriesSelected) {
  484. unselectAllCountries();
  485. }
  486. requestRenderIfNotRequested();
  487. }
  488. function unselectAllCountries() {
  489. numCountriesSelected = 0;
  490. countryInfos.forEach((countryInfo) =&gt; {
  491. countryInfo.selected = false;
  492. });
  493. + resetPalette();
  494. }
  495. </pre>
  496. <p>and we that we should be able to highlight 1 or more countries.</p>
  497. <p></p><div translate="no" class="threejs_example_container notranslate">
  498. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/indexed-textures-picking-and-highlighting.html"></iframe></div>
  499. <a class="threejs_center" href="/manual/examples/indexed-textures-picking-and-highlighting.html" target="_blank">click here to open in a separate window</a>
  500. </div>
  501. <p></p>
  502. <p>That seems to work!</p>
  503. <p>One minor thing is we can't spin the globe without changing
  504. the selection state. If we select a country and then want to
  505. rotate the globe the selection will change.</p>
  506. <p>Let's try to fix that. Off the top of my head we can check 2 things.
  507. How much time passed between clicking and letting go.
  508. Another is did the user actually move the mouse. If the
  509. time is short or if they didn't move the mouse then it
  510. was probably a click. Otherwise they were probably trying
  511. to drag the globe.</p>
  512. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+const maxClickTimeMs = 200;
  513. +const maxMoveDeltaSq = 5 * 5;
  514. +const startPosition = {};
  515. +let startTimeMs;
  516. +
  517. +function recordStartTimeAndPosition(event) {
  518. + startTimeMs = performance.now();
  519. + const pos = getCanvasRelativePosition(event);
  520. + startPosition.x = pos.x;
  521. + startPosition.y = pos.y;
  522. +}
  523. function getCanvasRelativePosition(event) {
  524. const rect = canvas.getBoundingClientRect();
  525. return {
  526. x: (event.clientX - rect.left) * canvas.width / rect.width,
  527. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  528. };
  529. }
  530. function pickCountry(event) {
  531. // exit if we have not loaded the data yet
  532. if (!countryInfos) {
  533. return;
  534. }
  535. + // if it's been a moment since the user started
  536. + // then assume it was a drag action, not a select action
  537. + const clickTimeMs = performance.now() - startTimeMs;
  538. + if (clickTimeMs &gt; maxClickTimeMs) {
  539. + return;
  540. + }
  541. +
  542. + // if they moved assume it was a drag action
  543. + const position = getCanvasRelativePosition(event);
  544. + const moveDeltaSq = (startPosition.x - position.x) ** 2 +
  545. + (startPosition.y - position.y) ** 2;
  546. + if (moveDeltaSq &gt; maxMoveDeltaSq) {
  547. + return;
  548. + }
  549. - const position = {x: event.clientX, y: event.clientY};
  550. const id = pickHelper.pick(position, pickingScene, camera);
  551. if (id &gt; 0) {
  552. const countryInfo = countryInfos[id - 1];
  553. const selected = !countryInfo.selected;
  554. if (selected &amp;&amp; !event.shiftKey &amp;&amp; !event.ctrlKey &amp;&amp; !event.metaKey) {
  555. unselectAllCountries();
  556. }
  557. numCountriesSelected += selected ? 1 : -1;
  558. countryInfo.selected = selected;
  559. setPaletteColor(id, selected ? selectedColor : unselectedColor);
  560. paletteTexture.needsUpdate = true;
  561. } else if (numCountriesSelected) {
  562. unselectAllCountries();
  563. }
  564. requestRenderIfNotRequested();
  565. }
  566. function unselectAllCountries() {
  567. numCountriesSelected = 0;
  568. countryInfos.forEach((countryInfo) =&gt; {
  569. countryInfo.selected = false;
  570. });
  571. resetPalette();
  572. }
  573. +canvas.addEventListener('pointerdown', recordStartTimeAndPosition);
  574. canvas.addEventListener('pointerup', pickCountry);
  575. </pre>
  576. <p>and with those changes it <em>seems</em> like it works to me.</p>
  577. <p></p><div translate="no" class="threejs_example_container notranslate">
  578. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/indexed-textures-picking-debounced.html"></iframe></div>
  579. <a class="threejs_center" href="/manual/examples/indexed-textures-picking-debounced.html" target="_blank">click here to open in a separate window</a>
  580. </div>
  581. <p></p>
  582. <p>I'm not a UX expert so I'd love to hear if there is a better
  583. solution.</p>
  584. <p>I hope that gave you some idea of how indexed graphics can be useful
  585. and how you can modify the shaders three.js makes to add simple features.
  586. How to use GLSL, the language the shaders are written in, is too much for
  587. this article. There are a few links to some info in
  588. <a href="post-processing.html">the article on post processing</a>.</p>
  589. </div>
  590. </div>
  591. </div>
  592. <script src="../resources/prettify.js"></script>
  593. <script src="../resources/lesson.js"></script>
  594. </body></html>