lots-of-objects-multiple-data-sets.html 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 - Lots of Objects - Multiple Datasets</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. color: white;
  13. }
  14. #c {
  15. width: 100%;
  16. height: 100%;
  17. display: block;
  18. }
  19. #ui {
  20. position: absolute;
  21. left: 1em;
  22. top: 1em;
  23. }
  24. #ui>div {
  25. font-size: 20pt;
  26. padding: 1em;
  27. display: inline-block;
  28. }
  29. #ui>div.selected {
  30. color: red;
  31. }
  32. @media (max-width: 700px) {
  33. #ui>div {
  34. display: block;
  35. padding: .25em;
  36. }
  37. }
  38. </style>
  39. </head>
  40. <body>
  41. <canvas id="c"></canvas>
  42. <div id="ui"></div>
  43. </body>
  44. <script type="importmap">
  45. {
  46. "imports": {
  47. "three": "../../build/three.module.js",
  48. "three/addons/": "../../examples/jsm/"
  49. }
  50. }
  51. </script>
  52. <script type="module">
  53. import * as THREE from 'three';
  54. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  55. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  56. function main() {
  57. const canvas = document.querySelector( '#c' );
  58. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  59. const fov = 60;
  60. const aspect = 2; // the canvas default
  61. const near = 0.1;
  62. const far = 10;
  63. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  64. camera.position.z = 2.5;
  65. const controls = new OrbitControls( camera, canvas );
  66. controls.enableDamping = true;
  67. controls.enablePan = false;
  68. controls.minDistance = 1.2;
  69. controls.maxDistance = 4;
  70. controls.update();
  71. const scene = new THREE.Scene();
  72. scene.background = new THREE.Color( 'black' );
  73. {
  74. const loader = new THREE.TextureLoader();
  75. const texture = loader.load( 'resources/images/world.jpg', render );
  76. texture.colorSpace = THREE.SRGBColorSpace;
  77. const geometry = new THREE.SphereGeometry( 1, 64, 32 );
  78. const material = new THREE.MeshBasicMaterial( { map: texture } );
  79. scene.add( new THREE.Mesh( geometry, material ) );
  80. }
  81. async function loadFile( url ) {
  82. const req = await fetch( url );
  83. return req.text();
  84. }
  85. function parseData( text ) {
  86. const data = [];
  87. const settings = { data };
  88. let max;
  89. let min;
  90. // split into lines
  91. text.split( '\n' ).forEach( ( line ) => {
  92. // split the line by whitespace
  93. const parts = line.trim().split( /\s+/ );
  94. if ( parts.length === 2 ) {
  95. // only 2 parts, must be a key/value pair
  96. settings[ parts[ 0 ] ] = parseFloat( parts[ 1 ] );
  97. } else if ( parts.length > 2 ) {
  98. // more than 2 parts, must be data
  99. const values = parts.map( ( v ) => {
  100. const value = parseFloat( v );
  101. if ( value === settings.NODATA_value ) {
  102. return undefined;
  103. }
  104. max = Math.max( max === undefined ? value : max, value );
  105. min = Math.min( min === undefined ? value : min, value );
  106. return value;
  107. } );
  108. data.push( values );
  109. }
  110. } );
  111. return Object.assign( settings, { min, max } );
  112. }
  113. function addBoxes( file, hueRange ) {
  114. const { min, max, data } = file;
  115. const range = max - min;
  116. // these helpers will make it easy to position the boxes
  117. // We can rotate the lon helper on its Y axis to the longitude
  118. const lonHelper = new THREE.Object3D();
  119. scene.add( lonHelper );
  120. // We rotate the latHelper on its X axis to the latitude
  121. const latHelper = new THREE.Object3D();
  122. lonHelper.add( latHelper );
  123. // The position helper moves the object to the edge of the sphere
  124. const positionHelper = new THREE.Object3D();
  125. positionHelper.position.z = 1;
  126. latHelper.add( positionHelper );
  127. // Used to move the center of the cube so it scales from the position Z axis
  128. const originHelper = new THREE.Object3D();
  129. originHelper.position.z = 0.5;
  130. positionHelper.add( originHelper );
  131. const color = new THREE.Color();
  132. const lonFudge = Math.PI * .5;
  133. const latFudge = Math.PI * - 0.135;
  134. const geometries = [];
  135. data.forEach( ( row, latNdx ) => {
  136. row.forEach( ( value, lonNdx ) => {
  137. if ( value === undefined ) {
  138. return;
  139. }
  140. const amount = ( value - min ) / range;
  141. const boxWidth = 1;
  142. const boxHeight = 1;
  143. const boxDepth = 1;
  144. const geometry = new THREE.BoxGeometry( boxWidth, boxHeight, boxDepth );
  145. // adjust the helpers to point to the latitude and longitude
  146. lonHelper.rotation.y = THREE.MathUtils.degToRad( lonNdx + file.xllcorner ) + lonFudge;
  147. latHelper.rotation.x = THREE.MathUtils.degToRad( latNdx + file.yllcorner ) + latFudge;
  148. // use the world matrix of the origin helper to
  149. // position this geometry
  150. positionHelper.scale.set( 0.005, 0.005, THREE.MathUtils.lerp( 0.01, 0.5, amount ) );
  151. originHelper.updateWorldMatrix( true, false );
  152. geometry.applyMatrix4( originHelper.matrixWorld );
  153. // compute a color
  154. const hue = THREE.MathUtils.lerp( ...hueRange, amount );
  155. const saturation = 1;
  156. const lightness = THREE.MathUtils.lerp( 0.4, 1.0, amount );
  157. color.setHSL( hue, saturation, lightness );
  158. // get the colors as an array of values from 0 to 255
  159. const rgb = color.toArray().map( v => v * 255 );
  160. // make an array to store colors for each vertex
  161. const numVerts = geometry.getAttribute( 'position' ).count;
  162. const itemSize = 3; // r, g, b
  163. const colors = new Uint8Array( itemSize * numVerts );
  164. // copy the color into the colors array for each vertex
  165. colors.forEach( ( v, ndx ) => {
  166. colors[ ndx ] = rgb[ ndx % 3 ];
  167. } );
  168. const normalized = true;
  169. const colorAttrib = new THREE.BufferAttribute( colors, itemSize, normalized );
  170. geometry.setAttribute( 'color', colorAttrib );
  171. geometries.push( geometry );
  172. } );
  173. } );
  174. const mergedGeometry = BufferGeometryUtils.mergeGeometries(
  175. geometries, false );
  176. const material = new THREE.MeshBasicMaterial( {
  177. vertexColors: true,
  178. } );
  179. const mesh = new THREE.Mesh( mergedGeometry, material );
  180. scene.add( mesh );
  181. return mesh;
  182. }
  183. async function loadData( info ) {
  184. const text = await loadFile( info.url );
  185. info.file = parseData( text );
  186. }
  187. async function loadAll() {
  188. const fileInfos = [
  189. { name: 'men', hueRange: [ 0.7, 0.3 ], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
  190. { name: 'women', hueRange: [ 0.9, 1.1 ], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
  191. ];
  192. await Promise.all( fileInfos.map( loadData ) );
  193. function mapValues( data, fn ) {
  194. return data.map( ( row, rowNdx ) => {
  195. return row.map( ( value, colNdx ) => {
  196. return fn( value, rowNdx, colNdx );
  197. } );
  198. } );
  199. }
  200. function makeDiffFile( baseFile, otherFile, compareFn ) {
  201. let min;
  202. let max;
  203. const baseData = baseFile.data;
  204. const otherData = otherFile.data;
  205. const data = mapValues( baseData, ( base, rowNdx, colNdx ) => {
  206. const other = otherData[ rowNdx ][ colNdx ];
  207. if ( base === undefined || other === undefined ) {
  208. return undefined;
  209. }
  210. const value = compareFn( base, other );
  211. min = Math.min( min === undefined ? value : min, value );
  212. max = Math.max( max === undefined ? value : max, value );
  213. return value;
  214. } );
  215. // make a copy of baseFile and replace min, max, and data
  216. // with the new data
  217. return { ...baseFile, min, max, data };
  218. }
  219. // generate a new set of data
  220. {
  221. const menInfo = fileInfos[ 0 ];
  222. const womenInfo = fileInfos[ 1 ];
  223. const menFile = menInfo.file;
  224. const womenFile = womenInfo.file;
  225. function amountGreaterThan( a, b ) {
  226. return Math.max( a - b, 0 );
  227. }
  228. fileInfos.push( {
  229. name: '>50%men',
  230. hueRange: [ 0.6, 1.1 ],
  231. file: makeDiffFile( menFile, womenFile, ( men, women ) => {
  232. return amountGreaterThan( men, women );
  233. } ),
  234. } );
  235. fileInfos.push( {
  236. name: '>50% women',
  237. hueRange: [ 0.0, 0.4 ],
  238. file: makeDiffFile( womenFile, menFile, ( women, men ) => {
  239. return amountGreaterThan( women, men );
  240. } ),
  241. } );
  242. }
  243. // show the selected data, hide the rest
  244. function showFileInfo( fileInfos, fileInfo ) {
  245. fileInfos.forEach( ( info ) => {
  246. const visible = fileInfo === info;
  247. info.root.visible = visible;
  248. info.elem.className = visible ? 'selected' : '';
  249. } );
  250. requestRenderIfNotRequested();
  251. }
  252. const uiElem = document.querySelector( '#ui' );
  253. fileInfos.forEach( ( info ) => {
  254. const boxes = addBoxes( info.file, info.hueRange );
  255. info.root = boxes;
  256. const div = document.createElement( 'div' );
  257. info.elem = div;
  258. div.textContent = info.name;
  259. uiElem.appendChild( div );
  260. function show() {
  261. showFileInfo( fileInfos, info );
  262. }
  263. div.addEventListener( 'mouseover', show );
  264. div.addEventListener( 'touchstart', show );
  265. } );
  266. // show the first set of data
  267. showFileInfo( fileInfos, fileInfos[ 0 ] );
  268. }
  269. loadAll();
  270. function resizeRendererToDisplaySize( renderer ) {
  271. const canvas = renderer.domElement;
  272. const width = canvas.clientWidth;
  273. const height = canvas.clientHeight;
  274. const needResize = canvas.width !== width || canvas.height !== height;
  275. if ( needResize ) {
  276. renderer.setSize( width, height, false );
  277. }
  278. return needResize;
  279. }
  280. let renderRequested = false;
  281. function render() {
  282. renderRequested = undefined;
  283. if ( resizeRendererToDisplaySize( renderer ) ) {
  284. const canvas = renderer.domElement;
  285. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  286. camera.updateProjectionMatrix();
  287. }
  288. controls.update();
  289. renderer.render( scene, camera );
  290. }
  291. render();
  292. function requestRenderIfNotRequested() {
  293. if ( ! renderRequested ) {
  294. renderRequested = true;
  295. requestAnimationFrame( render );
  296. }
  297. }
  298. controls.addEventListener( 'change', requestRenderIfNotRequested );
  299. window.addEventListener( 'resize', requestRenderIfNotRequested );
  300. }
  301. main();
  302. </script>
  303. </html>