HeightmapTerrainData.js 29 KB

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