threejs-lots-of-objects-morphtargets-w-colors.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 w/colors</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 type="module">
  44. import * as THREE from './resources/threejs/r114/build/three.module.js';
  45. import {BufferGeometryUtils} from './resources/threejs/r114/examples/jsm/utils/BufferGeometryUtils.js';
  46. import {OrbitControls} from './resources/threejs/r114/examples/jsm/controls/OrbitControls.js';
  47. import {TWEEN} from './resources/threejs/r114/examples/jsm/libs/tween.module.min.js';
  48. class TweenManger {
  49. constructor() {
  50. this.numTweensRunning = 0;
  51. }
  52. _handleComplete() {
  53. --this.numTweensRunning;
  54. console.assert(this.numTweensRunning >= 0); /* eslint no-console: off */
  55. }
  56. createTween(targetObject) {
  57. const self = this;
  58. ++this.numTweensRunning;
  59. let userCompleteFn = () => {};
  60. // create a new tween and install our own onComplete callback
  61. const tween = new TWEEN.Tween(targetObject).onComplete(function(...args) {
  62. self._handleComplete();
  63. userCompleteFn.call(this, ...args);
  64. });
  65. // replace the tween's onComplete function with our own
  66. // so we can call the user's callback if they supply one.
  67. tween.onComplete = (fn) => {
  68. userCompleteFn = fn;
  69. return tween;
  70. };
  71. return tween;
  72. }
  73. update() {
  74. TWEEN.update();
  75. return this.numTweensRunning > 0;
  76. }
  77. }
  78. function main() {
  79. const canvas = document.querySelector('#c');
  80. const renderer = new THREE.WebGLRenderer({canvas});
  81. const tweenManager = new TweenManger();
  82. const fov = 60;
  83. const aspect = 2; // the canvas default
  84. const near = 0.1;
  85. const far = 10;
  86. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  87. camera.position.z = 2.5;
  88. const controls = new OrbitControls(camera, canvas);
  89. controls.enableDamping = true;
  90. controls.enablePan = false;
  91. controls.minDistance = 1.2;
  92. controls.maxDistance = 4;
  93. controls.update();
  94. const scene = new THREE.Scene();
  95. scene.background = new THREE.Color('black');
  96. {
  97. const loader = new THREE.TextureLoader();
  98. const texture = loader.load('resources/images/world.jpg', render);
  99. const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
  100. const material = new THREE.MeshBasicMaterial({map: texture});
  101. scene.add(new THREE.Mesh(geometry, material));
  102. }
  103. async function loadFile(url) {
  104. const req = await fetch(url);
  105. return req.text();
  106. }
  107. function parseData(text) {
  108. const data = [];
  109. const settings = {data};
  110. let max;
  111. let min;
  112. // split into lines
  113. text.split('\n').forEach((line) => {
  114. // split the line by whitespace
  115. const parts = line.trim().split(/\s+/);
  116. if (parts.length === 2) {
  117. // only 2 parts, must be a key/value pair
  118. settings[parts[0]] = parseFloat(parts[1]);
  119. } else if (parts.length > 2) {
  120. // more than 2 parts, must be data
  121. const values = parts.map((v) => {
  122. const value = parseFloat(v);
  123. if (value === settings.NODATA_value) {
  124. return undefined;
  125. }
  126. max = Math.max(max === undefined ? value : max, value);
  127. min = Math.min(min === undefined ? value : min, value);
  128. return value;
  129. });
  130. data.push(values);
  131. }
  132. });
  133. return Object.assign(settings, {min, max});
  134. }
  135. function dataMissingInAnySet(fileInfos, latNdx, lonNdx) {
  136. for (const fileInfo of fileInfos) {
  137. if (fileInfo.file.data[latNdx][lonNdx] === undefined) {
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. function makeBoxes(file, hueRange, fileInfos) {
  144. const {min, max, data} = file;
  145. const range = max - min;
  146. // these helpers will make it easy to position the boxes
  147. // We can rotate the lon helper on its Y axis to the longitude
  148. const lonHelper = new THREE.Object3D();
  149. scene.add(lonHelper);
  150. // We rotate the latHelper on its X axis to the latitude
  151. const latHelper = new THREE.Object3D();
  152. lonHelper.add(latHelper);
  153. // The position helper moves the object to the edge of the sphere
  154. const positionHelper = new THREE.Object3D();
  155. positionHelper.position.z = 1;
  156. latHelper.add(positionHelper);
  157. // Used to move the center of the cube so it scales from the position Z axis
  158. const originHelper = new THREE.Object3D();
  159. originHelper.position.z = 0.5;
  160. positionHelper.add(originHelper);
  161. const color = new THREE.Color();
  162. const lonFudge = Math.PI * .5;
  163. const latFudge = Math.PI * -0.135;
  164. const geometries = [];
  165. data.forEach((row, latNdx) => {
  166. row.forEach((value, lonNdx) => {
  167. if (dataMissingInAnySet(fileInfos, latNdx, lonNdx)) {
  168. return;
  169. }
  170. const amount = (value - min) / range;
  171. const boxWidth = 1;
  172. const boxHeight = 1;
  173. const boxDepth = 1;
  174. const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
  175. // adjust the helpers to point to the latitude and longitude
  176. lonHelper.rotation.y = THREE.MathUtils.degToRad(lonNdx + file.xllcorner) + lonFudge;
  177. latHelper.rotation.x = THREE.MathUtils.degToRad(latNdx + file.yllcorner) + latFudge;
  178. // use the world matrix of the origin helper to
  179. // position this geometry
  180. positionHelper.scale.set(0.005, 0.005, THREE.MathUtils.lerp(0.01, 0.5, amount));
  181. originHelper.updateWorldMatrix(true, false);
  182. geometry.applyMatrix4(originHelper.matrixWorld);
  183. // compute a color
  184. const hue = THREE.MathUtils.lerp(...hueRange, amount);
  185. const saturation = 1;
  186. const lightness = THREE.MathUtils.lerp(0.4, 1.0, amount);
  187. color.setHSL(hue, saturation, lightness);
  188. // get the colors as an array of values from 0 to 255
  189. const rgb = color.toArray().map(v => v * 255);
  190. // make an array to store colors for each vertex
  191. const numVerts = geometry.getAttribute('position').count;
  192. const itemSize = 3; // r, g, b
  193. const colors = new Uint8Array(itemSize * numVerts);
  194. // copy the color into the colors array for each vertex
  195. colors.forEach((v, ndx) => {
  196. colors[ndx] = rgb[ndx % 3];
  197. });
  198. const normalized = true;
  199. const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  200. geometry.setAttribute('color', colorAttrib);
  201. geometries.push(geometry);
  202. });
  203. });
  204. return BufferGeometryUtils.mergeBufferGeometries(
  205. geometries, false);
  206. }
  207. async function loadData(info) {
  208. const text = await loadFile(info.url);
  209. info.file = parseData(text);
  210. }
  211. async function loadAll() {
  212. const fileInfos = [
  213. {name: 'men', hueRange: [0.7, 0.3], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' },
  214. {name: 'women', hueRange: [0.9, 1.1], url: 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014ft_2010_cntm_1_deg.asc' },
  215. ];
  216. await Promise.all(fileInfos.map(loadData));
  217. function mapValues(data, fn) {
  218. return data.map((row, rowNdx) => {
  219. return row.map((value, colNdx) => {
  220. return fn(value, rowNdx, colNdx);
  221. });
  222. });
  223. }
  224. function makeDiffFile(baseFile, otherFile, compareFn) {
  225. let min;
  226. let max;
  227. const baseData = baseFile.data;
  228. const otherData = otherFile.data;
  229. const data = mapValues(baseData, (base, rowNdx, colNdx) => {
  230. const other = otherData[rowNdx][colNdx];
  231. if (base === undefined || other === undefined) {
  232. return undefined;
  233. }
  234. const value = compareFn(base, other);
  235. min = Math.min(min === undefined ? value : min, value);
  236. max = Math.max(max === undefined ? value : max, value);
  237. return value;
  238. });
  239. // make a copy of baseFile and replace min, max, and data
  240. // with the new data
  241. return Object.assign({}, baseFile, {
  242. min,
  243. max,
  244. data,
  245. });
  246. }
  247. // generate a new set of data
  248. {
  249. const menInfo = fileInfos[0];
  250. const womenInfo = fileInfos[1];
  251. const menFile = menInfo.file;
  252. const womenFile = womenInfo.file;
  253. function amountGreaterThan(a, b) {
  254. return Math.max(a - b, 0);
  255. }
  256. fileInfos.push({
  257. name: '>50%men',
  258. hueRange: [0.6, 1.1],
  259. file: makeDiffFile(menFile, womenFile, (men, women) => {
  260. return amountGreaterThan(men, women);
  261. }),
  262. });
  263. fileInfos.push({
  264. name: '>50% women',
  265. hueRange: [0.0, 0.4],
  266. file: makeDiffFile(womenFile, menFile, (women, men) => {
  267. return amountGreaterThan(women, men);
  268. }),
  269. });
  270. }
  271. // make geometry for each data set
  272. const geometries = fileInfos.map((info) => {
  273. return makeBoxes(info.file, info.hueRange, fileInfos);
  274. });
  275. // use the first geometry as the base
  276. // and add all the geometries as morphtargets
  277. const baseGeometry = geometries[0];
  278. baseGeometry.morphAttributes.position = geometries.map((geometry, ndx) => {
  279. const attribute = geometry.getAttribute('position');
  280. // put the number in front so we can more easily parse it later
  281. const name = `${ndx}target`;
  282. attribute.name = name;
  283. return attribute;
  284. });
  285. const colorAttributes = geometries.map((geometry, ndx) => {
  286. const attribute = geometry.getAttribute('color');
  287. const name = `morphColor${ndx}`;
  288. attribute.name = `color${ndx}`; // just for debugging
  289. return {name, attribute};
  290. });
  291. const material = new THREE.MeshBasicMaterial({
  292. vertexColors: THREE.VertexColors,
  293. morphTargets: true,
  294. });
  295. const vertexShaderReplacements = [
  296. {
  297. from: '#include <morphtarget_pars_vertex>',
  298. to: `
  299. uniform float morphTargetInfluences[8];
  300. `,
  301. },
  302. {
  303. from: '#include <morphnormal_vertex>',
  304. to: `
  305. `,
  306. },
  307. {
  308. from: '#include <morphtarget_vertex>',
  309. to: `
  310. transformed += (morphTarget0 - position) * morphTargetInfluences[0];
  311. transformed += (morphTarget1 - position) * morphTargetInfluences[1];
  312. transformed += (morphTarget2 - position) * morphTargetInfluences[2];
  313. transformed += (morphTarget3 - position) * morphTargetInfluences[3];
  314. `,
  315. },
  316. {
  317. from: '#include <color_pars_vertex>',
  318. to: `
  319. varying vec3 vColor;
  320. attribute vec3 morphColor0;
  321. attribute vec3 morphColor1;
  322. attribute vec3 morphColor2;
  323. attribute vec3 morphColor3;
  324. `,
  325. },
  326. {
  327. from: '#include <color_vertex>',
  328. to: `
  329. vColor.xyz = morphColor0 * morphTargetInfluences[0] +
  330. morphColor1 * morphTargetInfluences[1] +
  331. morphColor2 * morphTargetInfluences[2] +
  332. morphColor3 * morphTargetInfluences[3];
  333. `,
  334. },
  335. ];
  336. material.onBeforeCompile = (shader) => {
  337. vertexShaderReplacements.forEach((rep) => {
  338. shader.vertexShader = shader.vertexShader.replace(rep.from, rep.to);
  339. });
  340. };
  341. const mesh = new THREE.Mesh(baseGeometry, material);
  342. scene.add(mesh);
  343. mesh.onBeforeRender = function(renderer, scene, camera, geometry) {
  344. // remove all the color attributes
  345. for (const {name} of colorAttributes) {
  346. geometry.deleteAttribute(name);
  347. }
  348. for (let i = 0; i < colorAttributes.length; ++i) {
  349. const attrib = geometry.getAttribute(`morphTarget${i}`);
  350. if (!attrib) {
  351. break;
  352. }
  353. // The name will be something like "2target" as we named it above
  354. // where 2 is the index of the data set
  355. const ndx = parseInt(attrib.name);
  356. const name = `morphColor${i}`;
  357. geometry.setAttribute(name, colorAttributes[ndx].attribute);
  358. }
  359. };
  360. // show the selected data, hide the rest
  361. function showFileInfo(fileInfos, fileInfo) {
  362. fileInfos.forEach((info) => {
  363. const visible = fileInfo === info;
  364. info.elem.className = visible ? 'selected' : '';
  365. const targets = {};
  366. fileInfos.forEach((info, i) => {
  367. targets[i] = info === fileInfo ? 1 : 0;
  368. });
  369. const durationInMs = 1000;
  370. tweenManager.createTween(mesh.morphTargetInfluences)
  371. .to(targets, durationInMs)
  372. .start();
  373. });
  374. requestRenderIfNotRequested();
  375. }
  376. const uiElem = document.querySelector('#ui');
  377. fileInfos.forEach((info) => {
  378. const div = document.createElement('div');
  379. info.elem = div;
  380. div.textContent = info.name;
  381. uiElem.appendChild(div);
  382. function show() {
  383. showFileInfo(fileInfos, info);
  384. }
  385. div.addEventListener('mouseover', show);
  386. div.addEventListener('touchstart', show);
  387. });
  388. // show the first set of data
  389. showFileInfo(fileInfos, fileInfos[0]);
  390. }
  391. loadAll();
  392. function resizeRendererToDisplaySize(renderer) {
  393. const canvas = renderer.domElement;
  394. const width = canvas.clientWidth;
  395. const height = canvas.clientHeight;
  396. const needResize = canvas.width !== width || canvas.height !== height;
  397. if (needResize) {
  398. renderer.setSize(width, height, false);
  399. }
  400. return needResize;
  401. }
  402. let renderRequested = false;
  403. function render() {
  404. renderRequested = undefined;
  405. if (resizeRendererToDisplaySize(renderer)) {
  406. const canvas = renderer.domElement;
  407. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  408. camera.updateProjectionMatrix();
  409. }
  410. if (tweenManager.update()) {
  411. requestRenderIfNotRequested();
  412. }
  413. controls.update();
  414. renderer.render(scene, camera);
  415. }
  416. render();
  417. function requestRenderIfNotRequested() {
  418. if (!renderRequested) {
  419. renderRequested = true;
  420. requestAnimationFrame(render);
  421. }
  422. }
  423. controls.addEventListener('change', requestRenderIfNotRequested);
  424. window.addEventListener('resize', requestRenderIfNotRequested);
  425. }
  426. main();
  427. </script>
  428. </html>