lots-of-objects-animated.html 12 KB

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