GroundPrimitive.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. import ApproximateTerrainHeights from '../Core/ApproximateTerrainHeights.js';
  2. import BoundingSphere from '../Core/BoundingSphere.js';
  3. import Cartesian3 from '../Core/Cartesian3.js';
  4. import Cartographic from '../Core/Cartographic.js';
  5. import Check from '../Core/Check.js';
  6. import defaultValue from '../Core/defaultValue.js';
  7. import defined from '../Core/defined.js';
  8. import defineProperties from '../Core/defineProperties.js';
  9. import destroyObject from '../Core/destroyObject.js';
  10. import DeveloperError from '../Core/DeveloperError.js';
  11. import GeometryInstance from '../Core/GeometryInstance.js';
  12. import isArray from '../Core/isArray.js';
  13. import CesiumMath from '../Core/Math.js';
  14. import OrientedBoundingBox from '../Core/OrientedBoundingBox.js';
  15. import Rectangle from '../Core/Rectangle.js';
  16. import when from '../ThirdParty/when.js';
  17. import ClassificationPrimitive from './ClassificationPrimitive.js';
  18. import ClassificationType from './ClassificationType.js';
  19. import PerInstanceColorAppearance from './PerInstanceColorAppearance.js';
  20. import SceneMode from './SceneMode.js';
  21. import ShadowVolumeAppearance from './ShadowVolumeAppearance.js';
  22. var GroundPrimitiveUniformMap = {
  23. u_globeMinimumAltitude: function() {
  24. return 55000.0;
  25. }
  26. };
  27. /**
  28. * A ground primitive represents geometry draped over terrain or 3D Tiles in the {@link Scene}.
  29. * <p>
  30. * A primitive combines geometry instances with an {@link Appearance} that describes the full shading, including
  31. * {@link Material} and {@link RenderState}. Roughly, the geometry instance defines the structure and placement,
  32. * and the appearance defines the visual characteristics. Decoupling geometry and appearance allows us to mix
  33. * and match most of them and add a new geometry or appearance independently of each other.
  34. * </p>
  35. * <p>
  36. * Support for the WEBGL_depth_texture extension is required to use GeometryInstances with different PerInstanceColors
  37. * or materials besides PerInstanceColorAppearance.
  38. * </p>
  39. * <p>
  40. * Textured GroundPrimitives were designed for notional patterns and are not meant for precisely mapping
  41. * textures to terrain - for that use case, use {@link SingleTileImageryProvider}.
  42. * </p>
  43. * <p>
  44. * For correct rendering, this feature requires the EXT_frag_depth WebGL extension. For hardware that do not support this extension, there
  45. * will be rendering artifacts for some viewing angles.
  46. * </p>
  47. * <p>
  48. * Valid geometries are {@link CircleGeometry}, {@link CorridorGeometry}, {@link EllipseGeometry}, {@link PolygonGeometry}, and {@link RectangleGeometry}.
  49. * </p>
  50. *
  51. * @alias GroundPrimitive
  52. * @constructor
  53. *
  54. * @param {Object} [options] Object with the following properties:
  55. * @param {Array|GeometryInstance} [options.geometryInstances] The geometry instances to render.
  56. * @param {Appearance} [options.appearance] The appearance used to render the primitive. Defaults to a flat PerInstanceColorAppearance when GeometryInstances have a color attribute.
  57. * @param {Boolean} [options.show=true] Determines if this primitive will be shown.
  58. * @param {Boolean} [options.vertexCacheOptimize=false] When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
  59. * @param {Boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
  60. * @param {Boolean} [options.compressVertices=true] When <code>true</code>, the geometry vertices are compressed, which will save memory.
  61. * @param {Boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
  62. * @param {Boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}. When <code>false</code>, GPU memory is saved.
  63. * @param {Boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready. If false initializeTerrainHeights() must be called first.
  64. * @param {ClassificationType} [options.classificationType=ClassificationType.BOTH] Determines whether terrain, 3D Tiles or both will be classified.
  65. * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
  66. * @param {Boolean} [options.debugShowShadowVolume=false] For debugging only. Determines if the shadow volume for each geometry in the primitive is drawn. Must be <code>true</code> on
  67. * creation for the volumes to be created before the geometry is released or options.releaseGeometryInstance must be <code>false</code>.
  68. *
  69. * @example
  70. * // Example 1: Create primitive with a single instance
  71. * var rectangleInstance = new Cesium.GeometryInstance({
  72. * geometry : new Cesium.RectangleGeometry({
  73. * rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0)
  74. * }),
  75. * id : 'rectangle',
  76. * attributes : {
  77. * color : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
  78. * }
  79. * });
  80. * scene.primitives.add(new Cesium.GroundPrimitive({
  81. * geometryInstances : rectangleInstance
  82. * }));
  83. *
  84. * // Example 2: Batch instances
  85. * var color = new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5); // Both instances must have the same color.
  86. * var rectangleInstance = new Cesium.GeometryInstance({
  87. * geometry : new Cesium.RectangleGeometry({
  88. * rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0)
  89. * }),
  90. * id : 'rectangle',
  91. * attributes : {
  92. * color : color
  93. * }
  94. * });
  95. * var ellipseInstance = new Cesium.GeometryInstance({
  96. * geometry : new Cesium.EllipseGeometry({
  97. * center : Cesium.Cartesian3.fromDegrees(-105.0, 40.0),
  98. * semiMinorAxis : 300000.0,
  99. * semiMajorAxis : 400000.0
  100. * }),
  101. * id : 'ellipse',
  102. * attributes : {
  103. * color : color
  104. * }
  105. * });
  106. * scene.primitives.add(new Cesium.GroundPrimitive({
  107. * geometryInstances : [rectangleInstance, ellipseInstance]
  108. * }));
  109. *
  110. * @see Primitive
  111. * @see ClassificationPrimitive
  112. * @see GeometryInstance
  113. * @see Appearance
  114. */
  115. function GroundPrimitive(options) {
  116. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  117. var appearance = options.appearance;
  118. var geometryInstances = options.geometryInstances;
  119. if (!defined(appearance) && defined(geometryInstances)) {
  120. var geometryInstancesArray = isArray(geometryInstances) ? geometryInstances : [geometryInstances];
  121. var geometryInstanceCount = geometryInstancesArray.length;
  122. for (var i = 0; i < geometryInstanceCount; i++) {
  123. var attributes = geometryInstancesArray[i].attributes;
  124. if (defined(attributes) && defined(attributes.color)) {
  125. appearance = new PerInstanceColorAppearance({
  126. flat : true
  127. });
  128. break;
  129. }
  130. }
  131. }
  132. /**
  133. * The {@link Appearance} used to shade this primitive. Each geometry
  134. * instance is shaded with the same appearance. Some appearances, like
  135. * {@link PerInstanceColorAppearance} allow giving each instance unique
  136. * properties.
  137. *
  138. * @type Appearance
  139. *
  140. * @default undefined
  141. */
  142. this.appearance = appearance;
  143. /**
  144. * The geometry instances rendered with this primitive. This may
  145. * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
  146. * is <code>true</code> when the primitive is constructed.
  147. * <p>
  148. * Changing this property after the primitive is rendered has no effect.
  149. * </p>
  150. *
  151. * @readonly
  152. * @type {Array|GeometryInstance}
  153. *
  154. * @default undefined
  155. */
  156. this.geometryInstances = options.geometryInstances;
  157. /**
  158. * Determines if the primitive will be shown. This affects all geometry
  159. * instances in the primitive.
  160. *
  161. * @type {Boolean}
  162. *
  163. * @default true
  164. */
  165. this.show = defaultValue(options.show, true);
  166. /**
  167. * Determines whether terrain, 3D Tiles or both will be classified.
  168. *
  169. * @type {ClassificationType}
  170. *
  171. * @default ClassificationType.BOTH
  172. */
  173. this.classificationType = defaultValue(options.classificationType, ClassificationType.BOTH);
  174. /**
  175. * This property is for debugging only; it is not for production use nor is it optimized.
  176. * <p>
  177. * Draws the bounding sphere for each draw command in the primitive.
  178. * </p>
  179. *
  180. * @type {Boolean}
  181. *
  182. * @default false
  183. */
  184. this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false);
  185. /**
  186. * This property is for debugging only; it is not for production use nor is it optimized.
  187. * <p>
  188. * Draws the shadow volume for each geometry in the primitive.
  189. * </p>
  190. *
  191. * @type {Boolean}
  192. *
  193. * @default false
  194. */
  195. this.debugShowShadowVolume = defaultValue(options.debugShowShadowVolume, false);
  196. this._boundingVolumes = [];
  197. this._boundingVolumes2D = [];
  198. this._ready = false;
  199. this._readyPromise = when.defer();
  200. this._primitive = undefined;
  201. this._maxHeight = undefined;
  202. this._minHeight = undefined;
  203. this._maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
  204. this._minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
  205. this._boundingSpheresKeys = [];
  206. this._boundingSpheres = [];
  207. this._useFragmentCulling = false;
  208. // Used when inserting in an OrderedPrimitiveCollection
  209. this._zIndex = undefined;
  210. var that = this;
  211. this._classificationPrimitiveOptions = {
  212. geometryInstances : undefined,
  213. appearance : undefined,
  214. vertexCacheOptimize : defaultValue(options.vertexCacheOptimize, false),
  215. interleave : defaultValue(options.interleave, false),
  216. releaseGeometryInstances : defaultValue(options.releaseGeometryInstances, true),
  217. allowPicking : defaultValue(options.allowPicking, true),
  218. asynchronous : defaultValue(options.asynchronous, true),
  219. compressVertices : defaultValue(options.compressVertices, true),
  220. _createBoundingVolumeFunction : undefined,
  221. _updateAndQueueCommandsFunction : undefined,
  222. _pickPrimitive : that,
  223. _extruded : true,
  224. _uniformMap : GroundPrimitiveUniformMap
  225. };
  226. }
  227. defineProperties(GroundPrimitive.prototype, {
  228. /**
  229. * When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
  230. *
  231. * @memberof GroundPrimitive.prototype
  232. *
  233. * @type {Boolean}
  234. * @readonly
  235. *
  236. * @default true
  237. */
  238. vertexCacheOptimize : {
  239. get : function() {
  240. return this._classificationPrimitiveOptions.vertexCacheOptimize;
  241. }
  242. },
  243. /**
  244. * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
  245. *
  246. * @memberof GroundPrimitive.prototype
  247. *
  248. * @type {Boolean}
  249. * @readonly
  250. *
  251. * @default false
  252. */
  253. interleave : {
  254. get : function() {
  255. return this._classificationPrimitiveOptions.interleave;
  256. }
  257. },
  258. /**
  259. * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
  260. *
  261. * @memberof GroundPrimitive.prototype
  262. *
  263. * @type {Boolean}
  264. * @readonly
  265. *
  266. * @default true
  267. */
  268. releaseGeometryInstances : {
  269. get : function() {
  270. return this._classificationPrimitiveOptions.releaseGeometryInstances;
  271. }
  272. },
  273. /**
  274. * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}. When <code>false</code>, GPU memory is saved.
  275. *
  276. * @memberof GroundPrimitive.prototype
  277. *
  278. * @type {Boolean}
  279. * @readonly
  280. *
  281. * @default true
  282. */
  283. allowPicking : {
  284. get : function() {
  285. return this._classificationPrimitiveOptions.allowPicking;
  286. }
  287. },
  288. /**
  289. * Determines if the geometry instances will be created and batched on a web worker.
  290. *
  291. * @memberof GroundPrimitive.prototype
  292. *
  293. * @type {Boolean}
  294. * @readonly
  295. *
  296. * @default true
  297. */
  298. asynchronous : {
  299. get : function() {
  300. return this._classificationPrimitiveOptions.asynchronous;
  301. }
  302. },
  303. /**
  304. * When <code>true</code>, geometry vertices are compressed, which will save memory.
  305. *
  306. * @memberof GroundPrimitive.prototype
  307. *
  308. * @type {Boolean}
  309. * @readonly
  310. *
  311. * @default true
  312. */
  313. compressVertices : {
  314. get : function() {
  315. return this._classificationPrimitiveOptions.compressVertices;
  316. }
  317. },
  318. /**
  319. * Determines if the primitive is complete and ready to render. If this property is
  320. * true, the primitive will be rendered the next time that {@link GroundPrimitive#update}
  321. * is called.
  322. *
  323. * @memberof GroundPrimitive.prototype
  324. *
  325. * @type {Boolean}
  326. * @readonly
  327. */
  328. ready : {
  329. get : function() {
  330. return this._ready;
  331. }
  332. },
  333. /**
  334. * Gets a promise that resolves when the primitive is ready to render.
  335. * @memberof GroundPrimitive.prototype
  336. * @type {Promise.<GroundPrimitive>}
  337. * @readonly
  338. */
  339. readyPromise : {
  340. get : function() {
  341. return this._readyPromise.promise;
  342. }
  343. }
  344. });
  345. /**
  346. * Determines if GroundPrimitive rendering is supported.
  347. *
  348. * @function
  349. * @param {Scene} scene The scene.
  350. * @returns {Boolean} <code>true</code> if GroundPrimitives are supported; otherwise, returns <code>false</code>
  351. */
  352. GroundPrimitive.isSupported = ClassificationPrimitive.isSupported;
  353. function getComputeMaximumHeightFunction(primitive) {
  354. return function(granularity, ellipsoid) {
  355. var r = ellipsoid.maximumRadius;
  356. var delta = (r / Math.cos(granularity * 0.5)) - r;
  357. return primitive._maxHeight + delta;
  358. };
  359. }
  360. function getComputeMinimumHeightFunction(primitive) {
  361. return function(granularity, ellipsoid) {
  362. return primitive._minHeight;
  363. };
  364. }
  365. var scratchBVCartesianHigh = new Cartesian3();
  366. var scratchBVCartesianLow = new Cartesian3();
  367. var scratchBVCartesian = new Cartesian3();
  368. var scratchBVCartographic = new Cartographic();
  369. var scratchBVRectangle = new Rectangle();
  370. function getRectangle(frameState, geometry) {
  371. var ellipsoid = frameState.mapProjection.ellipsoid;
  372. if (!defined(geometry.attributes) || !defined(geometry.attributes.position3DHigh)) {
  373. if (defined(geometry.rectangle)) {
  374. return geometry.rectangle;
  375. }
  376. return undefined;
  377. }
  378. var highPositions = geometry.attributes.position3DHigh.values;
  379. var lowPositions = geometry.attributes.position3DLow.values;
  380. var length = highPositions.length;
  381. var minLat = Number.POSITIVE_INFINITY;
  382. var minLon = Number.POSITIVE_INFINITY;
  383. var maxLat = Number.NEGATIVE_INFINITY;
  384. var maxLon = Number.NEGATIVE_INFINITY;
  385. for (var i = 0; i < length; i +=3) {
  386. var highPosition = Cartesian3.unpack(highPositions, i, scratchBVCartesianHigh);
  387. var lowPosition = Cartesian3.unpack(lowPositions, i, scratchBVCartesianLow);
  388. var position = Cartesian3.add(highPosition, lowPosition, scratchBVCartesian);
  389. var cartographic = ellipsoid.cartesianToCartographic(position, scratchBVCartographic);
  390. var latitude = cartographic.latitude;
  391. var longitude = cartographic.longitude;
  392. minLat = Math.min(minLat, latitude);
  393. minLon = Math.min(minLon, longitude);
  394. maxLat = Math.max(maxLat, latitude);
  395. maxLon = Math.max(maxLon, longitude);
  396. }
  397. var rectangle = scratchBVRectangle;
  398. rectangle.north = maxLat;
  399. rectangle.south = minLat;
  400. rectangle.east = maxLon;
  401. rectangle.west = minLon;
  402. return rectangle;
  403. }
  404. function setMinMaxTerrainHeights(primitive, rectangle, ellipsoid) {
  405. var result = ApproximateTerrainHeights.getMinimumMaximumHeights(rectangle, ellipsoid);
  406. primitive._minTerrainHeight = result.minimumTerrainHeight;
  407. primitive._maxTerrainHeight = result.maximumTerrainHeight;
  408. }
  409. function createBoundingVolume(groundPrimitive, frameState, geometry) {
  410. var ellipsoid = frameState.mapProjection.ellipsoid;
  411. var rectangle = getRectangle(frameState, geometry);
  412. // Use an oriented bounding box by default, but switch to a bounding sphere if bounding box creation would fail.
  413. if (rectangle.width < CesiumMath.PI) {
  414. var obb = OrientedBoundingBox.fromRectangle(rectangle, groundPrimitive._maxHeight, groundPrimitive._minHeight, ellipsoid);
  415. groundPrimitive._boundingVolumes.push(obb);
  416. } else {
  417. var highPositions = geometry.attributes.position3DHigh.values;
  418. var lowPositions = geometry.attributes.position3DLow.values;
  419. groundPrimitive._boundingVolumes.push(BoundingSphere.fromEncodedCartesianVertices(highPositions, lowPositions));
  420. }
  421. if (!frameState.scene3DOnly) {
  422. var projection = frameState.mapProjection;
  423. var boundingVolume = BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, groundPrimitive._maxHeight, groundPrimitive._minHeight);
  424. Cartesian3.fromElements(boundingVolume.center.z, boundingVolume.center.x, boundingVolume.center.y, boundingVolume.center);
  425. groundPrimitive._boundingVolumes2D.push(boundingVolume);
  426. }
  427. }
  428. function boundingVolumeIndex(commandIndex, length) {
  429. return Math.floor((commandIndex % length) / 3);
  430. }
  431. function updateAndQueueRenderCommand(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume) {
  432. // Use derived appearance command for 2D if needed
  433. var classificationPrimitive = groundPrimitive._primitive;
  434. if (frameState.mode !== SceneMode.SCENE3D &&
  435. command.shaderProgram === classificationPrimitive._spColor &&
  436. classificationPrimitive._needs2DShader) {
  437. command = command.derivedCommands.appearance2D;
  438. }
  439. command.owner = groundPrimitive;
  440. command.modelMatrix = modelMatrix;
  441. command.boundingVolume = boundingVolume;
  442. command.cull = cull;
  443. command.debugShowBoundingVolume = debugShowBoundingVolume;
  444. frameState.commandList.push(command);
  445. }
  446. function updateAndQueuePickCommand(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume) {
  447. // Use derived pick command for 2D if needed
  448. var classificationPrimitive = groundPrimitive._primitive;
  449. if (frameState.mode !== SceneMode.SCENE3D &&
  450. command.shaderProgram === classificationPrimitive._spPick &&
  451. classificationPrimitive._needs2DShader) {
  452. command = command.derivedCommands.pick2D;
  453. }
  454. command.owner = groundPrimitive;
  455. command.modelMatrix = modelMatrix;
  456. command.boundingVolume = boundingVolume;
  457. command.cull = cull;
  458. frameState.commandList.push(command);
  459. }
  460. function updateAndQueueCommands(groundPrimitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume, twoPasses) {
  461. var boundingVolumes;
  462. if (frameState.mode === SceneMode.SCENE3D) {
  463. boundingVolumes = groundPrimitive._boundingVolumes;
  464. } else {
  465. boundingVolumes = groundPrimitive._boundingVolumes2D;
  466. }
  467. var classificationType = groundPrimitive.classificationType;
  468. var queueTerrainCommands = (classificationType !== ClassificationType.CESIUM_3D_TILE);
  469. var queue3DTilesCommands = (classificationType !== ClassificationType.TERRAIN);
  470. var passes = frameState.passes;
  471. var classificationPrimitive = groundPrimitive._primitive;
  472. var i;
  473. var boundingVolume;
  474. var command;
  475. if (passes.render) {
  476. var colorLength = colorCommands.length;
  477. for (i = 0; i < colorLength; ++i) {
  478. boundingVolume = boundingVolumes[boundingVolumeIndex(i, colorLength)];
  479. if (queueTerrainCommands) {
  480. command = colorCommands[i];
  481. updateAndQueueRenderCommand(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume);
  482. }
  483. if (queue3DTilesCommands) {
  484. command = colorCommands[i].derivedCommands.tileset;
  485. updateAndQueueRenderCommand(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume);
  486. }
  487. }
  488. if (frameState.invertClassification) {
  489. var ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
  490. var ignoreShowCommandsLength = ignoreShowCommands.length;
  491. for (i = 0; i < ignoreShowCommandsLength; ++i) {
  492. boundingVolume = boundingVolumes[Math.floor(i / 2)];
  493. command = ignoreShowCommands[i];
  494. updateAndQueueRenderCommand(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume);
  495. }
  496. }
  497. }
  498. if (passes.pick) {
  499. var pickLength = pickCommands.length;
  500. var pickOffsets;
  501. if (!groundPrimitive._useFragmentCulling) {
  502. // Must be using pick offsets
  503. pickOffsets = classificationPrimitive._primitive._pickOffsets;
  504. }
  505. for (i = 0; i < pickLength; ++i) {
  506. boundingVolume = boundingVolumes[boundingVolumeIndex(i, pickLength)];
  507. if (!groundPrimitive._useFragmentCulling) {
  508. var pickOffset = pickOffsets[boundingVolumeIndex(i, pickLength)];
  509. boundingVolume = boundingVolumes[pickOffset.index];
  510. }
  511. if (queueTerrainCommands) {
  512. command = pickCommands[i];
  513. updateAndQueuePickCommand(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume);
  514. }
  515. if (queue3DTilesCommands) {
  516. command = pickCommands[i].derivedCommands.tileset;
  517. updateAndQueuePickCommand(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume);
  518. }
  519. }
  520. }
  521. }
  522. /**
  523. * Initializes the minimum and maximum terrain heights. This only needs to be called if you are creating the
  524. * GroundPrimitive synchronously.
  525. *
  526. * @returns {Promise} A promise that will resolve once the terrain heights have been loaded.
  527. *
  528. */
  529. GroundPrimitive.initializeTerrainHeights = function() {
  530. return ApproximateTerrainHeights.initialize();
  531. };
  532. /**
  533. * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
  534. * get the draw commands needed to render this primitive.
  535. * <p>
  536. * Do not call this function directly. This is documented just to
  537. * list the exceptions that may be propagated when the scene is rendered:
  538. * </p>
  539. *
  540. * @exception {DeveloperError} For synchronous GroundPrimitive, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve.
  541. * @exception {DeveloperError} All instance geometries must have the same primitiveType.
  542. * @exception {DeveloperError} Appearance and material have a uniform with the same name.
  543. */
  544. GroundPrimitive.prototype.update = function(frameState) {
  545. if (!defined(this._primitive) && !defined(this.geometryInstances)) {
  546. return;
  547. }
  548. if (!ApproximateTerrainHeights.initialized) {
  549. //>>includeStart('debug', pragmas.debug);
  550. if (!this.asynchronous) {
  551. throw new DeveloperError('For synchronous GroundPrimitives, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve.');
  552. }
  553. //>>includeEnd('debug');
  554. GroundPrimitive.initializeTerrainHeights();
  555. return;
  556. }
  557. var that = this;
  558. var primitiveOptions = this._classificationPrimitiveOptions;
  559. if (!defined(this._primitive)) {
  560. var ellipsoid = frameState.mapProjection.ellipsoid;
  561. var instance;
  562. var geometry;
  563. var instanceType;
  564. var instances = isArray(this.geometryInstances) ? this.geometryInstances : [this.geometryInstances];
  565. var length = instances.length;
  566. var groundInstances = new Array(length);
  567. var i;
  568. var rectangle;
  569. for (i = 0; i < length; ++i) {
  570. instance = instances[i];
  571. geometry = instance.geometry;
  572. var instanceRectangle = getRectangle(frameState, geometry);
  573. if (!defined(rectangle)) {
  574. rectangle = Rectangle.clone(instanceRectangle);
  575. } else if (defined(instanceRectangle)) {
  576. Rectangle.union(rectangle, instanceRectangle, rectangle);
  577. }
  578. var id = instance.id;
  579. if (defined(id) && defined(instanceRectangle)) {
  580. var boundingSphere = ApproximateTerrainHeights.getBoundingSphere(instanceRectangle, ellipsoid);
  581. this._boundingSpheresKeys.push(id);
  582. this._boundingSpheres.push(boundingSphere);
  583. }
  584. instanceType = geometry.constructor;
  585. if (!defined(instanceType) || !defined(instanceType.createShadowVolume)) {
  586. //>>includeStart('debug', pragmas.debug);
  587. throw new DeveloperError('Not all of the geometry instances have GroundPrimitive support.');
  588. //>>includeEnd('debug');
  589. }
  590. }
  591. // Now compute the min/max heights for the primitive
  592. setMinMaxTerrainHeights(this, rectangle, ellipsoid);
  593. var exaggeration = frameState.terrainExaggeration;
  594. this._minHeight = this._minTerrainHeight * exaggeration;
  595. this._maxHeight = this._maxTerrainHeight * exaggeration;
  596. var useFragmentCulling = GroundPrimitive._supportsMaterials(frameState.context);
  597. this._useFragmentCulling = useFragmentCulling;
  598. if (useFragmentCulling) {
  599. // Determine whether to add spherical or planar extent attributes for computing texture coordinates.
  600. // This depends on the size of the GeometryInstances.
  601. var attributes;
  602. var usePlanarExtents = true;
  603. for (i = 0; i < length; ++i) {
  604. instance = instances[i];
  605. geometry = instance.geometry;
  606. rectangle = getRectangle(frameState, geometry);
  607. if (ShadowVolumeAppearance.shouldUseSphericalCoordinates(rectangle)) {
  608. usePlanarExtents = false;
  609. break;
  610. }
  611. }
  612. for (i = 0; i < length; ++i) {
  613. instance = instances[i];
  614. geometry = instance.geometry;
  615. instanceType = geometry.constructor;
  616. var boundingRectangle = getRectangle(frameState, geometry);
  617. var textureCoordinateRotationPoints = geometry.textureCoordinateRotationPoints;
  618. var useFloatBatchTable = frameState.context.floatTextureSixPlaces;
  619. if (usePlanarExtents) {
  620. attributes = ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes(boundingRectangle, textureCoordinateRotationPoints, ellipsoid, frameState.mapProjection, useFloatBatchTable, this._maxHeight);
  621. } else {
  622. attributes = ShadowVolumeAppearance.getSphericalExtentGeometryInstanceAttributes(boundingRectangle, textureCoordinateRotationPoints, ellipsoid, frameState.mapProjection, useFloatBatchTable);
  623. }
  624. var instanceAttributes = instance.attributes;
  625. for (var attributeKey in instanceAttributes) {
  626. if (instanceAttributes.hasOwnProperty(attributeKey)) {
  627. attributes[attributeKey] = instanceAttributes[attributeKey];
  628. }
  629. }
  630. groundInstances[i] = new GeometryInstance({
  631. geometry : instanceType.createShadowVolume(geometry, getComputeMinimumHeightFunction(this),
  632. getComputeMaximumHeightFunction(this)),
  633. attributes : attributes,
  634. id : instance.id
  635. });
  636. }
  637. } else {
  638. // ClassificationPrimitive will check if the colors are all the same if it detects lack of fragment culling attributes
  639. for (i = 0; i < length; ++i) {
  640. instance = instances[i];
  641. geometry = instance.geometry;
  642. instanceType = geometry.constructor;
  643. groundInstances[i] = new GeometryInstance({
  644. geometry : instanceType.createShadowVolume(geometry, getComputeMinimumHeightFunction(this),
  645. getComputeMaximumHeightFunction(this)),
  646. attributes : instance.attributes,
  647. id : instance.id
  648. });
  649. }
  650. }
  651. primitiveOptions.geometryInstances = groundInstances;
  652. primitiveOptions.appearance = this.appearance;
  653. primitiveOptions._createBoundingVolumeFunction = function(frameState, geometry) {
  654. createBoundingVolume(that, frameState, geometry);
  655. };
  656. primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume, twoPasses) {
  657. updateAndQueueCommands(that, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume, twoPasses);
  658. };
  659. this._primitive = new ClassificationPrimitive(primitiveOptions);
  660. this._primitive.readyPromise.then(function(primitive) {
  661. that._ready = true;
  662. if (that.releaseGeometryInstances) {
  663. that.geometryInstances = undefined;
  664. }
  665. var error = primitive._error;
  666. if (!defined(error)) {
  667. that._readyPromise.resolve(that);
  668. } else {
  669. that._readyPromise.reject(error);
  670. }
  671. });
  672. }
  673. this._primitive.appearance = this.appearance;
  674. this._primitive.show = this.show;
  675. this._primitive.debugShowShadowVolume = this.debugShowShadowVolume;
  676. this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
  677. this._primitive.update(frameState);
  678. };
  679. /**
  680. * @private
  681. */
  682. GroundPrimitive.prototype.getBoundingSphere = function(id) {
  683. var index = this._boundingSpheresKeys.indexOf(id);
  684. if (index !== -1) {
  685. return this._boundingSpheres[index];
  686. }
  687. return undefined;
  688. };
  689. /**
  690. * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
  691. *
  692. * @param {*} id The id of the {@link GeometryInstance}.
  693. * @returns {Object} The typed array in the attribute's format or undefined if the is no instance with id.
  694. *
  695. * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
  696. *
  697. * @example
  698. * var attributes = primitive.getGeometryInstanceAttributes('an id');
  699. * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
  700. * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
  701. */
  702. GroundPrimitive.prototype.getGeometryInstanceAttributes = function(id) {
  703. //>>includeStart('debug', pragmas.debug);
  704. if (!defined(this._primitive)) {
  705. throw new DeveloperError('must call update before calling getGeometryInstanceAttributes');
  706. }
  707. //>>includeEnd('debug');
  708. return this._primitive.getGeometryInstanceAttributes(id);
  709. };
  710. /**
  711. * Returns true if this object was destroyed; otherwise, false.
  712. * <p>
  713. * If this object was destroyed, it should not be used; calling any function other than
  714. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  715. * </p>
  716. *
  717. * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  718. *
  719. * @see GroundPrimitive#destroy
  720. */
  721. GroundPrimitive.prototype.isDestroyed = function() {
  722. return false;
  723. };
  724. /**
  725. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  726. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  727. * <p>
  728. * Once an object is destroyed, it should not be used; calling any function other than
  729. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  730. * assign the return value (<code>undefined</code>) to the object as done in the example.
  731. * </p>
  732. *
  733. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  734. *
  735. * @example
  736. * e = e && e.destroy();
  737. *
  738. * @see GroundPrimitive#isDestroyed
  739. */
  740. GroundPrimitive.prototype.destroy = function() {
  741. this._primitive = this._primitive && this._primitive.destroy();
  742. return destroyObject(this);
  743. };
  744. /**
  745. * Exposed for testing.
  746. *
  747. * @param {Context} context Rendering context
  748. * @returns {Boolean} Whether or not the current context supports materials on GroundPrimitives.
  749. * @private
  750. */
  751. GroundPrimitive._supportsMaterials = function(context) {
  752. return context.depthTexture;
  753. };
  754. /**
  755. * Checks if the given Scene supports materials on GroundPrimitives.
  756. * Materials on GroundPrimitives require support for the WEBGL_depth_texture extension.
  757. *
  758. * @param {Scene} scene The current scene.
  759. * @returns {Boolean} Whether or not the current scene supports materials on GroundPrimitives.
  760. */
  761. GroundPrimitive.supportsMaterials = function(scene) {
  762. //>>includeStart('debug', pragmas.debug);
  763. Check.typeOf.object('scene', scene);
  764. //>>includeEnd('debug');
  765. return GroundPrimitive._supportsMaterials(scene.frameState.context);
  766. };
  767. export default GroundPrimitive;