lots-of-objects-animated.html 12 KB

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