2
0

lots-of-objects-multiple-data-sets.html 10.0 KB

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