智慧水务管理系统 - 精河县供水工程综合管理平台

CloudCollection.js 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. import BlendingState from "./BlendingState.js";
  2. import Buffer from "../Renderer/Buffer.js";
  3. import BufferUsage from "../Renderer/BufferUsage.js";
  4. import Cartesian3 from "../Core/Cartesian3.js";
  5. import Check from "../Core/Check.js";
  6. import Color from "../Core/Color.js";
  7. import ComputeCommand from "../Renderer/ComputeCommand.js";
  8. import CloudType from "./CloudType.js";
  9. import CloudCollectionFS from "../Shaders/CloudCollectionFS.js";
  10. import CloudCollectionVS from "../Shaders/CloudCollectionVS.js";
  11. import CloudNoiseFS from "../Shaders/CloudNoiseFS.js";
  12. import CloudNoiseVS from "../Shaders/CloudNoiseVS.js";
  13. import ComponentDatatype from "../Core/ComponentDatatype.js";
  14. import CumulusCloud from "./CumulusCloud.js";
  15. import Frozen from "../Core/Frozen.js";
  16. import defined from "../Core/defined.js";
  17. import destroyObject from "../Core/destroyObject.js";
  18. import DeveloperError from "../Core/DeveloperError.js";
  19. import DrawCommand from "../Renderer/DrawCommand.js";
  20. import EncodedCartesian3 from "../Core/EncodedCartesian3.js";
  21. import IndexDatatype from "../Core/IndexDatatype.js";
  22. import Pass from "../Renderer/Pass.js";
  23. import PixelDatatype from "../Renderer/PixelDatatype.js";
  24. import PixelFormat from "../Core/PixelFormat.js";
  25. import RenderState from "../Renderer/RenderState.js";
  26. import Sampler from "../Renderer/Sampler.js";
  27. import ShaderSource from "../Renderer/ShaderSource.js";
  28. import ShaderProgram from "../Renderer/ShaderProgram.js";
  29. import Texture from "../Renderer/Texture.js";
  30. import TextureMagnificationFilter from "../Renderer/TextureMagnificationFilter.js";
  31. import TextureMinificationFilter from "../Renderer/TextureMinificationFilter.js";
  32. import TextureWrap from "../Renderer/TextureWrap.js";
  33. import VertexArray from "../Renderer/VertexArray.js";
  34. import VertexArrayFacade from "../Renderer/VertexArrayFacade.js";
  35. import WebGLConstants from "../Core/WebGLConstants.js";
  36. let attributeLocations;
  37. const scratchTextureDimensions = new Cartesian3();
  38. const attributeLocationsBatched = {
  39. positionHighAndScaleX: 0,
  40. positionLowAndScaleY: 1,
  41. packedAttribute0: 2, // show, brightness, direction
  42. packedAttribute1: 3, // cloudSize, slice
  43. color: 4,
  44. };
  45. const attributeLocationsInstanced = {
  46. direction: 0,
  47. positionHighAndScaleX: 1,
  48. positionLowAndScaleY: 2,
  49. packedAttribute0: 3, // show, brightness
  50. packedAttribute1: 4, // cloudSize, slice
  51. color: 5,
  52. };
  53. const SHOW_INDEX = CumulusCloud.SHOW_INDEX;
  54. const POSITION_INDEX = CumulusCloud.POSITION_INDEX;
  55. const SCALE_INDEX = CumulusCloud.SCALE_INDEX;
  56. const MAXIMUM_SIZE_INDEX = CumulusCloud.MAXIMUM_SIZE_INDEX;
  57. const SLICE_INDEX = CumulusCloud.SLICE_INDEX;
  58. const BRIGHTNESS_INDEX = CumulusCloud.BRIGHTNESS_INDEX;
  59. const NUMBER_OF_PROPERTIES = CumulusCloud.NUMBER_OF_PROPERTIES;
  60. const COLOR_INDEX = CumulusCloud.COLOR_INDEX;
  61. /**
  62. * A renderable collection of clouds in the 3D scene.
  63. * <br /><br />
  64. * <div align='center'>
  65. * <img src='Images/CumulusCloud.png' width='400' height='300' /><br />
  66. * Example cumulus clouds
  67. * </div>
  68. * <br /><br />
  69. * Clouds are added and removed from the collection using {@link CloudCollection#add}
  70. * and {@link CloudCollection#remove}.
  71. * @alias CloudCollection
  72. * @constructor
  73. *
  74. * @param {object} [options] Object with the following properties:
  75. * @param {boolean} [options.show=true] Whether to display the clouds.
  76. * @param {number} [options.noiseDetail=16.0] Desired amount of detail in the noise texture.
  77. * @param {number} [options.noiseOffset=Cartesian3.ZERO] Desired translation of data in noise texture.
  78. * @param {boolean} [options.debugBillboards=false] For debugging only. Determines if the billboards are rendered with an opaque color.
  79. * @param {boolean} [options.debugEllipsoids=false] For debugging only. Determines if the clouds will be rendered as opaque ellipsoids.
  80. * @see CloudCollection#add
  81. * @see CloudCollection#remove
  82. * @see CumulusCloud
  83. *
  84. * @demo {@link https://sandcastle.cesium.com/index.html?id=clouds|Cesium Sandcastle Clouds Demo}
  85. * @demo {@link https://sandcastle.cesium.com/index.html?id=cloud-parameters|Cesium Sandcastle Cloud Parameters Demo}
  86. *
  87. * @example
  88. * // Create a cloud collection with two cumulus clouds
  89. * const clouds = scene.primitives.add(new Cesium.CloudCollection());
  90. * clouds.add({
  91. * position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
  92. * maximumSize: new Cesium.Cartesian3(20.0, 12.0, 8.0)
  93. * });
  94. * clouds.add({
  95. * position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
  96. * maximumSize: new Cesium.Cartesian3(15.0, 9.0, 9.0),
  97. * slice: 0.5
  98. * });
  99. *
  100. */
  101. function CloudCollection(options) {
  102. options = options ?? Frozen.EMPTY_OBJECT;
  103. this._clouds = [];
  104. this._cloudsToUpdate = [];
  105. this._cloudsToUpdateIndex = 0;
  106. this._cloudsRemoved = false;
  107. this._createVertexArray = false;
  108. this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES);
  109. this._noiseTexture = undefined;
  110. this._textureSliceWidth = 128;
  111. this._noiseTextureRows = 4;
  112. /**
  113. * <p>
  114. * Controls the amount of detail captured in the precomputed noise texture
  115. * used to render the cumulus clouds. In order for the texture to be tileable,
  116. * this must be a power of two. For best results, set this to be a power of two
  117. * between <code>8.0</code> and <code>32.0</code> (inclusive).
  118. * </p>
  119. *
  120. * <div align='center'>
  121. * <table border='0' cellpadding='5'><tr>
  122. * <td align='center'>
  123. * <code>clouds.noiseDetail = 8.0;</code><br/>
  124. * <img src='Images/CloudCollection.noiseDetail8.png' width='250' height='158' />
  125. * </td>
  126. * <td align='center'>
  127. * <code>clouds.noiseDetail = 32.0;</code><br/>
  128. * <img src='Images/CloudCollection.noiseDetail32.png' width='250' height='158' />
  129. * </td>
  130. * </tr></table>
  131. * </div>
  132. *
  133. * @type {number}
  134. *
  135. * @default 16.0
  136. */
  137. this.noiseDetail = options.noiseDetail ?? 16.0;
  138. /**
  139. * <p>
  140. * Applies a translation to noise texture coordinates to generate different data.
  141. * This can be modified if the default noise does not generate good-looking clouds.
  142. * </p>
  143. *
  144. * <div align='center'>
  145. * <table border='0' cellpadding='5'><tr>
  146. * <td align='center'>
  147. * <code>default</code><br/>
  148. * <img src='Images/CloudCollection.noiseOffsetdefault.png' width='250' height='158' />
  149. * </td>
  150. * <td align='center'>
  151. * <code>clouds.noiseOffset = new Cesium.Cartesian3(10, 20, 10);</code><br/>
  152. * <img src='Images/CloudCollection.noiseOffsetx10y20z10.png' width='250' height='158' />
  153. * </td>
  154. * </tr></table>
  155. * </div>
  156. * @type {Cartesian3}
  157. *
  158. * @default Cartesian3.ZERO
  159. */
  160. this.noiseOffset = Cartesian3.clone(options.noiseOffset ?? Cartesian3.ZERO);
  161. this._loading = false;
  162. this._ready = false;
  163. const that = this;
  164. this._uniforms = {
  165. u_noiseTexture: function () {
  166. return that._noiseTexture;
  167. },
  168. u_noiseTextureDimensions: getNoiseTextureDimensions(that),
  169. u_noiseDetail: function () {
  170. return that.noiseDetail;
  171. },
  172. };
  173. this._vaNoise = undefined;
  174. this._spNoise = undefined;
  175. this._spCreated = false;
  176. this._sp = undefined;
  177. this._rs = undefined;
  178. /**
  179. * Determines if billboards in this collection will be shown.
  180. *
  181. * @type {boolean}
  182. * @default true
  183. */
  184. this.show = options.show ?? true;
  185. this._colorCommands = [];
  186. /**
  187. * This property is for debugging only; it is not for production use nor is it optimized.
  188. * <p>
  189. * Renders the billboards with one opaque color for the sake of debugging.
  190. * </p>
  191. *
  192. * @type {boolean}
  193. *
  194. * @default false
  195. */
  196. this.debugBillboards = options.debugBillboards ?? false;
  197. this._compiledDebugBillboards = false;
  198. /**
  199. * This property is for debugging only; it is not for production use nor is it optimized.
  200. * <p>
  201. * Draws the clouds as opaque, monochrome ellipsoids for the sake of debugging.
  202. * If <code>debugBillboards</code> is also true, then the ellipsoids will draw on top of the billboards.
  203. * </p>
  204. *
  205. * @type {boolean}
  206. *
  207. * @default false
  208. */
  209. this.debugEllipsoids = options.debugEllipsoids ?? false;
  210. this._compiledDebugEllipsoids = false;
  211. }
  212. // Wraps useful texture metrics into a single vec3 for less overhead.
  213. function getNoiseTextureDimensions(collection) {
  214. return function () {
  215. scratchTextureDimensions.x = collection._textureSliceWidth;
  216. scratchTextureDimensions.y = collection._noiseTextureRows;
  217. scratchTextureDimensions.z = 1.0 / collection._noiseTextureRows;
  218. return scratchTextureDimensions;
  219. };
  220. }
  221. Object.defineProperties(CloudCollection.prototype, {
  222. /**
  223. * Returns the number of clouds in this collection.
  224. * @memberof CloudCollection.prototype
  225. * @type {number}
  226. */
  227. length: {
  228. get: function () {
  229. removeClouds(this);
  230. return this._clouds.length;
  231. },
  232. },
  233. });
  234. function destroyClouds(clouds) {
  235. const length = clouds.length;
  236. for (let i = 0; i < length; ++i) {
  237. if (clouds[i]) {
  238. clouds[i]._destroy();
  239. }
  240. }
  241. }
  242. /**
  243. * Creates and adds a cloud with the specified initial properties to the collection.
  244. * The added cloud is returned so it can be modified or removed from the collection later.
  245. *
  246. * @param {object}[options] A template describing the cloud's properties as shown in Example 1.
  247. * @returns {CumulusCloud} The cloud that was added to the collection.
  248. *
  249. * @performance Calling <code>add</code> is expected constant time. However, the collection's vertex buffer
  250. * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead. For
  251. * best performance, add as many clouds as possible before calling <code>update</code>.
  252. *
  253. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  254. *
  255. *
  256. * @example
  257. * // Example 1: Add a cumulus cloud, specifying all the default values.
  258. * const c = clouds.add({
  259. * show : true,
  260. * position : Cesium.Cartesian3.ZERO,
  261. * scale : new Cesium.Cartesian2(20.0, 12.0),
  262. * maximumSize: new Cesium.Cartesian3(20.0, 12.0, 12.0),
  263. * slice: -1.0,
  264. * cloudType : CloudType.CUMULUS
  265. * });
  266. *
  267. * @example
  268. * // Example 2: Specify only the cloud's cartographic position.
  269. * const c = clouds.add({
  270. * position : Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
  271. * });
  272. *
  273. * @see CloudCollection#remove
  274. * @see CloudCollection#removeAll
  275. */
  276. CloudCollection.prototype.add = function (options) {
  277. options = options ?? Frozen.EMPTY_OBJECT;
  278. const cloudType = options.cloudType ?? CloudType.CUMULUS;
  279. //>>includeStart('debug', pragmas.debug);
  280. if (!CloudType.validate(cloudType)) {
  281. throw new DeveloperError("invalid cloud type");
  282. }
  283. //>>includeEnd('debug');
  284. let cloud;
  285. if (cloudType === CloudType.CUMULUS) {
  286. cloud = new CumulusCloud(options, this);
  287. cloud._index = this._clouds.length;
  288. this._clouds.push(cloud);
  289. this._createVertexArray = true;
  290. }
  291. return cloud;
  292. };
  293. /**
  294. * Removes a cloud from the collection.
  295. *
  296. * @param {CumulusCloud} cloud The cloud to remove.
  297. * @returns {boolean} <code>true</code> if the cloud was removed; <code>false</code> if the cloud was not found in the collection.
  298. *
  299. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  300. *
  301. *
  302. * @example
  303. * const c = clouds.add(...);
  304. * clouds.remove(c); // Returns true
  305. *
  306. * @see CloudCollection#add
  307. * @see CloudCollection#removeAll
  308. * @see CumulusCloud#show
  309. */
  310. CloudCollection.prototype.remove = function (cloud) {
  311. if (this.contains(cloud)) {
  312. this._clouds[cloud._index] = undefined; // Removed later in removeClouds()
  313. this._cloudsRemoved = true;
  314. this._createVertexArray = true;
  315. cloud._destroy();
  316. return true;
  317. }
  318. return false;
  319. };
  320. /**
  321. * Removes all clouds from the collection.
  322. *
  323. * @performance <code>O(n)</code>. It is more efficient to remove all the clouds
  324. * from a collection and then add new ones than to create a new collection entirely.
  325. *
  326. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  327. *
  328. * @example
  329. * clouds.add(...);
  330. * clouds.add(...);
  331. * clouds.removeAll();
  332. *
  333. * @see CloudCollection#add
  334. * @see CloudCollection#remove
  335. */
  336. CloudCollection.prototype.removeAll = function () {
  337. destroyClouds(this._clouds);
  338. this._clouds = [];
  339. this._cloudsToUpdate = [];
  340. this._cloudsToUpdateIndex = 0;
  341. this._cloudsRemoved = false;
  342. this._createVertexArray = true;
  343. };
  344. function removeClouds(cloudCollection) {
  345. if (cloudCollection._cloudsRemoved) {
  346. cloudCollection._cloudsRemoved = false;
  347. const newClouds = [];
  348. const clouds = cloudCollection._clouds;
  349. const length = clouds.length;
  350. for (let i = 0, j = 0; i < length; ++i) {
  351. const cloud = clouds[i];
  352. if (defined(cloud)) {
  353. clouds._index = j++;
  354. newClouds.push(cloud);
  355. }
  356. }
  357. cloudCollection._clouds = newClouds;
  358. }
  359. }
  360. CloudCollection.prototype._updateCloud = function (cloud, propertyChanged) {
  361. if (!cloud._dirty) {
  362. this._cloudsToUpdate[this._cloudsToUpdateIndex++] = cloud;
  363. }
  364. ++this._propertiesChanged[propertyChanged];
  365. };
  366. /**
  367. * Check whether this collection contains a given cloud.
  368. *
  369. * @param {CumulusCloud} [cloud] The cloud to check for.
  370. * @returns {boolean} true if this collection contains the cloud, false otherwise.
  371. *
  372. * @see CloudCollection#get
  373. */
  374. CloudCollection.prototype.contains = function (cloud) {
  375. return defined(cloud) && cloud._cloudCollection === this;
  376. };
  377. /**
  378. * Returns the cloud in the collection at the specified index. Indices are zero-based
  379. * and increase as clouds are added. Removing a cloud shifts all clouds after
  380. * it to the left, changing their indices. This function is commonly used with
  381. * {@link CloudCollection#length} to iterate over all the clouds in the collection.
  382. *
  383. * @param {number} index The zero-based index of the cloud.
  384. * @returns {CumulusCloud} The cloud at the specified index.
  385. *
  386. * @performance Expected constant time. If clouds were removed from the collection and
  387. * {@link CloudCollection#update} was not called, an implicit <code>O(n)</code>
  388. * operation is performed.
  389. *
  390. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  391. *
  392. *
  393. * @example
  394. * // Toggle the show property of every cloud in the collection
  395. * const len = clouds.length;
  396. * for (let i = 0; i < len; ++i) {
  397. * const c = clouds.get(i);
  398. * c.show = !c.show;
  399. * }
  400. *
  401. * @see CloudCollection#length
  402. */
  403. CloudCollection.prototype.get = function (index) {
  404. //>>includeStart('debug', pragmas.debug);
  405. Check.typeOf.number("index", index);
  406. //>>includeEnd('debug');
  407. removeClouds(this);
  408. return this._clouds[index];
  409. };
  410. const texturePositions = new Float32Array([
  411. -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0,
  412. ]);
  413. const textureIndices = new Uint16Array([0, 1, 2, 0, 2, 3]);
  414. function createTextureVA(context) {
  415. const positionBuffer = Buffer.createVertexBuffer({
  416. context: context,
  417. typedArray: texturePositions,
  418. usage: BufferUsage.STATIC_DRAW,
  419. });
  420. const indexBuffer = Buffer.createIndexBuffer({
  421. context: context,
  422. typedArray: textureIndices,
  423. usage: BufferUsage.STATIC_DRAW,
  424. indexDatatype: IndexDatatype.UNSIGNED_SHORT,
  425. });
  426. const attributes = [
  427. {
  428. index: 0,
  429. vertexBuffer: positionBuffer,
  430. componentsPerAttribute: 2,
  431. componentDatatype: ComponentDatatype.FLOAT,
  432. },
  433. ];
  434. return new VertexArray({
  435. context: context,
  436. attributes: attributes,
  437. indexBuffer: indexBuffer,
  438. });
  439. }
  440. let getIndexBuffer;
  441. function getIndexBufferBatched(context) {
  442. const sixteenK = 16 * 1024;
  443. let indexBuffer = context.cache.cloudCollection_indexBufferBatched;
  444. if (defined(indexBuffer)) {
  445. return indexBuffer;
  446. }
  447. // Subtract 6 because the last index is reserved for primitive restart.
  448. // https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.18
  449. const length = sixteenK * 6 - 6;
  450. const indices = new Uint16Array(length);
  451. for (let i = 0, j = 0; i < length; i += 6, j += 4) {
  452. indices[i] = j;
  453. indices[i + 1] = j + 1;
  454. indices[i + 2] = j + 2;
  455. indices[i + 3] = j;
  456. indices[i + 4] = j + 2;
  457. indices[i + 5] = j + 3;
  458. }
  459. indexBuffer = Buffer.createIndexBuffer({
  460. context: context,
  461. typedArray: indices,
  462. usage: BufferUsage.STATIC_DRAW,
  463. indexDatatype: IndexDatatype.UNSIGNED_SHORT,
  464. });
  465. indexBuffer.vertexArrayDestroyable = false;
  466. context.cache.cloudCollection_indexBufferBatched = indexBuffer;
  467. return indexBuffer;
  468. }
  469. function getIndexBufferInstanced(context) {
  470. let indexBuffer = context.cache.cloudCollection_indexBufferInstanced;
  471. if (defined(indexBuffer)) {
  472. return indexBuffer;
  473. }
  474. indexBuffer = Buffer.createIndexBuffer({
  475. context: context,
  476. typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
  477. usage: BufferUsage.STATIC_DRAW,
  478. indexDatatype: IndexDatatype.UNSIGNED_SHORT,
  479. });
  480. indexBuffer.vertexArrayDestroyable = false;
  481. context.cache.cloudCollection_indexBufferInstanced = indexBuffer;
  482. return indexBuffer;
  483. }
  484. function getVertexBufferInstanced(context) {
  485. let vertexBuffer = context.cache.cloudCollection_vertexBufferInstanced;
  486. if (defined(vertexBuffer)) {
  487. return vertexBuffer;
  488. }
  489. vertexBuffer = Buffer.createVertexBuffer({
  490. context: context,
  491. typedArray: new Float32Array([0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]),
  492. usage: BufferUsage.STATIC_DRAW,
  493. });
  494. vertexBuffer.vertexArrayDestroyable = false;
  495. context.cache.cloudCollection_vertexBufferInstanced = vertexBuffer;
  496. return vertexBuffer;
  497. }
  498. function createVAF(context, numberOfClouds, instanced) {
  499. const attributes = [
  500. {
  501. index: attributeLocations.positionHighAndScaleX,
  502. componentsPerAttribute: 4,
  503. componentDatatype: ComponentDatatype.FLOAT,
  504. usage: BufferUsage.STATIC_DRAW,
  505. },
  506. {
  507. index: attributeLocations.positionLowAndScaleY,
  508. componentsPerAttribute: 4,
  509. componentDatatype: ComponentDatatype.FLOAT,
  510. usage: BufferUsage.STATIC_DRAW,
  511. },
  512. {
  513. index: attributeLocations.packedAttribute0,
  514. componentsPerAttribute: 4,
  515. componentDatatype: ComponentDatatype.FLOAT,
  516. usage: BufferUsage.STATIC_DRAW,
  517. },
  518. {
  519. index: attributeLocations.packedAttribute1,
  520. componentsPerAttribute: 4,
  521. componentDatatype: ComponentDatatype.FLOAT,
  522. usage: BufferUsage.STATIC_DRAW,
  523. },
  524. {
  525. index: attributeLocations.color,
  526. componentsPerAttribute: 4,
  527. componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
  528. normalize: true,
  529. usage: BufferUsage.STATIC_DRAW,
  530. },
  531. ];
  532. if (instanced) {
  533. attributes.push({
  534. index: attributeLocations.direction,
  535. componentsPerAttribute: 2,
  536. componentDatatype: ComponentDatatype.FLOAT,
  537. vertexBuffer: getVertexBufferInstanced(context),
  538. });
  539. }
  540. const sizeInVertices = instanced ? numberOfClouds : 4 * numberOfClouds;
  541. return new VertexArrayFacade(context, attributes, sizeInVertices, instanced);
  542. }
  543. const writePositionScratch = new EncodedCartesian3();
  544. function writePositionAndScale(cloudCollection, frameState, vafWriters, cloud) {
  545. let i;
  546. const positionHighWriter =
  547. vafWriters[attributeLocations.positionHighAndScaleX];
  548. const positionLowWriter = vafWriters[attributeLocations.positionLowAndScaleY];
  549. const position = cloud.position;
  550. EncodedCartesian3.fromCartesian(position, writePositionScratch);
  551. const scale = cloud.scale;
  552. const high = writePositionScratch.high;
  553. const low = writePositionScratch.low;
  554. if (cloudCollection._instanced) {
  555. i = cloud._index;
  556. positionHighWriter(i, high.x, high.y, high.z, scale.x);
  557. positionLowWriter(i, low.x, low.y, low.z, scale.y);
  558. } else {
  559. i = cloud._index * 4;
  560. positionHighWriter(i + 0, high.x, high.y, high.z, scale.x);
  561. positionHighWriter(i + 1, high.x, high.y, high.z, scale.x);
  562. positionHighWriter(i + 2, high.x, high.y, high.z, scale.x);
  563. positionHighWriter(i + 3, high.x, high.y, high.z, scale.x);
  564. positionLowWriter(i + 0, low.x, low.y, low.z, scale.y);
  565. positionLowWriter(i + 1, low.x, low.y, low.z, scale.y);
  566. positionLowWriter(i + 2, low.x, low.y, low.z, scale.y);
  567. positionLowWriter(i + 3, low.x, low.y, low.z, scale.y);
  568. }
  569. }
  570. function writePackedAttribute0(cloudCollection, frameState, vafWriters, cloud) {
  571. let i;
  572. const writer = vafWriters[attributeLocations.packedAttribute0];
  573. const show = cloud.show;
  574. const brightness = cloud.brightness;
  575. if (cloudCollection._instanced) {
  576. i = cloud._index;
  577. writer(i, show, brightness, 0.0, 0.0);
  578. } else {
  579. i = cloud._index * 4;
  580. writer(i + 0, show, brightness, 0.0, 0.0);
  581. writer(i + 1, show, brightness, 1.0, 0.0);
  582. writer(i + 2, show, brightness, 1.0, 1.0);
  583. writer(i + 3, show, brightness, 0.0, 1.0);
  584. }
  585. }
  586. function writePackedAttribute1(cloudCollection, frameState, vafWriters, cloud) {
  587. let i;
  588. const writer = vafWriters[attributeLocations.packedAttribute1];
  589. const maximumSize = cloud.maximumSize;
  590. const slice = cloud.slice;
  591. if (cloudCollection._instanced) {
  592. i = cloud._index;
  593. writer(i, maximumSize.x, maximumSize.y, maximumSize.z, slice);
  594. } else {
  595. i = cloud._index * 4;
  596. writer(i + 0, maximumSize.x, maximumSize.y, maximumSize.z, slice);
  597. writer(i + 1, maximumSize.x, maximumSize.y, maximumSize.z, slice);
  598. writer(i + 2, maximumSize.x, maximumSize.y, maximumSize.z, slice);
  599. writer(i + 3, maximumSize.x, maximumSize.y, maximumSize.z, slice);
  600. }
  601. }
  602. function writeColor(cloudCollection, frameState, vafWriters, cloud) {
  603. let i;
  604. const writer = vafWriters[attributeLocations.color];
  605. const color = cloud.color;
  606. const red = Color.floatToByte(color.red);
  607. const green = Color.floatToByte(color.green);
  608. const blue = Color.floatToByte(color.blue);
  609. const alpha = Color.floatToByte(color.alpha);
  610. if (cloudCollection._instanced) {
  611. i = cloud._index;
  612. writer(i, red, green, blue, alpha);
  613. } else {
  614. i = cloud._index * 4;
  615. writer(i + 0, red, green, blue, alpha);
  616. writer(i + 1, red, green, blue, alpha);
  617. writer(i + 2, red, green, blue, alpha);
  618. writer(i + 3, red, green, blue, alpha);
  619. }
  620. }
  621. function writeCloud(cloudCollection, frameState, vafWriters, cloud) {
  622. writePositionAndScale(cloudCollection, frameState, vafWriters, cloud);
  623. writePackedAttribute0(cloudCollection, frameState, vafWriters, cloud);
  624. writePackedAttribute1(cloudCollection, frameState, vafWriters, cloud);
  625. writeColor(cloudCollection, frameState, vafWriters, cloud);
  626. }
  627. function createNoiseTexture(cloudCollection, frameState, vsSource, fsSource) {
  628. const that = cloudCollection;
  629. const textureSliceWidth = that._textureSliceWidth;
  630. const noiseTextureRows = that._noiseTextureRows;
  631. //>>includeStart('debug', pragmas.debug);
  632. if (
  633. textureSliceWidth / noiseTextureRows < 1 ||
  634. textureSliceWidth % noiseTextureRows !== 0
  635. ) {
  636. throw new DeveloperError(
  637. "noiseTextureRows must evenly divide textureSliceWidth",
  638. );
  639. }
  640. //>>includeEnd('debug');
  641. const context = frameState.context;
  642. that._vaNoise = createTextureVA(context);
  643. that._spNoise = ShaderProgram.fromCache({
  644. context: context,
  645. vertexShaderSource: vsSource,
  646. fragmentShaderSource: fsSource,
  647. attributeLocations: {
  648. position: 0,
  649. },
  650. });
  651. const noiseDetail = that.noiseDetail;
  652. const noiseOffset = that.noiseOffset;
  653. that._noiseTexture = new Texture({
  654. context: context,
  655. width: (textureSliceWidth * textureSliceWidth) / noiseTextureRows,
  656. height: textureSliceWidth * noiseTextureRows,
  657. pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
  658. pixelFormat: PixelFormat.RGBA,
  659. sampler: new Sampler({
  660. wrapS: TextureWrap.REPEAT,
  661. wrapT: TextureWrap.REPEAT,
  662. minificationFilter: TextureMinificationFilter.NEAREST,
  663. magnificationFilter: TextureMagnificationFilter.NEAREST,
  664. }),
  665. });
  666. const textureCommand = new ComputeCommand({
  667. vertexArray: that._vaNoise,
  668. shaderProgram: that._spNoise,
  669. outputTexture: that._noiseTexture,
  670. uniformMap: {
  671. u_noiseTextureDimensions: getNoiseTextureDimensions(that),
  672. u_noiseDetail: function () {
  673. return noiseDetail;
  674. },
  675. u_noiseOffset: function () {
  676. return noiseOffset;
  677. },
  678. },
  679. persists: false,
  680. owner: cloudCollection,
  681. postExecute: function (texture) {
  682. that._ready = true;
  683. that._loading = false;
  684. },
  685. });
  686. frameState.commandList.push(textureCommand);
  687. that._loading = true;
  688. }
  689. function createVertexArray(cloudCollection, frameState) {
  690. const that = cloudCollection;
  691. const context = frameState.context;
  692. that._createVertexArray = false;
  693. that._vaf = that._vaf && that._vaf.destroy();
  694. const clouds = cloudCollection._clouds;
  695. const cloudsLength = clouds.length;
  696. if (cloudsLength > 0) {
  697. that._vaf = createVAF(context, cloudsLength, that._instanced);
  698. const vafWriters = that._vaf.writers;
  699. let i;
  700. // Rewrite entire buffer if clouds were added or removed.
  701. for (i = 0; i < cloudsLength; ++i) {
  702. const cloud = clouds[i];
  703. writeCloud(cloudCollection, frameState, vafWriters, cloud);
  704. }
  705. // Different cloud collections share the same index buffer.
  706. that._vaf.commit(getIndexBuffer(context));
  707. }
  708. }
  709. const scratchWriterArray = [];
  710. function updateClouds(cloudCollection, frameState) {
  711. const context = frameState.context;
  712. const that = cloudCollection;
  713. const clouds = that._clouds;
  714. const cloudsLength = clouds.length;
  715. const cloudsToUpdate = that._cloudsToUpdate;
  716. const cloudsToUpdateLength = that._cloudsToUpdateIndex;
  717. const properties = that._propertiesChanged;
  718. const writers = scratchWriterArray;
  719. writers.length = 0;
  720. if (properties[POSITION_INDEX] || properties[SCALE_INDEX]) {
  721. writers.push(writePositionAndScale);
  722. }
  723. if (properties[SHOW_INDEX] || properties[BRIGHTNESS_INDEX]) {
  724. writers.push(writePackedAttribute0);
  725. }
  726. if (properties[MAXIMUM_SIZE_INDEX] || properties[SLICE_INDEX]) {
  727. writers.push(writePackedAttribute1);
  728. }
  729. if (properties[COLOR_INDEX]) {
  730. writers.push(writeColor);
  731. }
  732. const numWriters = writers.length;
  733. const vafWriters = that._vaf.writers;
  734. let i, c, w;
  735. if (cloudsToUpdateLength / cloudsLength > 0.1) {
  736. // Like BillboardCollection, if more than 10% of clouds change,
  737. // rewrite the entire buffer.
  738. for (i = 0; i < cloudsToUpdateLength; ++i) {
  739. c = cloudsToUpdate[i];
  740. c._dirty = false;
  741. for (w = 0; w < numWriters; ++w) {
  742. writers[w](cloudCollection, frameState, vafWriters, c);
  743. }
  744. }
  745. that._vaf.commit(getIndexBuffer(context));
  746. } else {
  747. for (i = 0; i < cloudsToUpdateLength; ++i) {
  748. c = cloudsToUpdate[i];
  749. c._dirty = false;
  750. for (w = 0; w < numWriters; ++w) {
  751. writers[w](cloudCollection, frameState, vafWriters, c);
  752. }
  753. if (that._instanced) {
  754. that._vaf.subCommit(c._index, 1);
  755. } else {
  756. that._vaf.subCommit(c._index * 4, 4);
  757. }
  758. }
  759. that._vaf.endSubCommits();
  760. }
  761. that._cloudsToUpdateIndex = 0;
  762. }
  763. function createShaderProgram(cloudCollection, frameState, vsSource, fsSource) {
  764. const context = frameState.context;
  765. const that = cloudCollection;
  766. const vs = new ShaderSource({
  767. defines: [],
  768. sources: [vsSource],
  769. });
  770. if (that._instanced) {
  771. vs.defines.push("INSTANCED");
  772. }
  773. const fs = new ShaderSource({
  774. defines: [],
  775. sources: [fsSource],
  776. });
  777. if (that.debugBillboards) {
  778. fs.defines.push("DEBUG_BILLBOARDS");
  779. }
  780. if (that.debugEllipsoids) {
  781. fs.defines.push("DEBUG_ELLIPSOIDS");
  782. }
  783. that._sp = ShaderProgram.replaceCache({
  784. context: context,
  785. shaderProgram: that._sp,
  786. vertexShaderSource: vs,
  787. fragmentShaderSource: fs,
  788. attributeLocations: attributeLocations,
  789. });
  790. that._rs = RenderState.fromCache({
  791. depthTest: {
  792. enabled: true,
  793. func: WebGLConstants.LESS,
  794. },
  795. depthMask: false,
  796. blending: BlendingState.ALPHA_BLEND,
  797. });
  798. that._spCreated = true;
  799. that._compiledDebugBillboards = that.debugBillboards;
  800. that._compiledDebugEllipsoids = that.debugEllipsoids;
  801. }
  802. function createDrawCommands(cloudCollection, frameState) {
  803. const that = cloudCollection;
  804. const pass = frameState.passes;
  805. const uniforms = that._uniforms;
  806. const commandList = frameState.commandList;
  807. if (pass.render) {
  808. const colorList = that._colorCommands;
  809. const va = that._vaf.va;
  810. const vaLength = va.length;
  811. colorList.length = vaLength;
  812. for (let i = 0; i < vaLength; i++) {
  813. let command = colorList[i];
  814. if (!defined(command)) {
  815. command = colorList[i] = new DrawCommand();
  816. }
  817. command.pass = Pass.TRANSLUCENT;
  818. command.owner = cloudCollection;
  819. command.uniformMap = uniforms;
  820. command.count = va[i].indicesCount;
  821. command.vertexArray = va[i].va;
  822. command.shaderProgram = that._sp;
  823. command.renderState = that._rs;
  824. if (that._instanced) {
  825. command.count = 6;
  826. command.instanceCount = that._clouds.length;
  827. }
  828. commandList.push(command);
  829. }
  830. }
  831. }
  832. /**
  833. * @private
  834. */
  835. CloudCollection.prototype.update = function (frameState) {
  836. removeClouds(this);
  837. if (!this.show) {
  838. return;
  839. }
  840. const debugging = this.debugBillboards || this.debugEllipsoids;
  841. this._ready = debugging ? true : defined(this._noiseTexture);
  842. if (!this._ready && !this._loading && !debugging) {
  843. createNoiseTexture(this, frameState, CloudNoiseVS, CloudNoiseFS);
  844. }
  845. this._instanced = frameState.context.instancedArrays;
  846. attributeLocations = this._instanced
  847. ? attributeLocationsInstanced
  848. : attributeLocationsBatched;
  849. getIndexBuffer = this._instanced
  850. ? getIndexBufferInstanced
  851. : getIndexBufferBatched;
  852. const clouds = this._clouds;
  853. const cloudsLength = clouds.length;
  854. const cloudsToUpdate = this._cloudsToUpdate;
  855. const cloudsToUpdateLength = this._cloudsToUpdateIndex;
  856. if (this._createVertexArray) {
  857. createVertexArray(this, frameState);
  858. } else if (cloudsToUpdateLength > 0) {
  859. // Clouds were modified, but none were added or removed.
  860. updateClouds(this, frameState);
  861. }
  862. // If the number of total clouds ever shrinks considerably,
  863. // truncate cloudsToUpdate so that we free memory that
  864. // we are no longer using.
  865. if (cloudsToUpdateLength > cloudsLength * 1.5) {
  866. cloudsToUpdate.length = cloudsLength;
  867. }
  868. if (
  869. !defined(this._vaf) ||
  870. !defined(this._vaf.va) ||
  871. !this._ready & !debugging
  872. ) {
  873. return;
  874. }
  875. if (
  876. !this._spCreated ||
  877. this.debugBillboards !== this._compiledDebugBillboards ||
  878. this.debugEllipsoids !== this._compiledDebugEllipsoids
  879. ) {
  880. createShaderProgram(this, frameState, CloudCollectionVS, CloudCollectionFS);
  881. }
  882. createDrawCommands(this, frameState);
  883. };
  884. /**
  885. * Returns true if this object was destroyed; otherwise, false.
  886. * <br /><br />
  887. * If this object was destroyed, it should not be used; calling any function other than
  888. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  889. *
  890. * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  891. *
  892. * @see CloudCollection#destroy
  893. */
  894. CloudCollection.prototype.isDestroyed = function () {
  895. return false;
  896. };
  897. /**
  898. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  899. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  900. * <br /><br />
  901. * Once an object is destroyed, it should not be used; calling any function other than
  902. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  903. * assign the return value (<code>undefined</code>) to the object as done in the example.
  904. *
  905. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  906. *
  907. *
  908. * @example
  909. * clouds = clouds && clouds.destroy();
  910. *
  911. * @see CloudCollection#isDestroyed
  912. */
  913. CloudCollection.prototype.destroy = function () {
  914. this._noiseTexture = this._noiseTexture && this._noiseTexture.destroy();
  915. this._sp = this._sp && this._sp.destroy();
  916. this._vaf = this._vaf && this._vaf.destroy();
  917. destroyClouds(this._clouds);
  918. return destroyObject(this);
  919. };
  920. export default CloudCollection;