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

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