threejs-lots-of-objects-multiple-data-sets.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 - Multiple Datasets</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>
  47. 'use strict';
  48. /* global THREE */
  49. function main() {
  50. const canvas = document.querySelector('#c');
  51. const renderer = new THREE.WebGLRenderer({canvas: canvas});
  52. const fov = 60;
  53. const aspect = 2; // the canvas default
  54. const near = 0.1;
  55. const far = 10;
  56. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  57. camera.position.z = 2.5;
  58. const controls = new THREE.OrbitControls(camera, canvas);
  59. controls.enableDamping = true;
  60. controls.dampingFactor = 0.05;
  61. controls.rotateSpeed = 0.1;
  62. controls.enablePan = false;
  63. controls.minDistance = 1.2;
  64. controls.maxDistance = 4;
  65. controls.update();
  66. const scene = new THREE.Scene();
  67. scene.background = new THREE.Color('black');
  68. {
  69. const loader = new THREE.TextureLoader();
  70. const texture = loader.load('resources/images/world.jpg', render);
  71. const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
  72. const material = new THREE.MeshBasicMaterial({map: texture});
  73. scene.add(new THREE.Mesh(geometry, material));
  74. }
  75. async function loadFile(url) {
  76. const req = await fetch(url);
  77. return req.text();
  78. }
  79. function parseData(text) {
  80. const data = [];
  81. const settings = {data};
  82. let max;
  83. let min;
  84. // split into lines
  85. text.split('\n').forEach((line) => {
  86. // split the line by whitespace
  87. const parts = line.trim().split(/\s+/);
  88. if (parts.length === 2) {
  89. // only 2 parts, must be a key/value pair
  90. settings[parts[0]] = parseFloat(parts[1]);
  91. } else if (parts.length > 2) {
  92. // more than 2 parts, must be data
  93. const values = parts.map((v) => {
  94. const value = parseFloat(v);
  95. if (value === settings.NODATA_value) {
  96. return undefined;
  97. }
  98. max = Math.max(max === undefined ? value : max, value);
  99. min = Math.min(min === undefined ? value : min, value);
  100. return value;
  101. });
  102. data.push(values);
  103. }
  104. });
  105. return Object.assign(settings, {min, max});
  106. }
  107. function addBoxes(file, hueRange) {
  108. const {min, max, data} = file;
  109. const range = max - min;
  110. // these helpers will make it easy to position the boxes
  111. // We can rotate the lon helper on its Y axis to the longitude
  112. const lonHelper = new THREE.Object3D();
  113. scene.add(lonHelper);
  114. // We rotate the latHelper on its X axis to the latitude
  115. const latHelper = new THREE.Object3D();
  116. lonHelper.add(latHelper);
  117. // The position helper moves the object to the edge of the sphere
  118. const positionHelper = new THREE.Object3D();
  119. positionHelper.position.z = 1;
  120. latHelper.add(positionHelper);
  121. // Used to move the center of the cube so it scales from the position Z axis
  122. const originHelper = new THREE.Object3D();
  123. originHelper.position.z = 0.5;
  124. positionHelper.add(originHelper);
  125. const color = new THREE.Color();
  126. const lonFudge = Math.PI * .5;
  127. const latFudge = Math.PI * -0.135;
  128. const geometries = [];
  129. data.forEach((row, latNdx) => {
  130. row.forEach((value, lonNdx) => {
  131. if (value === undefined) {
  132. return;
  133. }
  134. const amount = (value - min) / range;
  135. const boxWidth = 1;
  136. const boxHeight = 1;
  137. const boxDepth = 1;
  138. const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
  139. // adjust the helpers to point to the latitude and longitude
  140. lonHelper.rotation.y = THREE.Math.degToRad(lonNdx + file.xllcorner) + lonFudge;
  141. latHelper.rotation.x = THREE.Math.degToRad(latNdx + file.yllcorner) + latFudge;
  142. // use the world matrix of the origin helper to
  143. // position this geometry
  144. positionHelper.scale.set(0.005, 0.005, THREE.Math.lerp(0.01, 0.5, amount));
  145. originHelper.updateWorldMatrix(true, false);
  146. geometry.applyMatrix(originHelper.matrixWorld);
  147. // compute a color
  148. const hue = THREE.Math.lerp(...hueRange, amount);
  149. const saturation = 1;
  150. const lightness = THREE.Math.lerp(0.4, 1.0, amount);
  151. color.setHSL(hue, saturation, lightness);
  152. // get the colors as an array of values from 0 to 255
  153. const rgb = color.toArray().map(v => v * 255);
  154. // make an array to store colors for each vertex
  155. const numVerts = geometry.getAttribute('position').count;
  156. const itemSize = 3; // r, g, b
  157. const colors = new Uint8Array(itemSize * numVerts);
  158. // copy the color into the colors array for each vertex
  159. colors.forEach((v, ndx) => {
  160. colors[ndx] = rgb[ndx % 3];
  161. });
  162. const normalized = true;
  163. const colorAttrib = new THREE.BufferAttribute(colors, itemSize, normalized);
  164. geometry.addAttribute('color', colorAttrib);
  165. geometries.push(geometry);
  166. });
  167. });
  168. const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries(
  169. geometries, false);
  170. const material = new THREE.MeshBasicMaterial({
  171. vertexColors: THREE.VertexColors,
  172. });
  173. const mesh = new THREE.Mesh(mergedGeometry, material);
  174. scene.add(mesh);
  175. return mesh;
  176. }
  177. async function loadData(info) {
  178. const text = await loadFile(info.url);
  179. info.file = parseData(text);
  180. }
  181. async function loadAll() {
  182. const fileInfos = [
  183. {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' },
  184. {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' },
  185. ];
  186. await Promise.all(fileInfos.map(loadData));
  187. function mapValues(data, fn) {
  188. return data.map((row, rowNdx) => {
  189. return row.map((value, colNdx) => {
  190. return fn(value, rowNdx, colNdx);
  191. });
  192. });
  193. }
  194. function makeDiffFile(baseFile, otherFile, compareFn) {
  195. let min;
  196. let max;
  197. const baseData = baseFile.data;
  198. const otherData = otherFile.data;
  199. const data = mapValues(baseData, (base, rowNdx, colNdx) => {
  200. const other = otherData[rowNdx][colNdx];
  201. if (base === undefined || other === undefined) {
  202. return undefined;
  203. }
  204. const value = compareFn(base, other);
  205. min = Math.min(min === undefined ? value : min, value);
  206. max = Math.max(max === undefined ? value : max, value);
  207. return value;
  208. });
  209. // make a copy of baseFile and replace min, max, and data
  210. // with the new data
  211. return Object.assign({}, baseFile, {
  212. min,
  213. max,
  214. data,
  215. });
  216. }
  217. // generate a new set of data
  218. {
  219. const menInfo = fileInfos[0];
  220. const womenInfo = fileInfos[1];
  221. const menFile = menInfo.file;
  222. const womenFile = womenInfo.file;
  223. function amountGreaterThan(a, b) {
  224. return Math.max(a - b, 0);
  225. }
  226. fileInfos.push({
  227. name: '>50%men',
  228. hueRange: [0.6, 1.1],
  229. file: makeDiffFile(menFile, womenFile, (men, women) => {
  230. return amountGreaterThan(men, women);
  231. }),
  232. });
  233. fileInfos.push({
  234. name: '>50% women',
  235. hueRange: [0.0, 0.4],
  236. file: makeDiffFile(womenFile, menFile, (women, men) => {
  237. return amountGreaterThan(women, men);
  238. }),
  239. });
  240. }
  241. // show the selected data, hide the rest
  242. function showFileInfo(fileInfos, fileInfo) {
  243. fileInfos.forEach((info) => {
  244. const visible = fileInfo === info;
  245. info.root.visible = visible;
  246. info.elem.className = visible ? 'selected' : '';
  247. });
  248. requestRenderIfNotRequested();
  249. }
  250. const uiElem = document.querySelector('#ui');
  251. fileInfos.forEach((info) => {
  252. const boxes = addBoxes(info.file, info.hueRange);
  253. info.root = boxes;
  254. const div = document.createElement('div');
  255. info.elem = div;
  256. div.textContent = info.name;
  257. uiElem.appendChild(div);
  258. function show() {
  259. showFileInfo(fileInfos, info);
  260. }
  261. div.addEventListener('mouseover', show);
  262. div.addEventListener('touchstart', show);
  263. });
  264. // show the first set of data
  265. showFileInfo(fileInfos, fileInfos[0]);
  266. }
  267. loadAll();
  268. function resizeRendererToDisplaySize(renderer) {
  269. const canvas = renderer.domElement;
  270. const width = canvas.clientWidth;
  271. const height = canvas.clientHeight;
  272. const needResize = canvas.width !== width || canvas.height !== height;
  273. if (needResize) {
  274. renderer.setSize(width, height, false);
  275. }
  276. return needResize;
  277. }
  278. let renderRequested = false;
  279. function render() {
  280. renderRequested = undefined;
  281. if (resizeRendererToDisplaySize(renderer)) {
  282. const canvas = renderer.domElement;
  283. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  284. camera.updateProjectionMatrix();
  285. }
  286. controls.update();
  287. renderer.render(scene, camera);
  288. }
  289. render();
  290. function requestRenderIfNotRequested() {
  291. if (!renderRequested) {
  292. renderRequested = true;
  293. requestAnimationFrame(render);
  294. }
  295. }
  296. controls.addEventListener('change', requestRenderIfNotRequested);
  297. window.addEventListener('resize', requestRenderIfNotRequested);
  298. }
  299. main();
  300. </script>
  301. </html>