HeightmapTerrainData.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. import BoundingSphere from "./BoundingSphere.js";
  2. import Cartesian3 from "./Cartesian3.js";
  3. import Check from "./Check.js";
  4. import defaultValue from "./defaultValue.js";
  5. import defined from "./defined.js";
  6. import DeveloperError from "./DeveloperError.js";
  7. import GeographicProjection from "./GeographicProjection.js";
  8. import HeightmapEncoding from "./HeightmapEncoding.js";
  9. import HeightmapTessellator from "./HeightmapTessellator.js";
  10. import CesiumMath from "./Math.js";
  11. import OrientedBoundingBox from "./OrientedBoundingBox.js";
  12. import Rectangle from "./Rectangle.js";
  13. import TaskProcessor from "./TaskProcessor.js";
  14. import TerrainData from "./TerrainData.js";
  15. import TerrainEncoding from "./TerrainEncoding.js";
  16. import TerrainMesh from "./TerrainMesh.js";
  17. import TerrainProvider from "./TerrainProvider.js";
  18. /**
  19. * Terrain data for a single tile where the terrain data is represented as a heightmap. A heightmap
  20. * is a rectangular array of heights in row-major order from north to south and west to east.
  21. *
  22. * @alias HeightmapTerrainData
  23. * @constructor
  24. *
  25. * @param {object} options Object with the following properties:
  26. * @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} options.buffer The buffer containing height data.
  27. * @param {number} options.width The width (longitude direction) of the heightmap, in samples.
  28. * @param {number} options.height The height (latitude direction) of the heightmap, in samples.
  29. * @param {number} [options.childTileMask=15] A bit mask indicating which of this tile's four children exist.
  30. * If a child's bit is set, geometry will be requested for that tile as well when it
  31. * is needed. If the bit is cleared, the child tile is not requested and geometry is
  32. * instead upsampled from the parent. The bit values are as follows:
  33. * <table>
  34. * <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
  35. * <tr><td>0</td><td>1</td><td>Southwest</td></tr>
  36. * <tr><td>1</td><td>2</td><td>Southeast</td></tr>
  37. * <tr><td>2</td><td>4</td><td>Northwest</td></tr>
  38. * <tr><td>3</td><td>8</td><td>Northeast</td></tr>
  39. * </table>
  40. * @param {Uint8Array} [options.waterMask] The water mask included in this terrain data, if any. A water mask is a square
  41. * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
  42. * Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
  43. * @param {object} [options.structure] An object describing the structure of the height data.
  44. * @param {number} [options.structure.heightScale=1.0] The factor by which to multiply height samples in order to obtain
  45. * the height above the heightOffset, in meters. The heightOffset is added to the resulting
  46. * height after multiplying by the scale.
  47. * @param {number} [options.structure.heightOffset=0.0] The offset to add to the scaled height to obtain the final
  48. * height in meters. The offset is added after the height sample is multiplied by the
  49. * heightScale.
  50. * @param {number} [options.structure.elementsPerHeight=1] The number of elements in the buffer that make up a single height
  51. * sample. This is usually 1, indicating that each element is a separate height sample. If
  52. * it is greater than 1, that number of elements together form the height sample, which is
  53. * computed according to the structure.elementMultiplier and structure.isBigEndian properties.
  54. * @param {number} [options.structure.stride=1] The number of elements to skip to get from the first element of
  55. * one height to the first element of the next height.
  56. * @param {number} [options.structure.elementMultiplier=256.0] The multiplier used to compute the height value when the
  57. * stride property is greater than 1. For example, if the stride is 4 and the strideMultiplier
  58. * is 256, the height is computed as follows:
  59. * `height = buffer[index] + buffer[index + 1] * 256 + buffer[index + 2] * 256 * 256 + buffer[index + 3] * 256 * 256 * 256`
  60. * This is assuming that the isBigEndian property is false. If it is true, the order of the
  61. * elements is reversed.
  62. * @param {boolean} [options.structure.isBigEndian=false] Indicates endianness of the elements in the buffer when the
  63. * stride property is greater than 1. If this property is false, the first element is the
  64. * low-order element. If it is true, the first element is the high-order element.
  65. * @param {number} [options.structure.lowestEncodedHeight] The lowest value that can be stored in the height buffer. Any heights that are lower
  66. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  67. * buffer is a `Uint16Array`, this value should be 0 because a `Uint16Array` cannot store negative numbers. If this parameter is
  68. * not specified, no minimum value is enforced.
  69. * @param {number} [options.structure.highestEncodedHeight] The highest value that can be stored in the height buffer. Any heights that are higher
  70. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  71. * buffer is a `Uint16Array`, this value should be `256 * 256 - 1` or 65535 because a `Uint16Array` cannot store numbers larger
  72. * than 65535. If this parameter is not specified, no maximum value is enforced.
  73. * @param {HeightmapEncoding} [options.encoding=HeightmapEncoding.NONE] The encoding that is used on the buffer.
  74. * @param {boolean} [options.createdByUpsampling=false] True if this instance was created by upsampling another instance;
  75. * otherwise, false.
  76. *
  77. *
  78. * @example
  79. * const buffer = ...
  80. * const heightBuffer = new Uint16Array(buffer, 0, that._heightmapWidth * that._heightmapWidth);
  81. * const childTileMask = new Uint8Array(buffer, heightBuffer.byteLength, 1)[0];
  82. * const waterMask = new Uint8Array(buffer, heightBuffer.byteLength + 1, buffer.byteLength - heightBuffer.byteLength - 1);
  83. * const terrainData = new Cesium.HeightmapTerrainData({
  84. * buffer : heightBuffer,
  85. * width : 65,
  86. * height : 65,
  87. * childTileMask : childTileMask,
  88. * waterMask : waterMask
  89. * });
  90. *
  91. * @see TerrainData
  92. * @see QuantizedMeshTerrainData
  93. * @see GoogleEarthEnterpriseTerrainData
  94. */
  95. function HeightmapTerrainData(options) {
  96. //>>includeStart('debug', pragmas.debug);
  97. if (!defined(options) || !defined(options.buffer)) {
  98. throw new DeveloperError("options.buffer is required.");
  99. }
  100. if (!defined(options.width)) {
  101. throw new DeveloperError("options.width is required.");
  102. }
  103. if (!defined(options.height)) {
  104. throw new DeveloperError("options.height is required.");
  105. }
  106. //>>includeEnd('debug');
  107. this._buffer = options.buffer;
  108. this._width = options.width;
  109. this._height = options.height;
  110. this._childTileMask = defaultValue(options.childTileMask, 15);
  111. this._encoding = defaultValue(options.encoding, HeightmapEncoding.NONE);
  112. const defaultStructure = HeightmapTessellator.DEFAULT_STRUCTURE;
  113. let structure = options.structure;
  114. if (!defined(structure)) {
  115. structure = defaultStructure;
  116. } else if (structure !== defaultStructure) {
  117. structure.heightScale = defaultValue(
  118. structure.heightScale,
  119. defaultStructure.heightScale
  120. );
  121. structure.heightOffset = defaultValue(
  122. structure.heightOffset,
  123. defaultStructure.heightOffset
  124. );
  125. structure.elementsPerHeight = defaultValue(
  126. structure.elementsPerHeight,
  127. defaultStructure.elementsPerHeight
  128. );
  129. structure.stride = defaultValue(structure.stride, defaultStructure.stride);
  130. structure.elementMultiplier = defaultValue(
  131. structure.elementMultiplier,
  132. defaultStructure.elementMultiplier
  133. );
  134. structure.isBigEndian = defaultValue(
  135. structure.isBigEndian,
  136. defaultStructure.isBigEndian
  137. );
  138. }
  139. this._structure = structure;
  140. this._createdByUpsampling = defaultValue(options.createdByUpsampling, false);
  141. this._waterMask = options.waterMask;
  142. this._skirtHeight = undefined;
  143. this._bufferType =
  144. this._encoding === HeightmapEncoding.LERC
  145. ? Float32Array
  146. : this._buffer.constructor;
  147. this._mesh = undefined;
  148. }
  149. Object.defineProperties(HeightmapTerrainData.prototype, {
  150. /**
  151. * An array of credits for this tile.
  152. * @memberof HeightmapTerrainData.prototype
  153. * @type {Credit[]}
  154. */
  155. credits: {
  156. get: function () {
  157. return undefined;
  158. },
  159. },
  160. /**
  161. * The water mask included in this terrain data, if any. A water mask is a square
  162. * Uint8Array or image where a value of 255 indicates water and a value of 0 indicates land.
  163. * Values in between 0 and 255 are allowed as well to smoothly blend between land and water.
  164. * @memberof HeightmapTerrainData.prototype
  165. * @type {Uint8Array|HTMLImageElement|HTMLCanvasElement}
  166. */
  167. waterMask: {
  168. get: function () {
  169. return this._waterMask;
  170. },
  171. },
  172. childTileMask: {
  173. get: function () {
  174. return this._childTileMask;
  175. },
  176. },
  177. });
  178. const createMeshTaskName = "createVerticesFromHeightmap";
  179. const createMeshTaskProcessorNoThrottle = new TaskProcessor(createMeshTaskName);
  180. const createMeshTaskProcessorThrottle = new TaskProcessor(
  181. createMeshTaskName,
  182. TerrainData.maximumAsynchronousTasks
  183. );
  184. /**
  185. * Creates a {@link TerrainMesh} from this terrain data.
  186. *
  187. * @private
  188. *
  189. * @param {object} options Object with the following properties:
  190. * @param {TilingScheme} options.tilingScheme The tiling scheme to which this tile belongs.
  191. * @param {number} options.x The X coordinate of the tile for which to create the terrain data.
  192. * @param {number} options.y The Y coordinate of the tile for which to create the terrain data.
  193. * @param {number} options.level The level of the tile for which to create the terrain data.
  194. * @param {number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
  195. * @param {number} [options.exaggerationRelativeHeight=0.0] The height relative to which terrain is exaggerated.
  196. * @param {boolean} [options.throttle=true] If true, indicates that this operation will need to be retried if too many asynchronous mesh creations are already in progress.
  197. * @returns {Promise<TerrainMesh>|undefined} A promise for the terrain mesh, or undefined if too many
  198. * asynchronous mesh creations are already in progress and the operation should
  199. * be retried later.
  200. */
  201. HeightmapTerrainData.prototype.createMesh = function (options) {
  202. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  203. //>>includeStart('debug', pragmas.debug);
  204. Check.typeOf.object("options.tilingScheme", options.tilingScheme);
  205. Check.typeOf.number("options.x", options.x);
  206. Check.typeOf.number("options.y", options.y);
  207. Check.typeOf.number("options.level", options.level);
  208. //>>includeEnd('debug');
  209. const tilingScheme = options.tilingScheme;
  210. const x = options.x;
  211. const y = options.y;
  212. const level = options.level;
  213. const exaggeration = defaultValue(options.exaggeration, 1.0);
  214. const exaggerationRelativeHeight = defaultValue(
  215. options.exaggerationRelativeHeight,
  216. 0.0
  217. );
  218. const throttle = defaultValue(options.throttle, true);
  219. const ellipsoid = tilingScheme.ellipsoid;
  220. const nativeRectangle = tilingScheme.tileXYToNativeRectangle(x, y, level);
  221. const rectangle = tilingScheme.tileXYToRectangle(x, y, level);
  222. // Compute the center of the tile for RTC rendering.
  223. const center = ellipsoid.cartographicToCartesian(Rectangle.center(rectangle));
  224. const structure = this._structure;
  225. const levelZeroMaxError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
  226. ellipsoid,
  227. this._width,
  228. tilingScheme.getNumberOfXTilesAtLevel(0)
  229. );
  230. const thisLevelMaxError = levelZeroMaxError / (1 << level);
  231. this._skirtHeight = Math.min(thisLevelMaxError * 4.0, 1000.0);
  232. const createMeshTaskProcessor = throttle
  233. ? createMeshTaskProcessorThrottle
  234. : createMeshTaskProcessorNoThrottle;
  235. const verticesPromise = createMeshTaskProcessor.scheduleTask({
  236. heightmap: this._buffer,
  237. structure: structure,
  238. includeWebMercatorT: true,
  239. width: this._width,
  240. height: this._height,
  241. nativeRectangle: nativeRectangle,
  242. rectangle: rectangle,
  243. relativeToCenter: center,
  244. ellipsoid: ellipsoid,
  245. skirtHeight: this._skirtHeight,
  246. isGeographic: tilingScheme.projection instanceof GeographicProjection,
  247. exaggeration: exaggeration,
  248. exaggerationRelativeHeight: exaggerationRelativeHeight,
  249. encoding: this._encoding,
  250. });
  251. if (!defined(verticesPromise)) {
  252. // Postponed
  253. return undefined;
  254. }
  255. const that = this;
  256. return Promise.resolve(verticesPromise).then(function (result) {
  257. let indicesAndEdges;
  258. if (that._skirtHeight > 0.0) {
  259. indicesAndEdges = TerrainProvider.getRegularGridAndSkirtIndicesAndEdgeIndices(
  260. result.gridWidth,
  261. result.gridHeight
  262. );
  263. } else {
  264. indicesAndEdges = TerrainProvider.getRegularGridIndicesAndEdgeIndices(
  265. result.gridWidth,
  266. result.gridHeight
  267. );
  268. }
  269. const vertexCountWithoutSkirts = result.gridWidth * result.gridHeight;
  270. // Clone complex result objects because the transfer from the web worker
  271. // has stripped them down to JSON-style objects.
  272. that._mesh = new TerrainMesh(
  273. center,
  274. new Float32Array(result.vertices),
  275. indicesAndEdges.indices,
  276. indicesAndEdges.indexCountWithoutSkirts,
  277. vertexCountWithoutSkirts,
  278. result.minimumHeight,
  279. result.maximumHeight,
  280. BoundingSphere.clone(result.boundingSphere3D),
  281. Cartesian3.clone(result.occludeePointInScaledSpace),
  282. result.numberOfAttributes,
  283. OrientedBoundingBox.clone(result.orientedBoundingBox),
  284. TerrainEncoding.clone(result.encoding),
  285. indicesAndEdges.westIndicesSouthToNorth,
  286. indicesAndEdges.southIndicesEastToWest,
  287. indicesAndEdges.eastIndicesNorthToSouth,
  288. indicesAndEdges.northIndicesWestToEast
  289. );
  290. // Free memory received from server after mesh is created.
  291. that._buffer = undefined;
  292. return that._mesh;
  293. });
  294. };
  295. /**
  296. * @param {object} options Object with the following properties:
  297. * @param {TilingScheme} options.tilingScheme The tiling scheme to which this tile belongs.
  298. * @param {number} options.x The X coordinate of the tile for which to create the terrain data.
  299. * @param {number} options.y The Y coordinate of the tile for which to create the terrain data.
  300. * @param {number} options.level The level of the tile for which to create the terrain data.
  301. * @param {number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
  302. * @param {number} [options.exaggerationRelativeHeight=0.0] The height relative to which terrain is exaggerated.
  303. *
  304. * @private
  305. */
  306. HeightmapTerrainData.prototype._createMeshSync = function (options) {
  307. //>>includeStart('debug', pragmas.debug);
  308. Check.typeOf.object("options.tilingScheme", options.tilingScheme);
  309. Check.typeOf.number("options.x", options.x);
  310. Check.typeOf.number("options.y", options.y);
  311. Check.typeOf.number("options.level", options.level);
  312. //>>includeEnd('debug');
  313. const tilingScheme = options.tilingScheme;
  314. const x = options.x;
  315. const y = options.y;
  316. const level = options.level;
  317. const exaggeration = defaultValue(options.exaggeration, 1.0);
  318. const exaggerationRelativeHeight = defaultValue(
  319. options.exaggerationRelativeHeight,
  320. 0.0
  321. );
  322. const ellipsoid = tilingScheme.ellipsoid;
  323. const nativeRectangle = tilingScheme.tileXYToNativeRectangle(x, y, level);
  324. const rectangle = tilingScheme.tileXYToRectangle(x, y, level);
  325. // Compute the center of the tile for RTC rendering.
  326. const center = ellipsoid.cartographicToCartesian(Rectangle.center(rectangle));
  327. const structure = this._structure;
  328. const levelZeroMaxError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(
  329. ellipsoid,
  330. this._width,
  331. tilingScheme.getNumberOfXTilesAtLevel(0)
  332. );
  333. const thisLevelMaxError = levelZeroMaxError / (1 << level);
  334. this._skirtHeight = Math.min(thisLevelMaxError * 4.0, 1000.0);
  335. const result = HeightmapTessellator.computeVertices({
  336. heightmap: this._buffer,
  337. structure: structure,
  338. includeWebMercatorT: true,
  339. width: this._width,
  340. height: this._height,
  341. nativeRectangle: nativeRectangle,
  342. rectangle: rectangle,
  343. relativeToCenter: center,
  344. ellipsoid: ellipsoid,
  345. skirtHeight: this._skirtHeight,
  346. isGeographic: tilingScheme.projection instanceof GeographicProjection,
  347. exaggeration: exaggeration,
  348. exaggerationRelativeHeight: exaggerationRelativeHeight,
  349. });
  350. // Free memory received from server after mesh is created.
  351. this._buffer = undefined;
  352. let indicesAndEdges;
  353. if (this._skirtHeight > 0.0) {
  354. indicesAndEdges = TerrainProvider.getRegularGridAndSkirtIndicesAndEdgeIndices(
  355. this._width,
  356. this._height
  357. );
  358. } else {
  359. indicesAndEdges = TerrainProvider.getRegularGridIndicesAndEdgeIndices(
  360. this._width,
  361. this._height
  362. );
  363. }
  364. const vertexCountWithoutSkirts = result.gridWidth * result.gridHeight;
  365. // No need to clone here (as we do in the async version) because the result
  366. // is not coming from a web worker.
  367. this._mesh = new TerrainMesh(
  368. center,
  369. result.vertices,
  370. indicesAndEdges.indices,
  371. indicesAndEdges.indexCountWithoutSkirts,
  372. vertexCountWithoutSkirts,
  373. result.minimumHeight,
  374. result.maximumHeight,
  375. result.boundingSphere3D,
  376. result.occludeePointInScaledSpace,
  377. result.encoding.stride,
  378. result.orientedBoundingBox,
  379. result.encoding,
  380. indicesAndEdges.westIndicesSouthToNorth,
  381. indicesAndEdges.southIndicesEastToWest,
  382. indicesAndEdges.eastIndicesNorthToSouth,
  383. indicesAndEdges.northIndicesWestToEast
  384. );
  385. return this._mesh;
  386. };
  387. /**
  388. * Computes the terrain height at a specified longitude and latitude.
  389. *
  390. * @param {Rectangle} rectangle The rectangle covered by this terrain data.
  391. * @param {number} longitude The longitude in radians.
  392. * @param {number} latitude The latitude in radians.
  393. * @returns {number} The terrain height at the specified position. If the position
  394. * is outside the rectangle, this method will extrapolate the height, which is likely to be wildly
  395. * incorrect for positions far outside the rectangle.
  396. */
  397. HeightmapTerrainData.prototype.interpolateHeight = function (
  398. rectangle,
  399. longitude,
  400. latitude
  401. ) {
  402. const width = this._width;
  403. const height = this._height;
  404. const structure = this._structure;
  405. const stride = structure.stride;
  406. const elementsPerHeight = structure.elementsPerHeight;
  407. const elementMultiplier = structure.elementMultiplier;
  408. const isBigEndian = structure.isBigEndian;
  409. const heightOffset = structure.heightOffset;
  410. const heightScale = structure.heightScale;
  411. const isMeshCreated = defined(this._mesh);
  412. const isLERCEncoding = this._encoding === HeightmapEncoding.LERC;
  413. const isInterpolationImpossible = !isMeshCreated && isLERCEncoding;
  414. if (isInterpolationImpossible) {
  415. // We can't interpolate using the buffer because it's LERC encoded
  416. // so please call createMesh() first and interpolate using the mesh;
  417. // as mesh creation will decode the LERC buffer
  418. return undefined;
  419. }
  420. let heightSample;
  421. if (isMeshCreated) {
  422. const buffer = this._mesh.vertices;
  423. const encoding = this._mesh.encoding;
  424. heightSample = interpolateMeshHeight(
  425. buffer,
  426. encoding,
  427. heightOffset,
  428. heightScale,
  429. rectangle,
  430. width,
  431. height,
  432. longitude,
  433. latitude
  434. );
  435. } else {
  436. heightSample = interpolateHeight(
  437. this._buffer,
  438. elementsPerHeight,
  439. elementMultiplier,
  440. stride,
  441. isBigEndian,
  442. rectangle,
  443. width,
  444. height,
  445. longitude,
  446. latitude
  447. );
  448. heightSample = heightSample * heightScale + heightOffset;
  449. }
  450. return heightSample;
  451. };
  452. /**
  453. * Upsamples this terrain data for use by a descendant tile. The resulting instance will contain a subset of the
  454. * height samples in this instance, interpolated if necessary.
  455. *
  456. * @param {TilingScheme} tilingScheme The tiling scheme of this terrain data.
  457. * @param {number} thisX The X coordinate of this tile in the tiling scheme.
  458. * @param {number} thisY The Y coordinate of this tile in the tiling scheme.
  459. * @param {number} thisLevel The level of this tile in the tiling scheme.
  460. * @param {number} descendantX The X coordinate within the tiling scheme of the descendant tile for which we are upsampling.
  461. * @param {number} descendantY The Y coordinate within the tiling scheme of the descendant tile for which we are upsampling.
  462. * @param {number} descendantLevel The level within the tiling scheme of the descendant tile for which we are upsampling.
  463. * @returns {Promise<HeightmapTerrainData>|undefined} A promise for upsampled heightmap terrain data for the descendant tile,
  464. * or undefined if the mesh is unavailable.
  465. */
  466. HeightmapTerrainData.prototype.upsample = function (
  467. tilingScheme,
  468. thisX,
  469. thisY,
  470. thisLevel,
  471. descendantX,
  472. descendantY,
  473. descendantLevel
  474. ) {
  475. //>>includeStart('debug', pragmas.debug);
  476. if (!defined(tilingScheme)) {
  477. throw new DeveloperError("tilingScheme is required.");
  478. }
  479. if (!defined(thisX)) {
  480. throw new DeveloperError("thisX is required.");
  481. }
  482. if (!defined(thisY)) {
  483. throw new DeveloperError("thisY is required.");
  484. }
  485. if (!defined(thisLevel)) {
  486. throw new DeveloperError("thisLevel is required.");
  487. }
  488. if (!defined(descendantX)) {
  489. throw new DeveloperError("descendantX is required.");
  490. }
  491. if (!defined(descendantY)) {
  492. throw new DeveloperError("descendantY is required.");
  493. }
  494. if (!defined(descendantLevel)) {
  495. throw new DeveloperError("descendantLevel is required.");
  496. }
  497. const levelDifference = descendantLevel - thisLevel;
  498. if (levelDifference > 1) {
  499. throw new DeveloperError(
  500. "Upsampling through more than one level at a time is not currently supported."
  501. );
  502. }
  503. //>>includeEnd('debug');
  504. const meshData = this._mesh;
  505. if (!defined(meshData)) {
  506. return undefined;
  507. }
  508. const width = this._width;
  509. const height = this._height;
  510. const structure = this._structure;
  511. const stride = structure.stride;
  512. const heights = new this._bufferType(width * height * stride);
  513. const buffer = meshData.vertices;
  514. const encoding = meshData.encoding;
  515. // PERFORMANCE_IDEA: don't recompute these rectangles - the caller already knows them.
  516. const sourceRectangle = tilingScheme.tileXYToRectangle(
  517. thisX,
  518. thisY,
  519. thisLevel
  520. );
  521. const destinationRectangle = tilingScheme.tileXYToRectangle(
  522. descendantX,
  523. descendantY,
  524. descendantLevel
  525. );
  526. const heightOffset = structure.heightOffset;
  527. const heightScale = structure.heightScale;
  528. const elementsPerHeight = structure.elementsPerHeight;
  529. const elementMultiplier = structure.elementMultiplier;
  530. const isBigEndian = structure.isBigEndian;
  531. const divisor = Math.pow(elementMultiplier, elementsPerHeight - 1);
  532. for (let j = 0; j < height; ++j) {
  533. const latitude = CesiumMath.lerp(
  534. destinationRectangle.north,
  535. destinationRectangle.south,
  536. j / (height - 1)
  537. );
  538. for (let i = 0; i < width; ++i) {
  539. const longitude = CesiumMath.lerp(
  540. destinationRectangle.west,
  541. destinationRectangle.east,
  542. i / (width - 1)
  543. );
  544. let heightSample = interpolateMeshHeight(
  545. buffer,
  546. encoding,
  547. heightOffset,
  548. heightScale,
  549. sourceRectangle,
  550. width,
  551. height,
  552. longitude,
  553. latitude
  554. );
  555. // Use conditionals here instead of Math.min and Math.max so that an undefined
  556. // lowestEncodedHeight or highestEncodedHeight has no effect.
  557. heightSample =
  558. heightSample < structure.lowestEncodedHeight
  559. ? structure.lowestEncodedHeight
  560. : heightSample;
  561. heightSample =
  562. heightSample > structure.highestEncodedHeight
  563. ? structure.highestEncodedHeight
  564. : heightSample;
  565. setHeight(
  566. heights,
  567. elementsPerHeight,
  568. elementMultiplier,
  569. divisor,
  570. stride,
  571. isBigEndian,
  572. j * width + i,
  573. heightSample
  574. );
  575. }
  576. }
  577. return Promise.resolve(
  578. new HeightmapTerrainData({
  579. buffer: heights,
  580. width: width,
  581. height: height,
  582. childTileMask: 0,
  583. structure: this._structure,
  584. createdByUpsampling: true,
  585. })
  586. );
  587. };
  588. /**
  589. * Determines if a given child tile is available, based on the
  590. * {@link HeightmapTerrainData.childTileMask}. The given child tile coordinates are assumed
  591. * to be one of the four children of this tile. If non-child tile coordinates are
  592. * given, the availability of the southeast child tile is returned.
  593. *
  594. * @param {number} thisX The tile X coordinate of this (the parent) tile.
  595. * @param {number} thisY The tile Y coordinate of this (the parent) tile.
  596. * @param {number} childX The tile X coordinate of the child tile to check for availability.
  597. * @param {number} childY The tile Y coordinate of the child tile to check for availability.
  598. * @returns {boolean} True if the child tile is available; otherwise, false.
  599. */
  600. HeightmapTerrainData.prototype.isChildAvailable = function (
  601. thisX,
  602. thisY,
  603. childX,
  604. childY
  605. ) {
  606. //>>includeStart('debug', pragmas.debug);
  607. if (!defined(thisX)) {
  608. throw new DeveloperError("thisX is required.");
  609. }
  610. if (!defined(thisY)) {
  611. throw new DeveloperError("thisY is required.");
  612. }
  613. if (!defined(childX)) {
  614. throw new DeveloperError("childX is required.");
  615. }
  616. if (!defined(childY)) {
  617. throw new DeveloperError("childY is required.");
  618. }
  619. //>>includeEnd('debug');
  620. let bitNumber = 2; // northwest child
  621. if (childX !== thisX * 2) {
  622. ++bitNumber; // east child
  623. }
  624. if (childY !== thisY * 2) {
  625. bitNumber -= 2; // south child
  626. }
  627. return (this._childTileMask & (1 << bitNumber)) !== 0;
  628. };
  629. /**
  630. * Gets a value indicating whether or not this terrain data was created by upsampling lower resolution
  631. * terrain data. If this value is false, the data was obtained from some other source, such
  632. * as by downloading it from a remote server. This method should return true for instances
  633. * returned from a call to {@link HeightmapTerrainData#upsample}.
  634. *
  635. * @returns {boolean} True if this instance was created by upsampling; otherwise, false.
  636. */
  637. HeightmapTerrainData.prototype.wasCreatedByUpsampling = function () {
  638. return this._createdByUpsampling;
  639. };
  640. function interpolateHeight(
  641. sourceHeights,
  642. elementsPerHeight,
  643. elementMultiplier,
  644. stride,
  645. isBigEndian,
  646. sourceRectangle,
  647. width,
  648. height,
  649. longitude,
  650. latitude
  651. ) {
  652. const fromWest =
  653. ((longitude - sourceRectangle.west) * (width - 1)) /
  654. (sourceRectangle.east - sourceRectangle.west);
  655. const fromSouth =
  656. ((latitude - sourceRectangle.south) * (height - 1)) /
  657. (sourceRectangle.north - sourceRectangle.south);
  658. let westInteger = fromWest | 0;
  659. let eastInteger = westInteger + 1;
  660. if (eastInteger >= width) {
  661. eastInteger = width - 1;
  662. westInteger = width - 2;
  663. }
  664. let southInteger = fromSouth | 0;
  665. let northInteger = southInteger + 1;
  666. if (northInteger >= height) {
  667. northInteger = height - 1;
  668. southInteger = height - 2;
  669. }
  670. const dx = fromWest - westInteger;
  671. const dy = fromSouth - southInteger;
  672. southInteger = height - 1 - southInteger;
  673. northInteger = height - 1 - northInteger;
  674. const southwestHeight = getHeight(
  675. sourceHeights,
  676. elementsPerHeight,
  677. elementMultiplier,
  678. stride,
  679. isBigEndian,
  680. southInteger * width + westInteger
  681. );
  682. const southeastHeight = getHeight(
  683. sourceHeights,
  684. elementsPerHeight,
  685. elementMultiplier,
  686. stride,
  687. isBigEndian,
  688. southInteger * width + eastInteger
  689. );
  690. const northwestHeight = getHeight(
  691. sourceHeights,
  692. elementsPerHeight,
  693. elementMultiplier,
  694. stride,
  695. isBigEndian,
  696. northInteger * width + westInteger
  697. );
  698. const northeastHeight = getHeight(
  699. sourceHeights,
  700. elementsPerHeight,
  701. elementMultiplier,
  702. stride,
  703. isBigEndian,
  704. northInteger * width + eastInteger
  705. );
  706. return triangleInterpolateHeight(
  707. dx,
  708. dy,
  709. southwestHeight,
  710. southeastHeight,
  711. northwestHeight,
  712. northeastHeight
  713. );
  714. }
  715. function interpolateMeshHeight(
  716. buffer,
  717. encoding,
  718. heightOffset,
  719. heightScale,
  720. sourceRectangle,
  721. width,
  722. height,
  723. longitude,
  724. latitude
  725. ) {
  726. // returns a height encoded according to the structure's heightScale and heightOffset.
  727. const fromWest =
  728. ((longitude - sourceRectangle.west) * (width - 1)) /
  729. (sourceRectangle.east - sourceRectangle.west);
  730. const fromSouth =
  731. ((latitude - sourceRectangle.south) * (height - 1)) /
  732. (sourceRectangle.north - sourceRectangle.south);
  733. let westInteger = fromWest | 0;
  734. let eastInteger = westInteger + 1;
  735. if (eastInteger >= width) {
  736. eastInteger = width - 1;
  737. westInteger = width - 2;
  738. }
  739. let southInteger = fromSouth | 0;
  740. let northInteger = southInteger + 1;
  741. if (northInteger >= height) {
  742. northInteger = height - 1;
  743. southInteger = height - 2;
  744. }
  745. const dx = fromWest - westInteger;
  746. const dy = fromSouth - southInteger;
  747. southInteger = height - 1 - southInteger;
  748. northInteger = height - 1 - northInteger;
  749. const southwestHeight =
  750. (encoding.decodeHeight(buffer, southInteger * width + westInteger) -
  751. heightOffset) /
  752. heightScale;
  753. const southeastHeight =
  754. (encoding.decodeHeight(buffer, southInteger * width + eastInteger) -
  755. heightOffset) /
  756. heightScale;
  757. const northwestHeight =
  758. (encoding.decodeHeight(buffer, northInteger * width + westInteger) -
  759. heightOffset) /
  760. heightScale;
  761. const northeastHeight =
  762. (encoding.decodeHeight(buffer, northInteger * width + eastInteger) -
  763. heightOffset) /
  764. heightScale;
  765. return triangleInterpolateHeight(
  766. dx,
  767. dy,
  768. southwestHeight,
  769. southeastHeight,
  770. northwestHeight,
  771. northeastHeight
  772. );
  773. }
  774. function triangleInterpolateHeight(
  775. dX,
  776. dY,
  777. southwestHeight,
  778. southeastHeight,
  779. northwestHeight,
  780. northeastHeight
  781. ) {
  782. // The HeightmapTessellator bisects the quad from southwest to northeast.
  783. if (dY < dX) {
  784. // Lower right triangle
  785. return (
  786. southwestHeight +
  787. dX * (southeastHeight - southwestHeight) +
  788. dY * (northeastHeight - southeastHeight)
  789. );
  790. }
  791. // Upper left triangle
  792. return (
  793. southwestHeight +
  794. dX * (northeastHeight - northwestHeight) +
  795. dY * (northwestHeight - southwestHeight)
  796. );
  797. }
  798. function getHeight(
  799. heights,
  800. elementsPerHeight,
  801. elementMultiplier,
  802. stride,
  803. isBigEndian,
  804. index
  805. ) {
  806. index *= stride;
  807. let height = 0;
  808. let i;
  809. if (isBigEndian) {
  810. for (i = 0; i < elementsPerHeight; ++i) {
  811. height = height * elementMultiplier + heights[index + i];
  812. }
  813. } else {
  814. for (i = elementsPerHeight - 1; i >= 0; --i) {
  815. height = height * elementMultiplier + heights[index + i];
  816. }
  817. }
  818. return height;
  819. }
  820. function setHeight(
  821. heights,
  822. elementsPerHeight,
  823. elementMultiplier,
  824. divisor,
  825. stride,
  826. isBigEndian,
  827. index,
  828. height
  829. ) {
  830. index *= stride;
  831. let i;
  832. if (isBigEndian) {
  833. for (i = 0; i < elementsPerHeight - 1; ++i) {
  834. heights[index + i] = (height / divisor) | 0;
  835. height -= heights[index + i] * divisor;
  836. divisor /= elementMultiplier;
  837. }
  838. } else {
  839. for (i = elementsPerHeight - 1; i > 0; --i) {
  840. heights[index + i] = (height / divisor) | 0;
  841. height -= heights[index + i] * divisor;
  842. divisor /= elementMultiplier;
  843. }
  844. }
  845. heights[index + i] = height;
  846. }
  847. export default HeightmapTerrainData;