lots-of-objects-merged-vertexcolors.html 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 - Merged w/vertex colors</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../../build/three.module.js",
  27. "three/addons/": "../../examples/jsm/"
  28. }
  29. }
  30. </script>
  31. <script type="module">
  32. import * as THREE from 'three';
  33. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  34. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  35. function main() {
  36. const canvas = document.querySelector( '#c' );
  37. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  38. const fov = 60;
  39. const aspect = 2; // the canvas default
  40. const near = 0.1;
  41. const far = 10;
  42. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  43. camera.position.z = 2.5;
  44. const controls = new OrbitControls( camera, canvas );
  45. controls.enableDamping = true;
  46. controls.enablePan = false;
  47. controls.minDistance = 1.2;
  48. controls.maxDistance = 4;
  49. controls.update();
  50. const scene = new THREE.Scene();
  51. scene.background = new THREE.Color( 'black' );
  52. {
  53. const loader = new THREE.TextureLoader();
  54. const texture = loader.load( 'resources/images/world.jpg', render );
  55. texture.colorSpace = THREE.SRGBColorSpace;
  56. const geometry = new THREE.SphereGeometry( 1, 64, 32 );
  57. const material = new THREE.MeshBasicMaterial( { map: texture } );
  58. scene.add( new THREE.Mesh( geometry, material ) );
  59. }
  60. async function loadFile( url ) {
  61. const req = await fetch( url );
  62. return req.text();
  63. }
  64. function parseData( text ) {
  65. const data = [];
  66. const settings = { data };
  67. let max;
  68. let min;
  69. // split into lines
  70. text.split( '\n' ).forEach( ( line ) => {
  71. // split the line by whitespace
  72. const parts = line.trim().split( /\s+/ );
  73. if ( parts.length === 2 ) {
  74. // only 2 parts, must be a key/value pair
  75. settings[ parts[ 0 ] ] = parseFloat( parts[ 1 ] );
  76. } else if ( parts.length > 2 ) {
  77. // more than 2 parts, must be data
  78. const values = parts.map( ( v ) => {
  79. const value = parseFloat( v );
  80. if ( value === settings.NODATA_value ) {
  81. return undefined;
  82. }
  83. max = Math.max( max === undefined ? value : max, value );
  84. min = Math.min( min === undefined ? value : min, value );
  85. return value;
  86. } );
  87. data.push( values );
  88. }
  89. } );
  90. return Object.assign( settings, { min, max } );
  91. }
  92. function addBoxes( file ) {
  93. const { min, max, data } = file;
  94. const range = max - min;
  95. // these helpers will make it easy to position the boxes
  96. // We can rotate the lon helper on its Y axis to the longitude
  97. const lonHelper = new THREE.Object3D();
  98. scene.add( lonHelper );
  99. // We rotate the latHelper on its X axis to the latitude
  100. const latHelper = new THREE.Object3D();
  101. lonHelper.add( latHelper );
  102. // The position helper moves the object to the edge of the sphere
  103. const positionHelper = new THREE.Object3D();
  104. positionHelper.position.z = 1;
  105. latHelper.add( positionHelper );
  106. // Used to move the center of the cube so it scales from the position Z axis
  107. const originHelper = new THREE.Object3D();
  108. originHelper.position.z = 0.5;
  109. positionHelper.add( originHelper );
  110. const color = new THREE.Color();
  111. const lonFudge = Math.PI * .5;
  112. const latFudge = Math.PI * - 0.135;
  113. const geometries = [];
  114. data.forEach( ( row, latNdx ) => {
  115. row.forEach( ( value, lonNdx ) => {
  116. if ( value === undefined ) {
  117. return;
  118. }
  119. const amount = ( value - min ) / range;
  120. const boxWidth = 1;
  121. const boxHeight = 1;
  122. const boxDepth = 1;
  123. const geometry = new THREE.BoxGeometry( boxWidth, boxHeight, boxDepth );
  124. // adjust the helpers to point to the latitude and longitude
  125. lonHelper.rotation.y = THREE.MathUtils.degToRad( lonNdx + file.xllcorner ) + lonFudge;
  126. latHelper.rotation.x = THREE.MathUtils.degToRad( latNdx + file.yllcorner ) + latFudge;
  127. // use the world matrix of the origin helper to
  128. // position this geometry
  129. positionHelper.scale.set( 0.005, 0.005, THREE.MathUtils.lerp( 0.01, 0.5, amount ) );
  130. originHelper.updateWorldMatrix( true, false );
  131. geometry.applyMatrix4( originHelper.matrixWorld );
  132. // compute a color
  133. const hue = THREE.MathUtils.lerp( 0.7, 0.3, amount );
  134. const saturation = 1;
  135. const lightness = THREE.MathUtils.lerp( 0.4, 1.0, amount );
  136. color.setHSL( hue, saturation, lightness );
  137. // get the colors as an array of values from 0 to 255
  138. const rgb = color.toArray().map( v => v * 255 );
  139. // make an array to store colors for each vertex
  140. const numVerts = geometry.getAttribute( 'position' ).count;
  141. const itemSize = 3; // r, g, b
  142. const colors = new Uint8Array( itemSize * numVerts );
  143. // copy the color into the colors array for each vertex
  144. colors.forEach( ( v, ndx ) => {
  145. colors[ ndx ] = rgb[ ndx % 3 ];
  146. } );
  147. const normalized = true;
  148. const colorAttrib = new THREE.BufferAttribute( colors, itemSize, normalized );
  149. geometry.setAttribute( 'color', colorAttrib );
  150. geometries.push( geometry );
  151. } );
  152. } );
  153. const mergedGeometry = BufferGeometryUtils.mergeGeometries(
  154. geometries, false );
  155. const material = new THREE.MeshBasicMaterial( {
  156. vertexColors: true,
  157. } );
  158. const mesh = new THREE.Mesh( mergedGeometry, material );
  159. scene.add( mesh );
  160. }
  161. loadFile( 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' )
  162. .then( parseData )
  163. .then( addBoxes )
  164. .then( render );
  165. function resizeRendererToDisplaySize( renderer ) {
  166. const canvas = renderer.domElement;
  167. const width = canvas.clientWidth;
  168. const height = canvas.clientHeight;
  169. const needResize = canvas.width !== width || canvas.height !== height;
  170. if ( needResize ) {
  171. renderer.setSize( width, height, false );
  172. }
  173. return needResize;
  174. }
  175. let renderRequested = false;
  176. function render() {
  177. renderRequested = undefined;
  178. if ( resizeRendererToDisplaySize( renderer ) ) {
  179. const canvas = renderer.domElement;
  180. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  181. camera.updateProjectionMatrix();
  182. }
  183. controls.update();
  184. renderer.render( scene, camera );
  185. }
  186. render();
  187. function requestRenderIfNotRequested() {
  188. if ( ! renderRequested ) {
  189. renderRequested = true;
  190. requestAnimationFrame( render );
  191. }
  192. }
  193. controls.addEventListener( 'change', requestRenderIfNotRequested );
  194. window.addEventListener( 'resize', requestRenderIfNotRequested );
  195. }
  196. main();
  197. </script>
  198. </html>