threejs-lots-of-objects-animated.html 12 KB

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