createElevationBandMaterial.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. import Cartesian4 from "../Core/Cartesian4.js";
  2. import CesiumMath from "../Core/Math.js";
  3. import Check from "../Core/Check.js";
  4. import Color from "../Core/Color.js";
  5. import defaultValue from "../Core/defaultValue.js";
  6. import defined from "../Core/defined.js";
  7. import DeveloperError from "../Core/DeveloperError.js";
  8. import mergeSort from "../Core/mergeSort.js";
  9. import PixelFormat from "../Core/PixelFormat.js";
  10. import PixelDatatype from "../Renderer/PixelDatatype.js";
  11. import Sampler from "../Renderer/Sampler.js";
  12. import Texture from "../Renderer/Texture.js";
  13. import TextureMagnificationFilter from "../Renderer/TextureMagnificationFilter.js";
  14. import TextureMinificationFilter from "../Renderer/TextureMinificationFilter.js";
  15. import TextureWrap from "../Renderer/TextureWrap.js";
  16. import Material from "./Material.js";
  17. const scratchColor = new Color();
  18. const scratchColorAbove = new Color();
  19. const scratchColorBelow = new Color();
  20. const scratchColorBlend = new Color();
  21. const scratchPackedFloat = new Cartesian4();
  22. const scratchColorBytes = new Uint8Array(4);
  23. function lerpEntryColor(height, entryBefore, entryAfter, result) {
  24. const lerpFactor =
  25. entryBefore.height === entryAfter.height
  26. ? 0.0
  27. : (height - entryBefore.height) /
  28. (entryAfter.height - entryBefore.height);
  29. return Color.lerp(entryBefore.color, entryAfter.color, lerpFactor, result);
  30. }
  31. function createNewEntry(height, color) {
  32. return {
  33. height: height,
  34. color: Color.clone(color),
  35. };
  36. }
  37. function removeDuplicates(entries) {
  38. // This function expects entries to be sorted from lowest to highest.
  39. // Remove entries that have the same height as before and after.
  40. entries = entries.filter(function (entry, index, array) {
  41. const hasPrev = index > 0;
  42. const hasNext = index < array.length - 1;
  43. const sameHeightAsPrev = hasPrev
  44. ? entry.height === array[index - 1].height
  45. : true;
  46. const sameHeightAsNext = hasNext
  47. ? entry.height === array[index + 1].height
  48. : true;
  49. const keep = !sameHeightAsPrev || !sameHeightAsNext;
  50. return keep;
  51. });
  52. // Remove entries that have the same color as before and after.
  53. entries = entries.filter(function (entry, index, array) {
  54. const hasPrev = index > 0;
  55. const hasNext = index < array.length - 1;
  56. const sameColorAsPrev = hasPrev
  57. ? Color.equals(entry.color, array[index - 1].color)
  58. : false;
  59. const sameColorAsNext = hasNext
  60. ? Color.equals(entry.color, array[index + 1].color)
  61. : false;
  62. const keep = !sameColorAsPrev || !sameColorAsNext;
  63. return keep;
  64. });
  65. // Also remove entries that have the same height AND color as the entry before.
  66. entries = entries.filter(function (entry, index, array) {
  67. const hasPrev = index > 0;
  68. const sameColorAsPrev = hasPrev
  69. ? Color.equals(entry.color, array[index - 1].color)
  70. : false;
  71. const sameHeightAsPrev = hasPrev
  72. ? entry.height === array[index - 1].height
  73. : true;
  74. const keep = !sameColorAsPrev || !sameHeightAsPrev;
  75. return keep;
  76. });
  77. return entries;
  78. }
  79. function preprocess(layers) {
  80. let i, j;
  81. const layeredEntries = [];
  82. const layersLength = layers.length;
  83. for (i = 0; i < layersLength; i++) {
  84. const layer = layers[i];
  85. const entriesOrig = layer.entries;
  86. const entriesLength = entriesOrig.length;
  87. //>>includeStart('debug', pragmas.debug);
  88. if (!Array.isArray(entriesOrig) || entriesLength === 0) {
  89. throw new DeveloperError("entries must be an array with size > 0.");
  90. }
  91. //>>includeEnd('debug');
  92. let entries = [];
  93. for (j = 0; j < entriesLength; j++) {
  94. const entryOrig = entriesOrig[j];
  95. //>>includeStart('debug', pragmas.debug);
  96. if (!defined(entryOrig.height)) {
  97. throw new DeveloperError("entry requires a height.");
  98. }
  99. if (!defined(entryOrig.color)) {
  100. throw new DeveloperError("entry requires a color.");
  101. }
  102. //>>includeEnd('debug');
  103. const height = CesiumMath.clamp(
  104. entryOrig.height,
  105. createElevationBandMaterial._minimumHeight,
  106. createElevationBandMaterial._maximumHeight
  107. );
  108. // premultiplied alpha
  109. const color = Color.clone(entryOrig.color, scratchColor);
  110. color.red *= color.alpha;
  111. color.green *= color.alpha;
  112. color.blue *= color.alpha;
  113. entries.push(createNewEntry(height, color));
  114. }
  115. let sortedAscending = true;
  116. let sortedDescending = true;
  117. for (j = 0; j < entriesLength - 1; j++) {
  118. const currEntry = entries[j + 0];
  119. const nextEntry = entries[j + 1];
  120. sortedAscending = sortedAscending && currEntry.height <= nextEntry.height;
  121. sortedDescending =
  122. sortedDescending && currEntry.height >= nextEntry.height;
  123. }
  124. // When the array is fully descending, reverse it.
  125. if (sortedDescending) {
  126. entries = entries.reverse();
  127. } else if (!sortedAscending) {
  128. // Stable sort from lowest to greatest height.
  129. mergeSort(entries, function (a, b) {
  130. return CesiumMath.sign(a.height - b.height);
  131. });
  132. }
  133. let extendDownwards = defaultValue(layer.extendDownwards, false);
  134. let extendUpwards = defaultValue(layer.extendUpwards, false);
  135. // Interpret a single entry to extend all the way up and down.
  136. if (entries.length === 1 && !extendDownwards && !extendUpwards) {
  137. extendDownwards = true;
  138. extendUpwards = true;
  139. }
  140. if (extendDownwards) {
  141. entries.splice(
  142. 0,
  143. 0,
  144. createNewEntry(
  145. createElevationBandMaterial._minimumHeight,
  146. entries[0].color
  147. )
  148. );
  149. }
  150. if (extendUpwards) {
  151. entries.splice(
  152. entries.length,
  153. 0,
  154. createNewEntry(
  155. createElevationBandMaterial._maximumHeight,
  156. entries[entries.length - 1].color
  157. )
  158. );
  159. }
  160. entries = removeDuplicates(entries);
  161. layeredEntries.push(entries);
  162. }
  163. return layeredEntries;
  164. }
  165. function createLayeredEntries(layers) {
  166. // clean up the input data and check for errors
  167. const layeredEntries = preprocess(layers);
  168. let entriesAccumNext = [];
  169. let entriesAccumCurr = [];
  170. let i;
  171. function addEntry(height, color) {
  172. entriesAccumNext.push(createNewEntry(height, color));
  173. }
  174. function addBlendEntry(height, a, b) {
  175. let result = Color.multiplyByScalar(b, 1.0 - a.alpha, scratchColorBlend);
  176. result = Color.add(result, a, result);
  177. addEntry(height, result);
  178. }
  179. // alpha blend new layers on top of old ones
  180. const layerLength = layeredEntries.length;
  181. for (i = 0; i < layerLength; i++) {
  182. const entries = layeredEntries[i];
  183. let idx = 0;
  184. let accumIdx = 0;
  185. // swap the arrays
  186. entriesAccumCurr = entriesAccumNext;
  187. entriesAccumNext = [];
  188. const entriesLength = entries.length;
  189. const entriesAccumLength = entriesAccumCurr.length;
  190. while (idx < entriesLength || accumIdx < entriesAccumLength) {
  191. const entry = idx < entriesLength ? entries[idx] : undefined;
  192. const prevEntry = idx > 0 ? entries[idx - 1] : undefined;
  193. const nextEntry = idx < entriesLength - 1 ? entries[idx + 1] : undefined;
  194. const entryAccum =
  195. accumIdx < entriesAccumLength ? entriesAccumCurr[accumIdx] : undefined;
  196. const prevEntryAccum =
  197. accumIdx > 0 ? entriesAccumCurr[accumIdx - 1] : undefined;
  198. const nextEntryAccum =
  199. accumIdx < entriesAccumLength - 1
  200. ? entriesAccumCurr[accumIdx + 1]
  201. : undefined;
  202. if (
  203. defined(entry) &&
  204. defined(entryAccum) &&
  205. entry.height === entryAccum.height
  206. ) {
  207. // New entry directly on top of accum entry
  208. const isSplitAccum =
  209. defined(nextEntryAccum) &&
  210. entryAccum.height === nextEntryAccum.height;
  211. const isStartAccum = !defined(prevEntryAccum);
  212. const isEndAccum = !defined(nextEntryAccum);
  213. const isSplit = defined(nextEntry) && entry.height === nextEntry.height;
  214. const isStart = !defined(prevEntry);
  215. const isEnd = !defined(nextEntry);
  216. if (isSplitAccum) {
  217. if (isSplit) {
  218. addBlendEntry(entry.height, entry.color, entryAccum.color);
  219. addBlendEntry(entry.height, nextEntry.color, nextEntryAccum.color);
  220. } else if (isStart) {
  221. addEntry(entry.height, entryAccum.color);
  222. addBlendEntry(entry.height, entry.color, nextEntryAccum.color);
  223. } else if (isEnd) {
  224. addBlendEntry(entry.height, entry.color, entryAccum.color);
  225. addEntry(entry.height, nextEntryAccum.color);
  226. } else {
  227. addBlendEntry(entry.height, entry.color, entryAccum.color);
  228. addBlendEntry(entry.height, entry.color, nextEntryAccum.color);
  229. }
  230. } else if (isStartAccum) {
  231. if (isSplit) {
  232. addEntry(entry.height, entry.color);
  233. addBlendEntry(entry.height, nextEntry.color, entryAccum.color);
  234. } else if (isEnd) {
  235. addEntry(entry.height, entry.color);
  236. addEntry(entry.height, entryAccum.color);
  237. } else if (isStart) {
  238. addBlendEntry(entry.height, entry.color, entryAccum.color);
  239. } else {
  240. addEntry(entry.height, entry.color);
  241. addBlendEntry(entry.height, entry.color, entryAccum.color);
  242. }
  243. } else if (isEndAccum) {
  244. if (isSplit) {
  245. addBlendEntry(entry.height, entry.color, entryAccum.color);
  246. addEntry(entry.height, nextEntry.color);
  247. } else if (isStart) {
  248. addEntry(entry.height, entryAccum.color);
  249. addEntry(entry.height, entry.color);
  250. } else if (isEnd) {
  251. addBlendEntry(entry.height, entry.color, entryAccum.color);
  252. } else {
  253. addBlendEntry(entry.height, entry.color, entryAccum.color);
  254. addEntry(entry.height, entry.color);
  255. }
  256. } else {
  257. // eslint-disable-next-line no-lonely-if
  258. if (isSplit) {
  259. addBlendEntry(entry.height, entry.color, entryAccum.color);
  260. addBlendEntry(entry.height, nextEntry.color, entryAccum.color);
  261. } else if (isStart) {
  262. addEntry(entry.height, entryAccum.color);
  263. addBlendEntry(entry.height, entry.color, entryAccum.color);
  264. } else if (isEnd) {
  265. addBlendEntry(entry.height, entry.color, entryAccum.color);
  266. addEntry(entry.height, entryAccum.color);
  267. } else {
  268. addBlendEntry(entry.height, entry.color, entryAccum.color);
  269. }
  270. }
  271. idx += isSplit ? 2 : 1;
  272. accumIdx += isSplitAccum ? 2 : 1;
  273. } else if (
  274. defined(entry) &&
  275. defined(entryAccum) &&
  276. defined(prevEntryAccum) &&
  277. entry.height < entryAccum.height
  278. ) {
  279. // New entry between two accum entries
  280. const colorBelow = lerpEntryColor(
  281. entry.height,
  282. prevEntryAccum,
  283. entryAccum,
  284. scratchColorBelow
  285. );
  286. if (!defined(prevEntry)) {
  287. addEntry(entry.height, colorBelow);
  288. addBlendEntry(entry.height, entry.color, colorBelow);
  289. } else if (!defined(nextEntry)) {
  290. addBlendEntry(entry.height, entry.color, colorBelow);
  291. addEntry(entry.height, colorBelow);
  292. } else {
  293. addBlendEntry(entry.height, entry.color, colorBelow);
  294. }
  295. idx++;
  296. } else if (
  297. defined(entryAccum) &&
  298. defined(entry) &&
  299. defined(prevEntry) &&
  300. entryAccum.height < entry.height
  301. ) {
  302. // Accum entry between two new entries
  303. const colorAbove = lerpEntryColor(
  304. entryAccum.height,
  305. prevEntry,
  306. entry,
  307. scratchColorAbove
  308. );
  309. if (!defined(prevEntryAccum)) {
  310. addEntry(entryAccum.height, colorAbove);
  311. addBlendEntry(entryAccum.height, colorAbove, entryAccum.color);
  312. } else if (!defined(nextEntryAccum)) {
  313. addBlendEntry(entryAccum.height, colorAbove, entryAccum.color);
  314. addEntry(entryAccum.height, colorAbove);
  315. } else {
  316. addBlendEntry(entryAccum.height, colorAbove, entryAccum.color);
  317. }
  318. accumIdx++;
  319. } else if (
  320. defined(entry) &&
  321. (!defined(entryAccum) || entry.height < entryAccum.height)
  322. ) {
  323. // New entry completely before or completely after accum entries
  324. if (
  325. defined(entryAccum) &&
  326. !defined(prevEntryAccum) &&
  327. !defined(nextEntry)
  328. ) {
  329. // Insert blank gap between last entry and first accum entry
  330. addEntry(entry.height, entry.color);
  331. addEntry(entry.height, createElevationBandMaterial._emptyColor);
  332. addEntry(entryAccum.height, createElevationBandMaterial._emptyColor);
  333. } else if (
  334. !defined(entryAccum) &&
  335. defined(prevEntryAccum) &&
  336. !defined(prevEntry)
  337. ) {
  338. // Insert blank gap between last accum entry and first entry
  339. addEntry(
  340. prevEntryAccum.height,
  341. createElevationBandMaterial._emptyColor
  342. );
  343. addEntry(entry.height, createElevationBandMaterial._emptyColor);
  344. addEntry(entry.height, entry.color);
  345. } else {
  346. addEntry(entry.height, entry.color);
  347. }
  348. idx++;
  349. } else if (
  350. defined(entryAccum) &&
  351. (!defined(entry) || entryAccum.height < entry.height)
  352. ) {
  353. // Accum entry completely before or completely after new entries
  354. addEntry(entryAccum.height, entryAccum.color);
  355. accumIdx++;
  356. }
  357. }
  358. }
  359. // one final cleanup pass in case duplicate colors show up in the final result
  360. const allEntries = removeDuplicates(entriesAccumNext);
  361. return allEntries;
  362. }
  363. /**
  364. * @typedef createElevationBandMaterialEntry
  365. *
  366. * @property {number} height The height.
  367. * @property {Color} color The color at this height.
  368. */
  369. /**
  370. * @typedef createElevationBandMaterialBand
  371. *
  372. * @property {createElevationBandMaterialEntry[]} entries A list of elevation entries. They will automatically be sorted from lowest to highest. If there is only one entry and <code>extendsDownards</code> and <code>extendUpwards</code> are both <code>false</code>, they will both be set to <code>true</code>.
  373. * @property {boolean} [extendDownwards=false] If <code>true</code>, the band's minimum elevation color will extend infinitely downwards.
  374. * @property {boolean} [extendUpwards=false] If <code>true</code>, the band's maximum elevation color will extend infinitely upwards.
  375. */
  376. /**
  377. * Creates a {@link Material} that combines multiple layers of color/gradient bands and maps them to terrain heights.
  378. *
  379. * The shader does a binary search over all the heights to find out which colors are above and below a given height, and
  380. * interpolates between them for the final color. This material supports hundreds of entries relatively cheaply.
  381. *
  382. * @function createElevationBandMaterial
  383. *
  384. * @param {object} options Object with the following properties:
  385. * @param {Scene} options.scene The scene where the visualization is taking place.
  386. * @param {createElevationBandMaterialBand[]} options.layers A list of bands ordered from lowest to highest precedence.
  387. * @returns {Material} A new {@link Material} instance.
  388. *
  389. * @demo {@link https://sandcastle.cesium.com/index.html?src=Elevation%20Band%20Material.html|Cesium Sandcastle Elevation Band Demo}
  390. *
  391. * @example
  392. * scene.globe.material = Cesium.createElevationBandMaterial({
  393. * scene : scene,
  394. * layers : [{
  395. * entries : [{
  396. * height : 4200.0,
  397. * color : new Cesium.Color(0.0, 0.0, 0.0, 1.0)
  398. * }, {
  399. * height : 8848.0,
  400. * color : new Cesium.Color(1.0, 1.0, 1.0, 1.0)
  401. * }],
  402. * extendDownwards : true,
  403. * extendUpwards : true,
  404. * }, {
  405. * entries : [{
  406. * height : 7000.0,
  407. * color : new Cesium.Color(1.0, 0.0, 0.0, 0.5)
  408. * }, {
  409. * height : 7100.0,
  410. * color : new Cesium.Color(1.0, 0.0, 0.0, 0.5)
  411. * }]
  412. * }]
  413. * });
  414. */
  415. function createElevationBandMaterial(options) {
  416. const { scene, layers } = defaultValue(options, defaultValue.EMPTY_OBJECT);
  417. //>>includeStart('debug', pragmas.debug);
  418. Check.typeOf.object("options.scene", scene);
  419. Check.defined("options.layers", layers);
  420. Check.typeOf.number.greaterThan("options.layers.length", layers.length, 0);
  421. //>>includeEnd('debug');
  422. const { context } = scene;
  423. const entries = createLayeredEntries(layers);
  424. const entriesLength = entries.length;
  425. let heightTexBuffer;
  426. let heightTexDatatype;
  427. let heightTexFormat;
  428. const isPackedHeight = !createElevationBandMaterial._useFloatTexture(context);
  429. if (isPackedHeight) {
  430. heightTexDatatype = PixelDatatype.UNSIGNED_BYTE;
  431. heightTexFormat = PixelFormat.RGBA;
  432. heightTexBuffer = new Uint8Array(entriesLength * 4);
  433. for (let i = 0; i < entriesLength; i++) {
  434. Cartesian4.packFloat(entries[i].height, scratchPackedFloat);
  435. Cartesian4.pack(scratchPackedFloat, heightTexBuffer, i * 4);
  436. }
  437. } else {
  438. heightTexDatatype = PixelDatatype.FLOAT;
  439. heightTexFormat = context.webgl2 ? PixelFormat.RED : PixelFormat.LUMINANCE;
  440. heightTexBuffer = new Float32Array(entriesLength);
  441. for (let i = 0; i < entriesLength; i++) {
  442. heightTexBuffer[i] = entries[i].height;
  443. }
  444. }
  445. const heightsTex = Texture.create({
  446. context: context,
  447. pixelFormat: heightTexFormat,
  448. pixelDatatype: heightTexDatatype,
  449. source: {
  450. arrayBufferView: heightTexBuffer,
  451. width: entriesLength,
  452. height: 1,
  453. },
  454. sampler: new Sampler({
  455. wrapS: TextureWrap.CLAMP_TO_EDGE,
  456. wrapT: TextureWrap.CLAMP_TO_EDGE,
  457. minificationFilter: TextureMinificationFilter.NEAREST,
  458. magnificationFilter: TextureMagnificationFilter.NEAREST,
  459. }),
  460. });
  461. const colorsArray = new Uint8Array(entriesLength * 4);
  462. for (let i = 0; i < entriesLength; i++) {
  463. const color = entries[i].color;
  464. color.toBytes(scratchColorBytes);
  465. colorsArray[i * 4 + 0] = scratchColorBytes[0];
  466. colorsArray[i * 4 + 1] = scratchColorBytes[1];
  467. colorsArray[i * 4 + 2] = scratchColorBytes[2];
  468. colorsArray[i * 4 + 3] = scratchColorBytes[3];
  469. }
  470. const colorsTex = Texture.create({
  471. context: context,
  472. pixelFormat: PixelFormat.RGBA,
  473. pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
  474. source: {
  475. arrayBufferView: colorsArray,
  476. width: entriesLength,
  477. height: 1,
  478. },
  479. sampler: new Sampler({
  480. wrapS: TextureWrap.CLAMP_TO_EDGE,
  481. wrapT: TextureWrap.CLAMP_TO_EDGE,
  482. minificationFilter: TextureMinificationFilter.LINEAR,
  483. magnificationFilter: TextureMagnificationFilter.LINEAR,
  484. }),
  485. });
  486. return Material.fromType("ElevationBand", {
  487. heights: heightsTex,
  488. colors: colorsTex,
  489. });
  490. }
  491. /**
  492. * Function for checking if the context will allow floating point textures for heights.
  493. *
  494. * @param {Context} context The {@link Context}.
  495. * @returns {boolean} <code>true</code> if floating point textures can be used for heights.
  496. * @private
  497. */
  498. createElevationBandMaterial._useFloatTexture = function (context) {
  499. return context.floatingPointTexture;
  500. };
  501. /**
  502. * This is the height that gets stored in the texture when using extendUpwards.
  503. * There's nothing special about it, it's just a really big number.
  504. * @private
  505. */
  506. createElevationBandMaterial._maximumHeight = +5906376425472;
  507. /**
  508. * This is the height that gets stored in the texture when using extendDownwards.
  509. * There's nothing special about it, it's just a really big number.
  510. * @private
  511. */
  512. createElevationBandMaterial._minimumHeight = -5906376425472;
  513. /**
  514. * Color used to create empty space in the color texture
  515. * @private
  516. */
  517. createElevationBandMaterial._emptyColor = new Color(0.0, 0.0, 0.0, 0.0);
  518. export default createElevationBandMaterial;