BatchTexture.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import arrayFill from "../Core/arrayFill.js";
  2. import Cartesian2 from "../Core/Cartesian2.js";
  3. import Cartesian4 from "../Core/Cartesian4.js";
  4. import Check from "../Core/Check.js";
  5. import Color from "../Core/Color.js";
  6. import defined from "../Core/defined.js";
  7. import destroyObject from "../Core/destroyObject.js";
  8. import DeveloperError from "../Core/DeveloperError.js";
  9. import PixelFormat from "../Core/PixelFormat.js";
  10. import ContextLimits from "../Renderer/ContextLimits.js";
  11. import PixelDatatype from "../Renderer/PixelDatatype.js";
  12. import Sampler from "../Renderer/Sampler.js";
  13. import Texture from "../Renderer/Texture.js";
  14. /**
  15. * An object that manages color, show/hide and picking textures for a batch
  16. * table or feature table.
  17. *
  18. * @param {Object} options Object with the following properties:
  19. * @param {Number} featuresLength The number of features in the batch table or feature table
  20. * @param {Cesium3DTileContent|ModelFeatureTable} owner The owner of this batch texture. For 3D Tiles, this will be a {@link Cesium3DTileContent}. For glTF models, this will be a {@link ModelFeatureTable}.
  21. * @param {Object} [statistics] The statistics object to update with information about the batch texture.
  22. * @param {Function} [colorChangedCallback] A callback function that is called whenever the color of a feature changes.
  23. *
  24. * @alias BatchTexture
  25. * @constructor
  26. *
  27. * @private
  28. */
  29. export default function BatchTexture(options) {
  30. //>>includeStart('debug', pragmas.debug);
  31. Check.typeOf.number("options.featuresLength", options.featuresLength);
  32. Check.typeOf.object("options.owner", options.owner);
  33. //>>includeEnd('debug');
  34. const featuresLength = options.featuresLength;
  35. // PERFORMANCE_IDEA: These parallel arrays probably generate cache misses in get/set color/show
  36. // and use A LOT of memory. How can we use less memory?
  37. this._showAlphaProperties = undefined; // [Show (0 or 255), Alpha (0 to 255)] property for each feature
  38. this._batchValues = undefined; // Per-feature RGBA (A is based on the color's alpha and feature's show property)
  39. this._batchValuesDirty = false;
  40. this._batchTexture = undefined;
  41. this._defaultTexture = undefined;
  42. this._pickTexture = undefined;
  43. this._pickIds = [];
  44. // Dimensions for batch and pick textures
  45. let textureDimensions;
  46. let textureStep;
  47. if (featuresLength > 0) {
  48. // PERFORMANCE_IDEA: this can waste memory in the last row in the uncommon case
  49. // when more than one row is needed (e.g., > 16K features in one tile)
  50. const width = Math.min(featuresLength, ContextLimits.maximumTextureSize);
  51. const height = Math.ceil(featuresLength / ContextLimits.maximumTextureSize);
  52. const stepX = 1.0 / width;
  53. const centerX = stepX * 0.5;
  54. const stepY = 1.0 / height;
  55. const centerY = stepY * 0.5;
  56. textureDimensions = new Cartesian2(width, height);
  57. textureStep = new Cartesian4(stepX, centerX, stepY, centerY);
  58. }
  59. this._translucentFeaturesLength = 0;
  60. this._featuresLength = featuresLength;
  61. this._textureDimensions = textureDimensions;
  62. this._textureStep = textureStep;
  63. this._owner = options.owner;
  64. this._statistics = options.statistics;
  65. this._colorChangedCallback = options.colorChangedCallback;
  66. }
  67. Object.defineProperties(BatchTexture.prototype, {
  68. /**
  69. * Number of features that are translucent
  70. *
  71. * @memberof BatchTexture.prototype
  72. * @type {Number}
  73. * @readonly
  74. * @private
  75. */
  76. translucentFeaturesLength: {
  77. get: function () {
  78. return this._translucentFeaturesLength;
  79. },
  80. },
  81. /**
  82. * Total size of all GPU resources used by this batch texture.
  83. *
  84. * @memberof BatchTexture.prototype
  85. * @type {Number}
  86. * @readonly
  87. * @private
  88. */
  89. memorySizeInBytes: {
  90. get: function () {
  91. let memory = 0;
  92. if (defined(this._pickTexture)) {
  93. memory += this._pickTexture.sizeInBytes;
  94. }
  95. if (defined(this._batchTexture)) {
  96. memory += this._batchTexture.sizeInBytes;
  97. }
  98. return memory;
  99. },
  100. },
  101. /**
  102. * Dimensions of the underlying batch texture.
  103. *
  104. * @memberof BatchTexture.prototype
  105. * @type {Cartesian2}
  106. * @readonly
  107. * @private
  108. */
  109. textureDimensions: {
  110. get: function () {
  111. return this._textureDimensions;
  112. },
  113. },
  114. /**
  115. * Size of each texture and distance from side to center of a texel in
  116. * each direction. Stored as (stepX, centerX, stepY, centerY)
  117. *
  118. * @memberof BatchTexture.prototype
  119. * @type {Cartesian4}
  120. * @readonly
  121. * @private
  122. */
  123. textureStep: {
  124. get: function () {
  125. return this._textureStep;
  126. },
  127. },
  128. /**
  129. * The underlying texture used for styling. The texels are accessed
  130. * by batch ID, and the value is the color of this feature after accounting
  131. * for show/hide settings.
  132. *
  133. * @memberof BatchTexture.prototype
  134. * @type {Texture}
  135. * @readonly
  136. * @private
  137. */
  138. batchTexture: {
  139. get: function () {
  140. return this._batchTexture;
  141. },
  142. },
  143. /**
  144. * The default texture to use when there are no batch values
  145. *
  146. * @memberof BatchTexture.prototype
  147. * @type {Texture}
  148. * @readonly
  149. * @private
  150. */
  151. defaultTexture: {
  152. get: function () {
  153. return this._defaultTexture;
  154. },
  155. },
  156. /**
  157. * The underlying texture used for picking. The texels are accessed by
  158. * batch ID, and the value is the pick color.
  159. *
  160. * @memberof BatchTexture.prototype
  161. * @type {Texture}
  162. * @readonly
  163. * @private
  164. */
  165. pickTexture: {
  166. get: function () {
  167. return this._pickTexture;
  168. },
  169. },
  170. });
  171. BatchTexture.DEFAULT_COLOR_VALUE = Color.WHITE;
  172. BatchTexture.DEFAULT_SHOW_VALUE = true;
  173. function getByteLength(batchTexture) {
  174. const dimensions = batchTexture._textureDimensions;
  175. return dimensions.x * dimensions.y * 4;
  176. }
  177. function getBatchValues(batchTexture) {
  178. if (!defined(batchTexture._batchValues)) {
  179. // Default batch texture to RGBA = 255: white highlight (RGB) and show/alpha = true/255 (A).
  180. const byteLength = getByteLength(batchTexture);
  181. const bytes = new Uint8Array(byteLength);
  182. arrayFill(bytes, 255);
  183. batchTexture._batchValues = bytes;
  184. }
  185. return batchTexture._batchValues;
  186. }
  187. function getShowAlphaProperties(batchTexture) {
  188. if (!defined(batchTexture._showAlphaProperties)) {
  189. const byteLength = 2 * batchTexture._featuresLength;
  190. const bytes = new Uint8Array(byteLength);
  191. // [Show = true, Alpha = 255]
  192. arrayFill(bytes, 255);
  193. batchTexture._showAlphaProperties = bytes;
  194. }
  195. return batchTexture._showAlphaProperties;
  196. }
  197. function checkBatchId(batchId, featuresLength) {
  198. if (!defined(batchId) || batchId < 0 || batchId >= featuresLength) {
  199. throw new DeveloperError(
  200. `batchId is required and between zero and featuresLength - 1 (${featuresLength}` -
  201. +")."
  202. );
  203. }
  204. }
  205. /**
  206. * Set whether a feature is visible.
  207. *
  208. * @param {Number} batchId the ID of the feature
  209. * @param {Boolean} show <code>true</code> if the feature should be shown, <code>false</code> otherwise
  210. * @private
  211. */
  212. BatchTexture.prototype.setShow = function (batchId, show) {
  213. //>>includeStart('debug', pragmas.debug);
  214. checkBatchId(batchId, this._featuresLength);
  215. Check.typeOf.bool("show", show);
  216. //>>includeEnd('debug');
  217. if (show && !defined(this._showAlphaProperties)) {
  218. // Avoid allocating since the default is show = true
  219. return;
  220. }
  221. const showAlphaProperties = getShowAlphaProperties(this);
  222. const propertyOffset = batchId * 2;
  223. const newShow = show ? 255 : 0;
  224. if (showAlphaProperties[propertyOffset] !== newShow) {
  225. showAlphaProperties[propertyOffset] = newShow;
  226. const batchValues = getBatchValues(this);
  227. // Compute alpha used in the shader based on show and color.alpha properties
  228. const offset = batchId * 4 + 3;
  229. batchValues[offset] = show ? showAlphaProperties[propertyOffset + 1] : 0;
  230. this._batchValuesDirty = true;
  231. }
  232. };
  233. /**
  234. * Set the show for all features at once.
  235. *
  236. * @param {Boolean} show <code>true</code> if the feature should be shown, <code>false</code> otherwise
  237. * @private
  238. */
  239. BatchTexture.prototype.setAllShow = function (show) {
  240. //>>includeStart('debug', pragmas.debug);
  241. Check.typeOf.bool("show", show);
  242. //>>includeEnd('debug');
  243. const featuresLength = this._featuresLength;
  244. for (let i = 0; i < featuresLength; ++i) {
  245. this.setShow(i, show);
  246. }
  247. };
  248. /**
  249. * Check the current show value for a feature
  250. *
  251. * @param {Number} batchId the ID of the feature
  252. * @return {Boolean} <code>true</code> if the feature is shown, or <code>false</code> otherwise
  253. * @private
  254. */
  255. BatchTexture.prototype.getShow = function (batchId) {
  256. //>>includeStart('debug', pragmas.debug);
  257. checkBatchId(batchId, this._featuresLength);
  258. //>>includeEnd('debug');
  259. if (!defined(this._showAlphaProperties)) {
  260. // Avoid allocating since the default is show = true
  261. return true;
  262. }
  263. const offset = batchId * 2;
  264. return this._showAlphaProperties[offset] === 255;
  265. };
  266. const scratchColorBytes = new Array(4);
  267. /**
  268. * Set the styling color of a feature
  269. *
  270. * @param {Number} batchId the ID of the feature
  271. * @param {Color} color the color to assign to this feature.
  272. *
  273. * @private
  274. */
  275. BatchTexture.prototype.setColor = function (batchId, color) {
  276. //>>includeStart('debug', pragmas.debug);
  277. checkBatchId(batchId, this._featuresLength);
  278. Check.typeOf.object("color", color);
  279. //>>includeEnd('debug');
  280. if (
  281. Color.equals(color, BatchTexture.DEFAULT_COLOR_VALUE) &&
  282. !defined(this._batchValues)
  283. ) {
  284. // Avoid allocating since the default is white
  285. return;
  286. }
  287. const newColor = color.toBytes(scratchColorBytes);
  288. const newAlpha = newColor[3];
  289. const batchValues = getBatchValues(this);
  290. const offset = batchId * 4;
  291. const showAlphaProperties = getShowAlphaProperties(this);
  292. const propertyOffset = batchId * 2;
  293. if (
  294. batchValues[offset] !== newColor[0] ||
  295. batchValues[offset + 1] !== newColor[1] ||
  296. batchValues[offset + 2] !== newColor[2] ||
  297. showAlphaProperties[propertyOffset + 1] !== newAlpha
  298. ) {
  299. batchValues[offset] = newColor[0];
  300. batchValues[offset + 1] = newColor[1];
  301. batchValues[offset + 2] = newColor[2];
  302. const wasTranslucent = showAlphaProperties[propertyOffset + 1] !== 255;
  303. // Compute alpha used in the shader based on show and color.alpha properties
  304. const show = showAlphaProperties[propertyOffset] !== 0;
  305. batchValues[offset + 3] = show ? newAlpha : 0;
  306. showAlphaProperties[propertyOffset + 1] = newAlpha;
  307. // Track number of translucent features so we know if this tile needs
  308. // opaque commands, translucent commands, or both for rendering.
  309. const isTranslucent = newAlpha !== 255;
  310. if (isTranslucent && !wasTranslucent) {
  311. ++this._translucentFeaturesLength;
  312. } else if (!isTranslucent && wasTranslucent) {
  313. --this._translucentFeaturesLength;
  314. }
  315. this._batchValuesDirty = true;
  316. if (defined(this._colorChangedCallback)) {
  317. this._colorChangedCallback(batchId, color);
  318. }
  319. }
  320. };
  321. /**
  322. * Set the styling color for all features at once
  323. *
  324. * @param {Color} color the color to assign to all features.
  325. *
  326. * @private
  327. */
  328. BatchTexture.prototype.setAllColor = function (color) {
  329. //>>includeStart('debug', pragmas.debug);
  330. Check.typeOf.object("color", color);
  331. //>>includeEnd('debug');
  332. const featuresLength = this._featuresLength;
  333. for (let i = 0; i < featuresLength; ++i) {
  334. this.setColor(i, color);
  335. }
  336. };
  337. /**
  338. * Get the current color of a feature
  339. *
  340. * @param {Number} batchId The ID of the feature
  341. * @param {Color} result A color object where the result will be stored.
  342. * @return {Color} The color assigned to the selected feature
  343. *
  344. * @private
  345. */
  346. BatchTexture.prototype.getColor = function (batchId, result) {
  347. //>>includeStart('debug', pragmas.debug);
  348. checkBatchId(batchId, this._featuresLength);
  349. Check.typeOf.object("result", result);
  350. //>>includeEnd('debug');
  351. if (!defined(this._batchValues)) {
  352. return Color.clone(BatchTexture.DEFAULT_COLOR_VALUE, result);
  353. }
  354. const batchValues = this._batchValues;
  355. const offset = batchId * 4;
  356. const showAlphaProperties = this._showAlphaProperties;
  357. const propertyOffset = batchId * 2;
  358. return Color.fromBytes(
  359. batchValues[offset],
  360. batchValues[offset + 1],
  361. batchValues[offset + 2],
  362. showAlphaProperties[propertyOffset + 1],
  363. result
  364. );
  365. };
  366. /**
  367. * Get the pick color of a feature. This feature is an RGBA encoding of the
  368. * pick ID.
  369. *
  370. * @param {Number} batchId The ID of the feature
  371. * @return {PickId} The picking color assigned to this feature
  372. *
  373. * @private
  374. */
  375. BatchTexture.prototype.getPickColor = function (batchId) {
  376. //>>includeStart('debug', pragmas.debug);
  377. checkBatchId(batchId, this._featuresLength);
  378. //>>includeEnd('debug');
  379. return this._pickIds[batchId];
  380. };
  381. function createTexture(batchTexture, context, bytes) {
  382. const dimensions = batchTexture._textureDimensions;
  383. return new Texture({
  384. context: context,
  385. pixelFormat: PixelFormat.RGBA,
  386. pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
  387. source: {
  388. width: dimensions.x,
  389. height: dimensions.y,
  390. arrayBufferView: bytes,
  391. },
  392. flipY: false,
  393. sampler: Sampler.NEAREST,
  394. });
  395. }
  396. function createPickTexture(batchTexture, context) {
  397. const featuresLength = batchTexture._featuresLength;
  398. if (!defined(batchTexture._pickTexture) && featuresLength > 0) {
  399. const pickIds = batchTexture._pickIds;
  400. const byteLength = getByteLength(batchTexture);
  401. const bytes = new Uint8Array(byteLength);
  402. const owner = batchTexture._owner;
  403. const statistics = batchTexture._statistics;
  404. // PERFORMANCE_IDEA: we could skip the pick texture completely by allocating
  405. // a continuous range of pickIds and then converting the base pickId + batchId
  406. // to RGBA in the shader. The only consider is precision issues, which might
  407. // not be an issue in WebGL 2.
  408. for (let i = 0; i < featuresLength; ++i) {
  409. const pickId = context.createPickId(owner.getFeature(i));
  410. pickIds.push(pickId);
  411. const pickColor = pickId.color;
  412. const offset = i * 4;
  413. bytes[offset] = Color.floatToByte(pickColor.red);
  414. bytes[offset + 1] = Color.floatToByte(pickColor.green);
  415. bytes[offset + 2] = Color.floatToByte(pickColor.blue);
  416. bytes[offset + 3] = Color.floatToByte(pickColor.alpha);
  417. }
  418. batchTexture._pickTexture = createTexture(batchTexture, context, bytes);
  419. if (defined(statistics)) {
  420. statistics.batchTableByteLength += batchTexture._pickTexture.sizeInBytes;
  421. }
  422. }
  423. }
  424. function updateBatchTexture(batchTexture) {
  425. const dimensions = batchTexture._textureDimensions;
  426. // PERFORMANCE_IDEA: Instead of rewriting the entire texture, use fine-grained
  427. // texture updates when less than, for example, 10%, of the values changed. Or
  428. // even just optimize the common case when one feature show/color changed.
  429. batchTexture._batchTexture.copyFrom({
  430. source: {
  431. width: dimensions.x,
  432. height: dimensions.y,
  433. arrayBufferView: batchTexture._batchValues,
  434. },
  435. });
  436. }
  437. BatchTexture.prototype.update = function (tileset, frameState) {
  438. const context = frameState.context;
  439. this._defaultTexture = context.defaultTexture;
  440. const passes = frameState.passes;
  441. if (passes.pick || passes.postProcess) {
  442. createPickTexture(this, context);
  443. }
  444. if (this._batchValuesDirty) {
  445. this._batchValuesDirty = false;
  446. // Create batch texture on-demand
  447. if (!defined(this._batchTexture)) {
  448. this._batchTexture = createTexture(this, context, this._batchValues);
  449. if (defined(this._statistics)) {
  450. this._statistics.batchTableByteLength += this._batchTexture.sizeInBytes;
  451. }
  452. }
  453. updateBatchTexture(this); // Apply per-feature show/color updates
  454. }
  455. };
  456. /**
  457. * Returns true if this object was destroyed; otherwise, false.
  458. * <p>
  459. * If this object was destroyed, it should not be used; calling any function other than
  460. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  461. * </p>
  462. *
  463. * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  464. *
  465. * @see BatchTexture#destroy
  466. * @private
  467. */
  468. BatchTexture.prototype.isDestroyed = function () {
  469. return false;
  470. };
  471. /**
  472. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  473. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  474. * <p>
  475. * Once an object is destroyed, it should not be used; calling any function other than
  476. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  477. * assign the return value (<code>undefined</code>) to the object as done in the example.
  478. * </p>
  479. *
  480. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  481. *
  482. * @example
  483. * e = e && e.destroy();
  484. *
  485. * @see BatchTexture#isDestroyed
  486. * @private
  487. */
  488. BatchTexture.prototype.destroy = function () {
  489. this._batchTexture = this._batchTexture && this._batchTexture.destroy();
  490. this._pickTexture = this._pickTexture && this._pickTexture.destroy();
  491. const pickIds = this._pickIds;
  492. const length = pickIds.length;
  493. for (let i = 0; i < length; ++i) {
  494. pickIds[i].destroy();
  495. }
  496. return destroyObject(this);
  497. };