Globe.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  1. import BoundingSphere from "../Core/BoundingSphere.js";
  2. import buildModuleUrl from "../Core/buildModuleUrl.js";
  3. import Cartesian3 from "../Core/Cartesian3.js";
  4. import Cartographic from "../Core/Cartographic.js";
  5. import Color from "../Core/Color.js";
  6. import defaultValue from "../Core/defaultValue.js";
  7. import defined from "../Core/defined.js";
  8. import destroyObject from "../Core/destroyObject.js";
  9. import DeveloperError from "../Core/DeveloperError.js";
  10. import Ellipsoid from "../Core/Ellipsoid.js";
  11. import EllipsoidTerrainProvider from "../Core/EllipsoidTerrainProvider.js";
  12. import Event from "../Core/Event.js";
  13. import IntersectionTests from "../Core/IntersectionTests.js";
  14. import NearFarScalar from "../Core/NearFarScalar.js";
  15. import Ray from "../Core/Ray.js";
  16. import Rectangle from "../Core/Rectangle.js";
  17. import Resource from "../Core/Resource.js";
  18. import ShaderSource from "../Renderer/ShaderSource.js";
  19. import Texture from "../Renderer/Texture.js";
  20. import GlobeFS from "../Shaders/GlobeFS.js";
  21. import GlobeVS from "../Shaders/GlobeVS.js";
  22. import AtmosphereCommon from "../Shaders/AtmosphereCommon.js";
  23. import GroundAtmosphere from "../Shaders/GroundAtmosphere.js";
  24. import GlobeSurfaceShaderSet from "./GlobeSurfaceShaderSet.js";
  25. import GlobeSurfaceTileProvider from "./GlobeSurfaceTileProvider.js";
  26. import GlobeTranslucency from "./GlobeTranslucency.js";
  27. import ImageryLayerCollection from "./ImageryLayerCollection.js";
  28. import QuadtreePrimitive from "./QuadtreePrimitive.js";
  29. import SceneMode from "./SceneMode.js";
  30. import ShadowMode from "./ShadowMode.js";
  31. /**
  32. * The globe rendered in the scene, including its terrain ({@link Globe#terrainProvider})
  33. * and imagery layers ({@link Globe#imageryLayers}). Access the globe using {@link Scene#globe}.
  34. *
  35. * @alias Globe
  36. * @constructor
  37. *
  38. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] Determines the size and shape of the
  39. * globe.
  40. */
  41. function Globe(ellipsoid) {
  42. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  43. const terrainProvider = new EllipsoidTerrainProvider({
  44. ellipsoid: ellipsoid,
  45. });
  46. const imageryLayerCollection = new ImageryLayerCollection();
  47. this._ellipsoid = ellipsoid;
  48. this._imageryLayerCollection = imageryLayerCollection;
  49. this._surfaceShaderSet = new GlobeSurfaceShaderSet();
  50. this._material = undefined;
  51. this._surface = new QuadtreePrimitive({
  52. tileProvider: new GlobeSurfaceTileProvider({
  53. terrainProvider: terrainProvider,
  54. imageryLayers: imageryLayerCollection,
  55. surfaceShaderSet: this._surfaceShaderSet,
  56. }),
  57. });
  58. this._terrainProvider = terrainProvider;
  59. this._terrainProviderChanged = new Event();
  60. this._undergroundColor = Color.clone(Color.BLACK);
  61. this._undergroundColorAlphaByDistance = new NearFarScalar(
  62. ellipsoid.maximumRadius / 1000.0,
  63. 0.0,
  64. ellipsoid.maximumRadius / 5.0,
  65. 1.0
  66. );
  67. this._translucency = new GlobeTranslucency();
  68. makeShadersDirty(this);
  69. /**
  70. * Determines if the globe will be shown.
  71. *
  72. * @type {Boolean}
  73. * @default true
  74. */
  75. this.show = true;
  76. this._oceanNormalMapResourceDirty = true;
  77. this._oceanNormalMapResource = new Resource({
  78. url: buildModuleUrl("Assets/Textures/waterNormalsSmall.jpg"),
  79. });
  80. /**
  81. * The maximum screen-space error used to drive level-of-detail refinement. Higher
  82. * values will provide better performance but lower visual quality.
  83. *
  84. * @type {Number}
  85. * @default 2
  86. */
  87. this.maximumScreenSpaceError = 2;
  88. /**
  89. * The size of the terrain tile cache, expressed as a number of tiles. Any additional
  90. * tiles beyond this number will be freed, as long as they aren't needed for rendering
  91. * this frame. A larger number will consume more memory but will show detail faster
  92. * when, for example, zooming out and then back in.
  93. *
  94. * @type {Number}
  95. * @default 100
  96. */
  97. this.tileCacheSize = 100;
  98. /**
  99. * Gets or sets the number of loading descendant tiles that is considered "too many".
  100. * If a tile has too many loading descendants, that tile will be loaded and rendered before any of
  101. * its descendants are loaded and rendered. This means more feedback for the user that something
  102. * is happening at the cost of a longer overall load time. Setting this to 0 will cause each
  103. * tile level to be loaded successively, significantly increasing load time. Setting it to a large
  104. * number (e.g. 1000) will minimize the number of tiles that are loaded but tend to make
  105. * detail appear all at once after a long wait.
  106. * @type {Number}
  107. * @default 20
  108. */
  109. this.loadingDescendantLimit = 20;
  110. /**
  111. * Gets or sets a value indicating whether the ancestors of rendered tiles should be preloaded.
  112. * Setting this to true optimizes the zoom-out experience and provides more detail in
  113. * newly-exposed areas when panning. The down side is that it requires loading more tiles.
  114. * @type {Boolean}
  115. * @default true
  116. */
  117. this.preloadAncestors = true;
  118. /**
  119. * Gets or sets a value indicating whether the siblings of rendered tiles should be preloaded.
  120. * Setting this to true causes tiles with the same parent as a rendered tile to be loaded, even
  121. * if they are culled. Setting this to true may provide a better panning experience at the
  122. * cost of loading more tiles.
  123. * @type {Boolean}
  124. * @default false
  125. */
  126. this.preloadSiblings = false;
  127. /**
  128. * The color to use to highlight terrain fill tiles. If undefined, fill tiles are not
  129. * highlighted at all. The alpha value is used to alpha blend with the tile's
  130. * actual color. Because terrain fill tiles do not represent the actual terrain surface,
  131. * it may be useful in some applications to indicate visually that they are not to be trusted.
  132. * @type {Color}
  133. * @default undefined
  134. */
  135. this.fillHighlightColor = undefined;
  136. /**
  137. * Enable lighting the globe with the scene's light source.
  138. *
  139. * @type {Boolean}
  140. * @default false
  141. */
  142. this.enableLighting = false;
  143. /**
  144. * A multiplier to adjust terrain lambert lighting.
  145. * This number is multiplied by the result of <code>czm_getLambertDiffuse</code> in GlobeFS.glsl.
  146. * This only takes effect when <code>enableLighting</code> is <code>true</code>.
  147. *
  148. * @type {Number}
  149. * @default 0.9
  150. */
  151. this.lambertDiffuseMultiplier = 0.9;
  152. /**
  153. * Enable dynamic lighting effects on atmosphere and fog. This only takes effect
  154. * when <code>enableLighting</code> is <code>true</code>.
  155. *
  156. * @type {Boolean}
  157. * @default true
  158. */
  159. this.dynamicAtmosphereLighting = true;
  160. /**
  161. * Whether dynamic atmosphere lighting uses the sun direction instead of the scene's
  162. * light direction. This only takes effect when <code>enableLighting</code> and
  163. * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
  164. *
  165. * @type {Boolean}
  166. * @default false
  167. */
  168. this.dynamicAtmosphereLightingFromSun = false;
  169. /**
  170. * Enable the ground atmosphere, which is drawn over the globe when viewed from a distance between <code>lightingFadeInDistance</code> and <code>lightingFadeOutDistance</code>.
  171. *
  172. * @type {Boolean}
  173. * @default true
  174. */
  175. this.showGroundAtmosphere = true;
  176. /**
  177. * The intensity of the light that is used for computing the ground atmosphere color.
  178. *
  179. * @type {Number}
  180. * @default 10.0
  181. */
  182. this.atmosphereLightIntensity = 10.0;
  183. /**
  184. * The Rayleigh scattering coefficient used in the atmospheric scattering equations for the ground atmosphere.
  185. *
  186. * @type {Cartesian3}
  187. * @default Cartesian3(5.5e-6, 13.0e-6, 28.4e-6)
  188. */
  189. this.atmosphereRayleighCoefficient = new Cartesian3(5.5e-6, 13.0e-6, 28.4e-6);
  190. /**
  191. * The Mie scattering coefficient used in the atmospheric scattering equations for the ground atmosphere.
  192. *
  193. * @type {Cartesian3}
  194. * @default Cartesian3(21e-6, 21e-6, 21e-6)
  195. */
  196. this.atmosphereMieCoefficient = new Cartesian3(21e-6, 21e-6, 21e-6);
  197. /**
  198. * The Rayleigh scale height used in the atmospheric scattering equations for the ground atmosphere, in meters.
  199. *
  200. * @type {Number}
  201. * @default 10000.0
  202. */
  203. this.atmosphereRayleighScaleHeight = 10000.0;
  204. /**
  205. * The Mie scale height used in the atmospheric scattering equations for the ground atmosphere, in meters.
  206. *
  207. * @type {Number}
  208. * @default 3200.0
  209. */
  210. this.atmosphereMieScaleHeight = 3200.0;
  211. /**
  212. * The anisotropy of the medium to consider for Mie scattering.
  213. * <p>
  214. * Valid values are between -1.0 and 1.0.
  215. * </p>
  216. * @type {Number}
  217. * @default 0.9
  218. */
  219. this.atmosphereMieAnisotropy = 0.9;
  220. /**
  221. * The distance where everything becomes lit. This only takes effect
  222. * when <code>enableLighting</code> or <code>showGroundAtmosphere</code> is <code>true</code>.
  223. *
  224. * @type {Number}
  225. * @default 10000000.0
  226. */
  227. this.lightingFadeOutDistance = 1.0e7;
  228. /**
  229. * The distance where lighting resumes. This only takes effect
  230. * when <code>enableLighting</code> or <code>showGroundAtmosphere</code> is <code>true</code>.
  231. *
  232. * @type {Number}
  233. * @default 20000000.0
  234. */
  235. this.lightingFadeInDistance = 2.0e7;
  236. /**
  237. * The distance where the darkness of night from the ground atmosphere fades out to a lit ground atmosphere.
  238. * This only takes effect when <code>showGroundAtmosphere</code>, <code>enableLighting</code>, and
  239. * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
  240. *
  241. * @type {Number}
  242. * @default 10000000.0
  243. */
  244. this.nightFadeOutDistance = 1.0e7;
  245. /**
  246. * The distance where the darkness of night from the ground atmosphere fades in to an unlit ground atmosphere.
  247. * This only takes effect when <code>showGroundAtmosphere</code>, <code>enableLighting</code>, and
  248. * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
  249. *
  250. * @type {Number}
  251. * @default 50000000.0
  252. */
  253. this.nightFadeInDistance = 5.0e7;
  254. /**
  255. * True if an animated wave effect should be shown in areas of the globe
  256. * covered by water; otherwise, false. This property is ignored if the
  257. * <code>terrainProvider</code> does not provide a water mask.
  258. *
  259. * @type {Boolean}
  260. * @default true
  261. */
  262. this.showWaterEffect = true;
  263. /**
  264. * True if primitives such as billboards, polylines, labels, etc. should be depth-tested
  265. * against the terrain surface, or false if such primitives should always be drawn on top
  266. * of terrain unless they're on the opposite side of the globe. The disadvantage of depth
  267. * testing primitives against terrain is that slight numerical noise or terrain level-of-detail
  268. * switched can sometimes make a primitive that should be on the surface disappear underneath it.
  269. *
  270. * @type {Boolean}
  271. * @default false
  272. *
  273. */
  274. this.depthTestAgainstTerrain = false;
  275. /**
  276. * Determines whether the globe casts or receives shadows from light sources. Setting the globe
  277. * to cast shadows may impact performance since the terrain is rendered again from the light's perspective.
  278. * Currently only terrain that is in view casts shadows. By default the globe does not cast shadows.
  279. *
  280. * @type {ShadowMode}
  281. * @default ShadowMode.RECEIVE_ONLY
  282. */
  283. this.shadows = ShadowMode.RECEIVE_ONLY;
  284. /**
  285. * The hue shift to apply to the atmosphere. Defaults to 0.0 (no shift).
  286. * A hue shift of 1.0 indicates a complete rotation of the hues available.
  287. * @type {Number}
  288. * @default 0.0
  289. */
  290. this.atmosphereHueShift = 0.0;
  291. /**
  292. * The saturation shift to apply to the atmosphere. Defaults to 0.0 (no shift).
  293. * A saturation shift of -1.0 is monochrome.
  294. * @type {Number}
  295. * @default 0.0
  296. */
  297. this.atmosphereSaturationShift = 0.0;
  298. /**
  299. * The brightness shift to apply to the atmosphere. Defaults to 0.0 (no shift).
  300. * A brightness shift of -1.0 is complete darkness, which will let space show through.
  301. * @type {Number}
  302. * @default 0.0
  303. */
  304. this.atmosphereBrightnessShift = 0.0;
  305. /**
  306. * A scalar used to exaggerate the terrain. Defaults to <code>1.0</code> (no exaggeration).
  307. * A value of <code>2.0</code> scales the terrain by 2x.
  308. * A value of <code>0.0</code> makes the terrain completely flat.
  309. * Note that terrain exaggeration will not modify any other primitive as they are positioned relative to the ellipsoid.
  310. * @type {Number}
  311. * @default 1.0
  312. */
  313. this.terrainExaggeration = 1.0;
  314. /**
  315. * The height from which terrain is exaggerated. Defaults to <code>0.0</code> (scaled relative to ellipsoid surface).
  316. * Terrain that is above this height will scale upwards and terrain that is below this height will scale downwards.
  317. * Note that terrain exaggeration will not modify any other primitive as they are positioned relative to the ellipsoid.
  318. * If {@link Globe#terrainExaggeration} is <code>1.0</code> this value will have no effect.
  319. * @type {Number}
  320. * @default 0.0
  321. */
  322. this.terrainExaggerationRelativeHeight = 0.0;
  323. /**
  324. * Whether to show terrain skirts. Terrain skirts are geometry extending downwards from a tile's edges used to hide seams between neighboring tiles.
  325. * Skirts are always hidden when the camera is underground or translucency is enabled.
  326. *
  327. * @type {Boolean}
  328. * @default true
  329. */
  330. this.showSkirts = true;
  331. /**
  332. * Whether to cull back-facing terrain. Back faces are not culled when the camera is underground or translucency is enabled.
  333. *
  334. * @type {Boolean}
  335. * @default true
  336. */
  337. this.backFaceCulling = true;
  338. this._oceanNormalMap = undefined;
  339. this._zoomedOutOceanSpecularIntensity = undefined;
  340. }
  341. Object.defineProperties(Globe.prototype, {
  342. /**
  343. * Gets an ellipsoid describing the shape of this globe.
  344. * @memberof Globe.prototype
  345. * @type {Ellipsoid}
  346. */
  347. ellipsoid: {
  348. get: function () {
  349. return this._ellipsoid;
  350. },
  351. },
  352. /**
  353. * Gets the collection of image layers that will be rendered on this globe.
  354. * @memberof Globe.prototype
  355. * @type {ImageryLayerCollection}
  356. */
  357. imageryLayers: {
  358. get: function () {
  359. return this._imageryLayerCollection;
  360. },
  361. },
  362. /**
  363. * Gets an event that's raised when an imagery layer is added, shown, hidden, moved, or removed.
  364. *
  365. * @memberof Globe.prototype
  366. * @type {Event}
  367. * @readonly
  368. */
  369. imageryLayersUpdatedEvent: {
  370. get: function () {
  371. return this._surface.tileProvider.imageryLayersUpdatedEvent;
  372. },
  373. },
  374. /**
  375. * Returns <code>true</code> when the tile load queue is empty, <code>false</code> otherwise. When the load queue is empty,
  376. * all terrain and imagery for the current view have been loaded.
  377. * @memberof Globe.prototype
  378. * @type {Boolean}
  379. * @readonly
  380. */
  381. tilesLoaded: {
  382. get: function () {
  383. if (!defined(this._surface)) {
  384. return true;
  385. }
  386. return (
  387. this._surface.tileProvider.ready &&
  388. this._surface._tileLoadQueueHigh.length === 0 &&
  389. this._surface._tileLoadQueueMedium.length === 0 &&
  390. this._surface._tileLoadQueueLow.length === 0
  391. );
  392. },
  393. },
  394. /**
  395. * Gets or sets the color of the globe when no imagery is available.
  396. * @memberof Globe.prototype
  397. * @type {Color}
  398. */
  399. baseColor: {
  400. get: function () {
  401. return this._surface.tileProvider.baseColor;
  402. },
  403. set: function (value) {
  404. this._surface.tileProvider.baseColor = value;
  405. },
  406. },
  407. /**
  408. * A property specifying a {@link ClippingPlaneCollection} used to selectively disable rendering on the outside of each plane.
  409. *
  410. * @memberof Globe.prototype
  411. * @type {ClippingPlaneCollection}
  412. */
  413. clippingPlanes: {
  414. get: function () {
  415. return this._surface.tileProvider.clippingPlanes;
  416. },
  417. set: function (value) {
  418. this._surface.tileProvider.clippingPlanes = value;
  419. },
  420. },
  421. /**
  422. * A property specifying a {@link Rectangle} used to limit globe rendering to a cartographic area.
  423. * Defaults to the maximum extent of cartographic coordinates.
  424. *
  425. * @memberof Globe.prototype
  426. * @type {Rectangle}
  427. * @default {@link Rectangle.MAX_VALUE}
  428. */
  429. cartographicLimitRectangle: {
  430. get: function () {
  431. return this._surface.tileProvider.cartographicLimitRectangle;
  432. },
  433. set: function (value) {
  434. if (!defined(value)) {
  435. value = Rectangle.clone(Rectangle.MAX_VALUE);
  436. }
  437. this._surface.tileProvider.cartographicLimitRectangle = value;
  438. },
  439. },
  440. /**
  441. * The normal map to use for rendering waves in the ocean. Setting this property will
  442. * only have an effect if the configured terrain provider includes a water mask.
  443. * @memberof Globe.prototype
  444. * @type {String}
  445. * @default buildModuleUrl('Assets/Textures/waterNormalsSmall.jpg')
  446. */
  447. oceanNormalMapUrl: {
  448. get: function () {
  449. return this._oceanNormalMapResource.url;
  450. },
  451. set: function (value) {
  452. this._oceanNormalMapResource.url = value;
  453. this._oceanNormalMapResourceDirty = true;
  454. },
  455. },
  456. /**
  457. * The terrain provider providing surface geometry for this globe.
  458. * @type {TerrainProvider}
  459. *
  460. * @memberof Globe.prototype
  461. * @type {TerrainProvider}
  462. *
  463. */
  464. terrainProvider: {
  465. get: function () {
  466. return this._terrainProvider;
  467. },
  468. set: function (value) {
  469. if (value !== this._terrainProvider) {
  470. this._terrainProvider = value;
  471. this._terrainProviderChanged.raiseEvent(value);
  472. if (defined(this._material)) {
  473. makeShadersDirty(this);
  474. }
  475. }
  476. },
  477. },
  478. /**
  479. * Gets an event that's raised when the terrain provider is changed
  480. *
  481. * @memberof Globe.prototype
  482. * @type {Event}
  483. * @readonly
  484. */
  485. terrainProviderChanged: {
  486. get: function () {
  487. return this._terrainProviderChanged;
  488. },
  489. },
  490. /**
  491. * Gets an event that's raised when the length of the tile load queue has changed since the last render frame. When the load queue is empty,
  492. * all terrain and imagery for the current view have been loaded. The event passes the new length of the tile load queue.
  493. *
  494. * @memberof Globe.prototype
  495. * @type {Event}
  496. */
  497. tileLoadProgressEvent: {
  498. get: function () {
  499. return this._surface.tileLoadProgressEvent;
  500. },
  501. },
  502. /**
  503. * Gets or sets the material appearance of the Globe. This can be one of several built-in {@link Material} objects or a custom material, scripted with
  504. * {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}.
  505. * @memberof Globe.prototype
  506. * @type {Material | undefined}
  507. */
  508. material: {
  509. get: function () {
  510. return this._material;
  511. },
  512. set: function (material) {
  513. if (this._material !== material) {
  514. this._material = material;
  515. makeShadersDirty(this);
  516. }
  517. },
  518. },
  519. /**
  520. * The color to render the back side of the globe when the camera is underground or the globe is translucent,
  521. * blended with the globe color based on the camera's distance.
  522. * <br /><br />
  523. * To disable underground coloring, set <code>undergroundColor</code> to <code>undefined</code>.
  524. *
  525. * @memberof Globe.prototype
  526. * @type {Color}
  527. * @default {@link Color.BLACK}
  528. *
  529. * @see Globe#undergroundColorAlphaByDistance
  530. */
  531. undergroundColor: {
  532. get: function () {
  533. return this._undergroundColor;
  534. },
  535. set: function (value) {
  536. this._undergroundColor = Color.clone(value, this._undergroundColor);
  537. },
  538. },
  539. /**
  540. * Gets or sets the near and far distance for blending {@link Globe#undergroundColor} with the globe color.
  541. * The alpha will interpolate between the {@link NearFarScalar#nearValue} and
  542. * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
  543. * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
  544. * Outside of these ranges the alpha remains clamped to the nearest bound. If undefined,
  545. * the underground color will not be blended with the globe color.
  546. * <br /> <br />
  547. * When the camera is above the ellipsoid the distance is computed from the nearest
  548. * point on the ellipsoid instead of the camera's position.
  549. *
  550. * @memberof Globe.prototype
  551. * @type {NearFarScalar}
  552. *
  553. * @see Globe#undergroundColor
  554. *
  555. */
  556. undergroundColorAlphaByDistance: {
  557. get: function () {
  558. return this._undergroundColorAlphaByDistance;
  559. },
  560. set: function (value) {
  561. //>>includeStart('debug', pragmas.debug);
  562. if (defined(value) && value.far < value.near) {
  563. throw new DeveloperError(
  564. "far distance must be greater than near distance."
  565. );
  566. }
  567. //>>includeEnd('debug');
  568. this._undergroundColorAlphaByDistance = NearFarScalar.clone(
  569. value,
  570. this._undergroundColorAlphaByDistance
  571. );
  572. },
  573. },
  574. /**
  575. * Properties for controlling globe translucency.
  576. *
  577. * @memberof Globe.prototype
  578. * @type {GlobeTranslucency}
  579. */
  580. translucency: {
  581. get: function () {
  582. return this._translucency;
  583. },
  584. },
  585. });
  586. function makeShadersDirty(globe) {
  587. const defines = [];
  588. const requireNormals =
  589. defined(globe._material) &&
  590. (globe._material.shaderSource.match(/slope/) ||
  591. globe._material.shaderSource.match("normalEC"));
  592. const fragmentSources = [AtmosphereCommon, GroundAtmosphere];
  593. if (
  594. defined(globe._material) &&
  595. (!requireNormals || globe._terrainProvider.requestVertexNormals)
  596. ) {
  597. fragmentSources.push(globe._material.shaderSource);
  598. defines.push("APPLY_MATERIAL");
  599. globe._surface._tileProvider.materialUniformMap = globe._material._uniforms;
  600. } else {
  601. globe._surface._tileProvider.materialUniformMap = undefined;
  602. }
  603. fragmentSources.push(GlobeFS);
  604. globe._surfaceShaderSet.baseVertexShaderSource = new ShaderSource({
  605. sources: [AtmosphereCommon, GroundAtmosphere, GlobeVS],
  606. defines: defines,
  607. });
  608. globe._surfaceShaderSet.baseFragmentShaderSource = new ShaderSource({
  609. sources: fragmentSources,
  610. defines: defines,
  611. });
  612. globe._surfaceShaderSet.material = globe._material;
  613. }
  614. function createComparePickTileFunction(rayOrigin) {
  615. return function (a, b) {
  616. const aDist = BoundingSphere.distanceSquaredTo(
  617. a.pickBoundingSphere,
  618. rayOrigin
  619. );
  620. const bDist = BoundingSphere.distanceSquaredTo(
  621. b.pickBoundingSphere,
  622. rayOrigin
  623. );
  624. return aDist - bDist;
  625. };
  626. }
  627. const scratchArray = [];
  628. const scratchSphereIntersectionResult = {
  629. start: 0.0,
  630. stop: 0.0,
  631. };
  632. /**
  633. * Find an intersection between a ray and the globe surface that was rendered. The ray must be given in world coordinates.
  634. *
  635. * @param {Ray} ray The ray to test for intersection.
  636. * @param {Scene} scene The scene.
  637. * @param {Boolean} [cullBackFaces=true] Set to true to not pick back faces.
  638. * @param {Cartesian3} [result] The object onto which to store the result.
  639. * @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found. The returned position is in projected coordinates for 2D and Columbus View.
  640. *
  641. * @private
  642. */
  643. Globe.prototype.pickWorldCoordinates = function (
  644. ray,
  645. scene,
  646. cullBackFaces,
  647. result
  648. ) {
  649. //>>includeStart('debug', pragmas.debug);
  650. if (!defined(ray)) {
  651. throw new DeveloperError("ray is required");
  652. }
  653. if (!defined(scene)) {
  654. throw new DeveloperError("scene is required");
  655. }
  656. //>>includeEnd('debug');
  657. cullBackFaces = defaultValue(cullBackFaces, true);
  658. const mode = scene.mode;
  659. const projection = scene.mapProjection;
  660. const sphereIntersections = scratchArray;
  661. sphereIntersections.length = 0;
  662. const tilesToRender = this._surface._tilesToRender;
  663. let length = tilesToRender.length;
  664. let tile;
  665. let i;
  666. for (i = 0; i < length; ++i) {
  667. tile = tilesToRender[i];
  668. const surfaceTile = tile.data;
  669. if (!defined(surfaceTile)) {
  670. continue;
  671. }
  672. let boundingVolume = surfaceTile.pickBoundingSphere;
  673. if (mode !== SceneMode.SCENE3D) {
  674. surfaceTile.pickBoundingSphere = boundingVolume = BoundingSphere.fromRectangleWithHeights2D(
  675. tile.rectangle,
  676. projection,
  677. surfaceTile.tileBoundingRegion.minimumHeight,
  678. surfaceTile.tileBoundingRegion.maximumHeight,
  679. boundingVolume
  680. );
  681. Cartesian3.fromElements(
  682. boundingVolume.center.z,
  683. boundingVolume.center.x,
  684. boundingVolume.center.y,
  685. boundingVolume.center
  686. );
  687. } else if (defined(surfaceTile.renderedMesh)) {
  688. BoundingSphere.clone(
  689. surfaceTile.tileBoundingRegion.boundingSphere,
  690. boundingVolume
  691. );
  692. } else {
  693. // So wait how did we render this thing then? It shouldn't be possible to get here.
  694. continue;
  695. }
  696. const boundingSphereIntersection = IntersectionTests.raySphere(
  697. ray,
  698. boundingVolume,
  699. scratchSphereIntersectionResult
  700. );
  701. if (defined(boundingSphereIntersection)) {
  702. sphereIntersections.push(surfaceTile);
  703. }
  704. }
  705. sphereIntersections.sort(createComparePickTileFunction(ray.origin));
  706. let intersection;
  707. length = sphereIntersections.length;
  708. for (i = 0; i < length; ++i) {
  709. intersection = sphereIntersections[i].pick(
  710. ray,
  711. scene.mode,
  712. scene.mapProjection,
  713. cullBackFaces,
  714. result
  715. );
  716. if (defined(intersection)) {
  717. break;
  718. }
  719. }
  720. return intersection;
  721. };
  722. const cartoScratch = new Cartographic();
  723. /**
  724. * Find an intersection between a ray and the globe surface that was rendered. The ray must be given in world coordinates.
  725. *
  726. * @param {Ray} ray The ray to test for intersection.
  727. * @param {Scene} scene The scene.
  728. * @param {Cartesian3} [result] The object onto which to store the result.
  729. * @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found.
  730. *
  731. * @example
  732. * // find intersection of ray through a pixel and the globe
  733. * const ray = viewer.camera.getPickRay(windowCoordinates);
  734. * const intersection = globe.pick(ray, scene);
  735. */
  736. Globe.prototype.pick = function (ray, scene, result) {
  737. result = this.pickWorldCoordinates(ray, scene, true, result);
  738. if (defined(result) && scene.mode !== SceneMode.SCENE3D) {
  739. result = Cartesian3.fromElements(result.y, result.z, result.x, result);
  740. const carto = scene.mapProjection.unproject(result, cartoScratch);
  741. result = scene.globe.ellipsoid.cartographicToCartesian(carto, result);
  742. }
  743. return result;
  744. };
  745. const scratchGetHeightCartesian = new Cartesian3();
  746. const scratchGetHeightIntersection = new Cartesian3();
  747. const scratchGetHeightCartographic = new Cartographic();
  748. const scratchGetHeightRay = new Ray();
  749. function tileIfContainsCartographic(tile, cartographic) {
  750. return defined(tile) && Rectangle.contains(tile.rectangle, cartographic)
  751. ? tile
  752. : undefined;
  753. }
  754. /**
  755. * Get the height of the surface at a given cartographic.
  756. *
  757. * @param {Cartographic} cartographic The cartographic for which to find the height.
  758. * @returns {Number|undefined} The height of the cartographic or undefined if it could not be found.
  759. */
  760. Globe.prototype.getHeight = function (cartographic) {
  761. //>>includeStart('debug', pragmas.debug);
  762. if (!defined(cartographic)) {
  763. throw new DeveloperError("cartographic is required");
  764. }
  765. //>>includeEnd('debug');
  766. const levelZeroTiles = this._surface._levelZeroTiles;
  767. if (!defined(levelZeroTiles)) {
  768. return;
  769. }
  770. let tile;
  771. let i;
  772. const length = levelZeroTiles.length;
  773. for (i = 0; i < length; ++i) {
  774. tile = levelZeroTiles[i];
  775. if (Rectangle.contains(tile.rectangle, cartographic)) {
  776. break;
  777. }
  778. }
  779. if (i >= length) {
  780. return undefined;
  781. }
  782. let tileWithMesh = tile;
  783. while (defined(tile)) {
  784. tile =
  785. tileIfContainsCartographic(tile._southwestChild, cartographic) ||
  786. tileIfContainsCartographic(tile._southeastChild, cartographic) ||
  787. tileIfContainsCartographic(tile._northwestChild, cartographic) ||
  788. tile._northeastChild;
  789. if (
  790. defined(tile) &&
  791. defined(tile.data) &&
  792. defined(tile.data.renderedMesh)
  793. ) {
  794. tileWithMesh = tile;
  795. }
  796. }
  797. tile = tileWithMesh;
  798. // This tile was either rendered or culled.
  799. // It is sometimes useful to get a height from a culled tile,
  800. // e.g. when we're getting a height in order to place a billboard
  801. // on terrain, and the camera is looking at that same billboard.
  802. // The culled tile must have a valid mesh, though.
  803. if (
  804. !defined(tile) ||
  805. !defined(tile.data) ||
  806. !defined(tile.data.renderedMesh)
  807. ) {
  808. // Tile was not rendered (culled).
  809. return undefined;
  810. }
  811. const projection = this._surface._tileProvider.tilingScheme.projection;
  812. const ellipsoid = this._surface._tileProvider.tilingScheme.ellipsoid;
  813. //cartesian has to be on the ellipsoid surface for `ellipsoid.geodeticSurfaceNormal`
  814. const cartesian = Cartesian3.fromRadians(
  815. cartographic.longitude,
  816. cartographic.latitude,
  817. 0.0,
  818. ellipsoid,
  819. scratchGetHeightCartesian
  820. );
  821. const ray = scratchGetHeightRay;
  822. const surfaceNormal = ellipsoid.geodeticSurfaceNormal(
  823. cartesian,
  824. ray.direction
  825. );
  826. // Try to find the intersection point between the surface normal and z-axis.
  827. // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
  828. const rayOrigin = ellipsoid.getSurfaceNormalIntersectionWithZAxis(
  829. cartesian,
  830. 11500.0,
  831. ray.origin
  832. );
  833. // Theoretically, not with Earth datums, the intersection point can be outside the ellipsoid
  834. if (!defined(rayOrigin)) {
  835. // intersection point is outside the ellipsoid, try other value
  836. // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
  837. let minimumHeight;
  838. if (defined(tile.data.tileBoundingRegion)) {
  839. minimumHeight = tile.data.tileBoundingRegion.minimumHeight;
  840. }
  841. const magnitude = Math.min(defaultValue(minimumHeight, 0.0), -11500.0);
  842. // multiply by the *positive* value of the magnitude
  843. const vectorToMinimumPoint = Cartesian3.multiplyByScalar(
  844. surfaceNormal,
  845. Math.abs(magnitude) + 1,
  846. scratchGetHeightIntersection
  847. );
  848. Cartesian3.subtract(cartesian, vectorToMinimumPoint, ray.origin);
  849. }
  850. const intersection = tile.data.pick(
  851. ray,
  852. undefined,
  853. projection,
  854. false,
  855. scratchGetHeightIntersection
  856. );
  857. if (!defined(intersection)) {
  858. return undefined;
  859. }
  860. return ellipsoid.cartesianToCartographic(
  861. intersection,
  862. scratchGetHeightCartographic
  863. ).height;
  864. };
  865. /**
  866. * @private
  867. */
  868. Globe.prototype.update = function (frameState) {
  869. if (!this.show) {
  870. return;
  871. }
  872. if (frameState.passes.render) {
  873. this._surface.update(frameState);
  874. }
  875. };
  876. /**
  877. * @private
  878. */
  879. Globe.prototype.beginFrame = function (frameState) {
  880. const surface = this._surface;
  881. const tileProvider = surface.tileProvider;
  882. const terrainProvider = this.terrainProvider;
  883. const hasWaterMask =
  884. this.showWaterEffect &&
  885. terrainProvider.ready &&
  886. terrainProvider.hasWaterMask;
  887. if (hasWaterMask && this._oceanNormalMapResourceDirty) {
  888. // url changed, load new normal map asynchronously
  889. this._oceanNormalMapResourceDirty = false;
  890. const oceanNormalMapResource = this._oceanNormalMapResource;
  891. const oceanNormalMapUrl = oceanNormalMapResource.url;
  892. if (defined(oceanNormalMapUrl)) {
  893. const that = this;
  894. oceanNormalMapResource.fetchImage().then(function (image) {
  895. if (oceanNormalMapUrl !== that._oceanNormalMapResource.url) {
  896. // url changed while we were loading
  897. return;
  898. }
  899. that._oceanNormalMap =
  900. that._oceanNormalMap && that._oceanNormalMap.destroy();
  901. that._oceanNormalMap = new Texture({
  902. context: frameState.context,
  903. source: image,
  904. });
  905. });
  906. } else {
  907. this._oceanNormalMap =
  908. this._oceanNormalMap && this._oceanNormalMap.destroy();
  909. }
  910. }
  911. const pass = frameState.passes;
  912. const mode = frameState.mode;
  913. if (pass.render) {
  914. if (this.showGroundAtmosphere) {
  915. this._zoomedOutOceanSpecularIntensity = 0.4;
  916. } else {
  917. this._zoomedOutOceanSpecularIntensity = 0.5;
  918. }
  919. surface.maximumScreenSpaceError = this.maximumScreenSpaceError;
  920. surface.tileCacheSize = this.tileCacheSize;
  921. surface.loadingDescendantLimit = this.loadingDescendantLimit;
  922. surface.preloadAncestors = this.preloadAncestors;
  923. surface.preloadSiblings = this.preloadSiblings;
  924. tileProvider.terrainProvider = this.terrainProvider;
  925. tileProvider.lightingFadeOutDistance = this.lightingFadeOutDistance;
  926. tileProvider.lightingFadeInDistance = this.lightingFadeInDistance;
  927. tileProvider.nightFadeOutDistance = this.nightFadeOutDistance;
  928. tileProvider.nightFadeInDistance = this.nightFadeInDistance;
  929. tileProvider.zoomedOutOceanSpecularIntensity =
  930. mode === SceneMode.SCENE3D ? this._zoomedOutOceanSpecularIntensity : 0.0;
  931. tileProvider.hasWaterMask = hasWaterMask;
  932. tileProvider.oceanNormalMap = this._oceanNormalMap;
  933. tileProvider.enableLighting = this.enableLighting;
  934. tileProvider.dynamicAtmosphereLighting = this.dynamicAtmosphereLighting;
  935. tileProvider.dynamicAtmosphereLightingFromSun = this.dynamicAtmosphereLightingFromSun;
  936. tileProvider.showGroundAtmosphere = this.showGroundAtmosphere;
  937. tileProvider.atmosphereLightIntensity = this.atmosphereLightIntensity;
  938. tileProvider.atmosphereRayleighCoefficient = this.atmosphereRayleighCoefficient;
  939. tileProvider.atmosphereMieCoefficient = this.atmosphereMieCoefficient;
  940. tileProvider.atmosphereRayleighScaleHeight = this.atmosphereRayleighScaleHeight;
  941. tileProvider.atmosphereMieScaleHeight = this.atmosphereMieScaleHeight;
  942. tileProvider.atmosphereMieAnisotropy = this.atmosphereMieAnisotropy;
  943. tileProvider.shadows = this.shadows;
  944. tileProvider.hueShift = this.atmosphereHueShift;
  945. tileProvider.saturationShift = this.atmosphereSaturationShift;
  946. tileProvider.brightnessShift = this.atmosphereBrightnessShift;
  947. tileProvider.fillHighlightColor = this.fillHighlightColor;
  948. tileProvider.showSkirts = this.showSkirts;
  949. tileProvider.backFaceCulling = this.backFaceCulling;
  950. tileProvider.undergroundColor = this._undergroundColor;
  951. tileProvider.undergroundColorAlphaByDistance = this._undergroundColorAlphaByDistance;
  952. tileProvider.lambertDiffuseMultiplier = this.lambertDiffuseMultiplier;
  953. surface.beginFrame(frameState);
  954. }
  955. };
  956. /**
  957. * @private
  958. */
  959. Globe.prototype.render = function (frameState) {
  960. if (!this.show) {
  961. return;
  962. }
  963. if (defined(this._material)) {
  964. this._material.update(frameState.context);
  965. }
  966. this._surface.render(frameState);
  967. };
  968. /**
  969. * @private
  970. */
  971. Globe.prototype.endFrame = function (frameState) {
  972. if (!this.show) {
  973. return;
  974. }
  975. if (frameState.passes.render) {
  976. this._surface.endFrame(frameState);
  977. }
  978. };
  979. /**
  980. * Returns true if this object was destroyed; otherwise, false.
  981. * <br /><br />
  982. * If this object was destroyed, it should not be used; calling any function other than
  983. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  984. *
  985. * @returns {Boolean} True if this object was destroyed; otherwise, false.
  986. *
  987. * @see Globe#destroy
  988. */
  989. Globe.prototype.isDestroyed = function () {
  990. return false;
  991. };
  992. /**
  993. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  994. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  995. * <br /><br />
  996. * Once an object is destroyed, it should not be used; calling any function other than
  997. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  998. * assign the return value (<code>undefined</code>) to the object as done in the example.
  999. *
  1000. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  1001. *
  1002. *
  1003. * @example
  1004. * globe = globe && globe.destroy();
  1005. *
  1006. * @see Globe#isDestroyed
  1007. */
  1008. Globe.prototype.destroy = function () {
  1009. this._surfaceShaderSet =
  1010. this._surfaceShaderSet && this._surfaceShaderSet.destroy();
  1011. this._surface = this._surface && this._surface.destroy();
  1012. this._oceanNormalMap = this._oceanNormalMap && this._oceanNormalMap.destroy();
  1013. return destroyObject(this);
  1014. };
  1015. export default Globe;