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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 - Morphtargets</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 dataMissingInAnySet(fileInfos, latNdx, lonNdx) {
  140. for (const fileInfo of fileInfos) {
  141. if (fileInfo.file.data[latNdx][lonNdx] === undefined) {
  142. return true;
  143. }
  144. }
  145. return false;
  146. }
  147. function makeBoxes(file, hueRange, fileInfos) {
  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 (dataMissingInAnySet(fileInfos, latNdx, lonNdx)) {
  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.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
  179. // adjust the helpers to point to the latitude and longitude
  180. lonHelper.rotation.y = THREE.Math.degToRad(lonNdx + file.xllcorner) + lonFudge;
  181. latHelper.rotation.x = THREE.Math.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.Math.lerp(0.01, 0.5, amount));
  185. originHelper.updateWorldMatrix(true, false);
  186. geometry.applyMatrix(originHelper.matrixWorld);
  187. // compute a color
  188. const hue = THREE.Math.lerp(...hueRange, amount);
  189. const saturation = 1;
  190. const lightness = THREE.Math.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.addAttribute('color', colorAttrib);
  205. geometries.push(geometry);
  206. });
  207. });
  208. return THREE.BufferGeometryUtils.mergeBufferGeometries(
  209. geometries, false);
  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. // make geometry for each data set
  276. const geometries = fileInfos.map((info) => {
  277. return makeBoxes(info.file, info.hueRange, fileInfos);
  278. });
  279. // use the first geometry as the base
  280. // and add all the geometries as morphtargets
  281. const baseGeometry = geometries[0];
  282. baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) => {
  283. const attribute = geometry.getAttribute('position');
  284. const name = `target${ndx}`;
  285. attribute.name = name;
  286. return attribute;
  287. });
  288. const material = new THREE.MeshBasicMaterial({
  289. vertexColors: THREE.VertexColors,
  290. morphTargets: true,
  291. });
  292. const mesh = new THREE.Mesh(baseGeometry, material);
  293. scene.add(mesh);
  294. // show the selected data, hide the rest
  295. function showFileInfo(fileInfos, fileInfo) {
  296. fileInfos.forEach((info) => {
  297. const visible = fileInfo === info;
  298. info.elem.className = visible ? 'selected' : '';
  299. const targets = {};
  300. fileInfos.forEach((info, i) => {
  301. targets[i] = info === fileInfo ? 1 : 0;
  302. });
  303. const durationInMs = 1000;
  304. tweenManager.createTween(mesh.morphTargetInfluences)
  305. .to(targets, durationInMs)
  306. .start();
  307. });
  308. requestRenderIfNotRequested();
  309. }
  310. const uiElem = document.querySelector('#ui');
  311. fileInfos.forEach((info) => {
  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>